Browse Source

#297

feature/297
みてるぞ 5 days ago
parent
commit
d39b99f0ab
6 changed files with 294 additions and 48 deletions
  1. +32
    -0
      backend/app/controllers/theatre_comments_controller.rb
  2. +2
    -2
      backend/app/models/theatre_comment.rb
  3. +2
    -0
      backend/config/routes.rb
  4. +6
    -4
      frontend/src/components/TopNav.tsx
  5. +243
    -40
      frontend/src/pages/theatres/TheatreDetailPage.tsx
  6. +9
    -2
      frontend/src/types.ts

+ 32
- 0
backend/app/controllers/theatre_comments_controller.rb View File

@@ -0,0 +1,32 @@
class TheatreCommentsController < ApplicationController
def index
no_gt = params[:no_gt].to_i
no_gt = 0 if no_gt.negative?

comments = TheatreComment
.where(theatre_id: params[:theatre_id])
.where('no > ?', no_gt)
.order(:no)

render json: comments.as_json(include: { user: { only: [:id, :name] } })
end

def create
return head :unauthorized unless current_user

content = params[:content]
return head :unprocessable_entity if content.blank?

theatre = Theatre.find_by(id: params[:theatre_id])
return head :not_found unless theatre

comment = nil
theatre.with_lock do
no = theatre.next_comment_no
comment = TheatreComment.create!(theatre:, no:, user: current_user, content:)
theatre.update!(next_comment_no: no + 1)
end

render json: comment, status: :created
end
end

+ 2
- 2
backend/app/models/theatre_comment.rb View File

@@ -1,8 +1,8 @@
class TheatreComment < ApplicationRecord class TheatreComment < ApplicationRecord
include MyDiscard
include Discard::Model


self.primary_key = :theatre_id, :no self.primary_key = :theatre_id, :no


belongs_to :theatre belongs_to :theatre
belongs_to :user
end end


+ 2
- 0
backend/config/routes.rb View File

@@ -78,5 +78,7 @@ Rails.application.routes.draw do
put :watching put :watching
patch :next_post patch :next_post
end end

resources :comments, controller: :theatre_comments, only: [:index, :create]
end end
end end

+ 6
- 4
frontend/src/components/TopNav.tsx View File

@@ -79,9 +79,11 @@ export default (({ user }: Props) => {
{ name: '上位タグ', to: '/tags/implications', visible: false }, { name: '上位タグ', to: '/tags/implications', visible: false },
{ name: 'ニコニコ連携', to: '/tags/nico' }, { name: 'ニコニコ連携', to: '/tags/nico' },
{ name: 'ヘルプ', to: '/wiki/ヘルプ:タグ' }] }, { name: 'ヘルプ', to: '/wiki/ヘルプ:タグ' }] },
// TODO: 本実装時に消す.
// { name: '上映会', to: '/theatres/1', base: '/theatres', subMenu: [
// { name: '一覧', to: '/theatres' }] },
{ name: '上映会', to: '/theatres/1', base: '/theatres', subMenu: [
{ name: <>第&thinsp;1&thinsp;会場</>, to: '/theatres/1' },
{ name: 'CyTube', to: '//cytube.mm428.net/r/deernijika' },
{ name: <>ニジカ放送局第&thinsp;1&thinsp;チャンネル</>,
to: '//www.youtube.com/watch?v=DCU3hL4Uu6A' }] },
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [ { name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
{ name: '検索', to: '/wiki' }, { name: '検索', to: '/wiki' },
{ name: '新規', to: '/wiki/new' }, { name: '新規', to: '/wiki/new' },
@@ -92,7 +94,7 @@ export default (({ user }: Props) => {
visible: wikiPageFlg }, visible: wikiPageFlg },
{ name: '履歴', to: `/wiki/changes?id=${ wikiId }`, visible: wikiPageFlg }, { name: '履歴', to: `/wiki/changes?id=${ wikiId }`, visible: wikiPageFlg },
{ name: '編輯', to: `/wiki/${ wikiId || wikiTitle }/edit`, visible: wikiPageFlg }] }, { name: '編輯', to: `/wiki/${ wikiId || wikiTitle }/edit`, visible: wikiPageFlg }] },
{ name: 'ユーザ', to: '/users', subMenu: [
{ name: 'ユーザ', to: '/users/settings', subMenu: [
{ name: '一覧', to: '/users', visible: false }, { name: '一覧', to: '/users', visible: false },
{ name: 'お前', to: `/users/${ user?.id }`, visible: false }, { name: 'お前', to: `/users/${ user?.id }`, visible: false },
{ name: '設定', to: '/users/settings', visible: Boolean (user) }] }] { name: '設定', to: '/users/settings', visible: Boolean (user) }] }]


+ 243
- 40
frontend/src/pages/theatres/TheatreDetailPage.tsx View File

@@ -3,84 +3,221 @@ import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom' import { useParams } from 'react-router-dom'


import PostEmbed from '@/components/PostEmbed' import PostEmbed from '@/components/PostEmbed'
import PrefetchLink from '@/components/PrefetchLink'
import TagDetailSidebar from '@/components/TagDetailSidebar'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import SidebarComponent from '@/components/layout/SidebarComponent'
import { SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet, apiPatch, apiPut } from '@/lib/api'
import { apiGet, apiPatch, apiPost, apiPut } from '@/lib/api'
import { fetchPost } from '@/lib/posts' import { fetchPost } from '@/lib/posts'
import { dateString } from '@/lib/utils'


import type { FC } from 'react' import type { FC } from 'react'


import type { NiconicoMetadata, NiconicoViewerHandle, Post, Theatre } from '@/types'
import type { NiconicoMetadata,
NiconicoViewerHandle,
Post,
Theatre,
TheatreComment } from '@/types'


type TheatreInfo = { type TheatreInfo = {
hostFlg: boolean hostFlg: boolean
postId: number | null postId: number | null
postStartedAt: string | null } postStartedAt: string | null }


const INITIAL_THEATRE_INFO = { hostFlg: false, postId: null, postStartedAt: null } as const



export default (() => { export default (() => {
const { id } = useParams () const { id } = useParams ()


const commentsRef = useRef<HTMLDivElement> (null)
const embedRef = useRef<NiconicoViewerHandle> (null) const embedRef = useRef<NiconicoViewerHandle> (null)
const theatreInfoRef = useRef<TheatreInfo> (INITIAL_THEATRE_INFO)
const videoLengthRef = useRef (0)
const lastCommentNoRef = useRef (0)


const [comments, setComments] = useState<TheatreComment[]> ([])
const [content, setContent] = useState ('')
const [loading, setLoading] = useState (false) const [loading, setLoading] = useState (false)
const [sending, setSending] = useState (false)
const [theatre, setTheatre] = useState<Theatre | null> (null) const [theatre, setTheatre] = useState<Theatre | null> (null)
const [theatreInfo, setTheatreInfo] =
useState<TheatreInfo> ({ hostFlg: false, postId: null, postStartedAt: null })
const [theatreInfo, setTheatreInfo] = useState<TheatreInfo> (INITIAL_THEATRE_INFO)
const [post, setPost] = useState<Post | null> (null) const [post, setPost] = useState<Post | null> (null)
const [videoLength, setVideoLength] = useState (9_999_999_999)
const [videoLength, setVideoLength] = useState (0)

useEffect (() => {
theatreInfoRef.current = theatreInfo
}, [theatreInfo])

useEffect (() => {
videoLengthRef.current = videoLength
}, [videoLength])

useEffect (() => {
lastCommentNoRef.current = comments.at (-1)?.no ?? 0
}, [comments])


useEffect (() => { useEffect (() => {
if (!(id)) if (!(id))
return return


let cancelled = false

setComments ([])
setTheatre (null)
setPost (null)
setTheatreInfo (INITIAL_THEATRE_INFO)
setVideoLength (0)
lastCommentNoRef.current = 0

void (async () => { void (async () => {
setTheatre (await apiGet<Theatre> (`/theatres/${ id }`))
try
{
const data = await apiGet<Theatre> (`/theatres/${ id }`)
if (!(cancelled))
setTheatre (data)
}
catch (error)
{
console.error (error)
}
}) () }) ()


const interval = setInterval (async () => {
if (theatreInfo.hostFlg
&& theatreInfo.postStartedAt
&& ((new Date).getTime () - (new Date (theatreInfo.postStartedAt)).getTime ()
> videoLength))
setTheatreInfo ({ hostFlg: true, postId: null, postStartedAt: null })
else
setTheatreInfo (await apiPut<TheatreInfo> (`/theatres/${ id }/watching`))
}, 1_000)
return () => {
cancelled = true
}
}, [id])


return () => clearInterval (interval)
}, [id, theatreInfo.hostFlg, theatreInfo.postStartedAt, videoLength])
useEffect (() => {
commentsRef.current?.scrollTo ({
top: commentsRef.current.scrollHeight,
behavior: 'smooth' })
}, [commentsRef])


useEffect (() => { useEffect (() => {
if (!(theatreInfo.hostFlg) || loading)
if (!(id))
return return


if (theatreInfo.postId == null)
let cancelled = false
let running = false

const tick = async () => {
if (running)
return

running = true

try
{
const newComments = await apiGet<TheatreComment[]> (
`/theatres/${ id }/comments`,
{ params: { no_gt: lastCommentNoRef.current } })

if (!(cancelled) && newComments.length > 0)
{
lastCommentNoRef.current = newComments[newComments.length - 1].no
setComments (prev => [...prev, ...newComments])
}

const currentInfo = theatreInfoRef.current
const ended =
currentInfo.hostFlg
&& currentInfo.postStartedAt
&& ((Date.now () - (new Date (currentInfo.postStartedAt)).getTime ())
> videoLengthRef.current + 3_000)

if (ended)
{
if (!(cancelled))
setTheatreInfo (prev => ({ ...prev, postId: null, postStartedAt: null }))

return
}

const nextInfo = await apiPut<TheatreInfo> (`/theatres/${ id }/watching`)
if (!(cancelled))
setTheatreInfo (nextInfo)
}
catch (error)
{
console.error (error)
}
finally
{ {
void (async () => {
setLoading (true)
await apiPatch<void> (`/theatres/${ id }/next_post`)
running = false
}
}

tick ()
const interval = setInterval (() => tick (), 1_000)

return () => {
cancelled = true
clearInterval (interval)
}
}, [id])

useEffect (() => {
if (!(id) || !(theatreInfo.hostFlg) || loading || theatreInfo.postId != null)
return

let cancelled = false

void (async () => {
setLoading (true)

try
{
await apiPatch<void> (`/theatres/${ id }/next_post`)
}
catch (error)
{
console.error (error)
}
finally
{
if (!(cancelled))
setLoading (false) setLoading (false)
}) ()
return
} }
}) ()

return () => {
cancelled = true
}
}, [id, loading, theatreInfo.hostFlg, theatreInfo.postId]) }, [id, loading, theatreInfo.hostFlg, theatreInfo.postId])


useEffect (() => { useEffect (() => {
if (theatreInfo.postId == null) if (theatreInfo.postId == null)
return return


let cancelled = false

void (async () => { void (async () => {
setPost (await fetchPost (String (theatreInfo.postId)))
try
{
const nextPost = await fetchPost (String (theatreInfo.postId))
if (!(cancelled))
setPost (nextPost)
}
catch (error)
{
console.error (error)
}
}) () }) ()

return () => {
cancelled = true
}
}, [theatreInfo.postId, theatreInfo.postStartedAt]) }, [theatreInfo.postId, theatreInfo.postStartedAt])


const syncPlayback = (meta: NiconicoMetadata) => { const syncPlayback = (meta: NiconicoMetadata) => {
if (!(theatreInfo.postStartedAt)) if (!(theatreInfo.postStartedAt))
return return


const targetTime =
((new Date).getTime () - (new Date (theatreInfo.postStartedAt)).getTime ())
const targetTime = Math.min (
Math.max (0, Date.now () - (new Date (theatreInfo.postStartedAt)).getTime ()),
videoLength)


const drift = Math.abs (meta.currentTime - targetTime) const drift = Math.abs (meta.currentTime - targetTime)


@@ -89,7 +226,7 @@ export default (() => {
} }


return ( return (
<MainArea>
<div className="md:flex md:flex-1">
<Helmet> <Helmet>
{theatre && ( {theatre && (
<title> <title>
@@ -99,16 +236,82 @@ export default (() => {
</title>)} </title>)}
</Helmet> </Helmet>


{post && (
<PostEmbed
ref={embedRef}
post={post}
onLoadComplete={info => {
embedRef.current?.play ()
setVideoLength (info.lengthInSeconds * 1_000)
}}
onMetadataChange={meta => {
syncPlayback (meta)
}}/>)}
</MainArea>)
<div className="hidden md:block">
<TagDetailSidebar post={post ?? null}/>
</div>

<MainArea>
{post ? (
<>
<PostEmbed
ref={embedRef}
post={post}
onLoadComplete={info => {
embedRef.current?.play ()
setVideoLength (info.lengthInSeconds * 1_000)
}}
onMetadataChange={syncPlayback}/>
<div className="m-2">
<>再生中:</>
<PrefetchLink to={`/posts/${ post.id }`} className="font-bold">
{post.title || post.url}
</PrefetchLink>
</div>
</>) : 'Loading...'}
</MainArea>

<SidebarComponent>
{comments.length > 0 && (
<form
className="w-full h-5/6"
onSubmit={async e => {
e.preventDefault ()

if (!(content))
return

try
{
setSending (true)
await apiPost (`/theatres/${ id }/comments`, { content })
setContent ('')
commentsRef.current?.scrollTo ({
top: commentsRef.current.scrollHeight,
behavior: 'smooth' })
}
finally
{
setSending (false)
}
}}>
<div
ref={commentsRef}
className="overflow-x-hidden overflow-y-scroll text-wrap
border border-black dark:border-white w-full h-3/4">
{comments.map (comment => (
<div key={comment.no} className="p-2">
<div className="w-full">
{comment.content}
</div>
<div className="w-full text-sm text-right">
by {comment.user ? (comment.user.name || '名もなきニジラー') : '運営'}
</div>
<div className="w-full text-sm text-right">
{dateString (comment.createdAt)}
</div>
</div>))}
</div>
<input
className="w-full p-2 border border-black dark:border-white"
type="text"
value={content}
onChange={e => setContent (e.target.value)}
disabled={sending}/>
</form>)}
</SidebarComponent>

<div className="md:hidden">
<TagDetailSidebar post={post ?? null}/>
</div>
</div>)
}) satisfies FC }) satisfies FC

+ 9
- 2
frontend/src/types.ts View File

@@ -29,7 +29,7 @@ export type FetchPostsParams = {
export type Menu = MenuItem[] export type Menu = MenuItem[]


export type MenuItem = { export type MenuItem = {
name: string
name: ReactNode
to: string to: string
base?: string base?: string
subMenu: SubMenuItem[] } subMenu: SubMenuItem[] }
@@ -93,7 +93,7 @@ export type PostTagChange = {
export type SubMenuItem = export type SubMenuItem =
| { component: ReactNode | { component: ReactNode
visible: boolean } visible: boolean }
| { name: string
| { name: ReactNode
to: string to: string
visible?: boolean } visible?: boolean }


@@ -115,6 +115,13 @@ export type Theatre = {
createdAt: string createdAt: string
updatedAt: string } updatedAt: string }


export type TheatreComment = {
theatreId: number,
no: number,
user: { id: number, name: string } | null
content: string
createdAt: string }

export type User = { export type User = {
id: number id: number
name: string | null name: string | null


Loading…
Cancel
Save