Browse Source

上映会のし組み作り(#295) (#296)

#295

#295

#295

#295

#295

#295

#295

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: https://git.miteruzo.com/miteruzo/btrc-hub/pulls/296
main
みてるぞ 1 week ago
parent
commit
8cf7107445
19 changed files with 864 additions and 67 deletions
  1. +52
    -0
      backend/app/controllers/theatres_controller.rb
  2. +13
    -0
      backend/app/models/theatre.rb
  3. +8
    -0
      backend/app/models/theatre_comment.rb
  4. +13
    -0
      backend/app/models/theatre_watching_user.rb
  5. +17
    -0
      backend/app/representations/theatre_repr.rb
  6. +7
    -0
      backend/config/routes.rb
  7. +17
    -0
      backend/db/migrate/20260316082500_create_theatres.rb
  8. +12
    -0
      backend/db/migrate/20260316083500_create_theatre_comments.rb
  9. +12
    -0
      backend/db/migrate/20260317015000_create_theatre_watching_users.rb
  10. +55
    -1
      backend/db/schema.rb
  11. +289
    -0
      backend/spec/requests/theatres_spec.rb
  12. +2
    -0
      frontend/src/App.tsx
  13. +185
    -57
      frontend/src/components/NicoViewer.tsx
  14. +16
    -5
      frontend/src/components/PostEmbed.tsx
  15. +3
    -0
      frontend/src/components/TopNav.tsx
  16. +8
    -3
      frontend/src/pages/posts/PostDetailPage.tsx
  17. +114
    -0
      frontend/src/pages/theatres/TheatreDetailPage.tsx
  18. +40
    -0
      frontend/src/types.ts
  19. +1
    -1
      frontend/vite.config.ts

+ 52
- 0
backend/app/controllers/theatres_controller.rb View File

@@ -0,0 +1,52 @@
class TheatresController < ApplicationController
def show
theatre = Theatre.find_by(id: params[:id])
return head :not_found unless theatre

render json: TheatreRepr.base(theatre)
end

def watching
return head :unauthorized unless current_user

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

host_flg = false
post_id = nil
post_started_at = nil

theatre.with_lock do
TheatreWatchingUser.find_or_initialize_by(theatre:, user: current_user).tap {
_1.expires_at = 30.seconds.from_now
}.save!

if (!(theatre.host_user_id?) ||
!(theatre.watching_users.exists?(id: theatre.host_user_id)))
theatre.update!(host_user_id: current_user.id)
end

host_flg = theatre.host_user_id == current_user.id
post_id = theatre.current_post_id
post_started_at = theatre.current_post_started_at
end

render json: { host_flg:, post_id:, post_started_at: }
end

def next_post
return head :unauthorized unless current_user

theatre = Theatre.find_by(id: params[:id])
return head :not_found unless theatre
return head :forbidden if theatre.host_user != current_user

post = Post.where("url LIKE '%nicovideo.jp%'")
.or(Post.where("url LIKE '%youtube.com%'"))
.order('RAND()')
.first
theatre.update!(current_post: post, current_post_started_at: Time.current)

head :no_content
end
end

+ 13
- 0
backend/app/models/theatre.rb View File

@@ -0,0 +1,13 @@
class Theatre < ApplicationRecord
include MyDiscard

has_many :comments, class_name: 'TheatreComment'
has_many :theatre_watching_users, dependent: :delete_all
has_many :active_theatre_watching_users, -> { active },
class_name: 'TheatreWatchingUser', inverse_of: :theatre
has_many :watching_users, through: :active_theatre_watching_users, source: :user

belongs_to :host_user, class_name: 'User', optional: true
belongs_to :current_post, class_name: 'Post', optional: true
belongs_to :created_by_user, class_name: 'User'
end

+ 8
- 0
backend/app/models/theatre_comment.rb View File

@@ -0,0 +1,8 @@
class TheatreComment < ApplicationRecord
include MyDiscard

self.primary_key = :theatre_id, :no

belongs_to :theatre
end


+ 13
- 0
backend/app/models/theatre_watching_user.rb View File

@@ -0,0 +1,13 @@
class TheatreWatchingUser < ApplicationRecord
self.primary_key = :theatre_id, :user_id

belongs_to :theatre
belongs_to :user

scope :active, -> { where('expires_at >= ?', Time.current) }
scope :expired, -> { where('expires_at < ?', Time.current) }

def active? = expires_at >= Time.current

def refresh! = update!(expires_at: 30.seconds.from_now)
end

+ 17
- 0
backend/app/representations/theatre_repr.rb View File

@@ -0,0 +1,17 @@
# frozen_string_literal: true


module TheatreRepr
BASE = { only: [:id, :name, :opens_at, :closes_at, :created_at, :updated_at],
include: { created_by_user: { only: [:id, :name] } } }.freeze

module_function

def base theatre
theatre.as_json(BASE)
end

def many theatre
theatre.map { |t| base(t) }
end
end

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

@@ -72,4 +72,11 @@ Rails.application.routes.draw do
end end
end end
end end

resources :theatres, only: [:show] do
member do
put :watching
patch :next_post
end
end
end end

+ 17
- 0
backend/db/migrate/20260316082500_create_theatres.rb View File

@@ -0,0 +1,17 @@
class CreateTheatres < ActiveRecord::Migration[8.0]
def change
create_table :theatres do |t|
t.string :name
t.datetime :opens_at, null: false, index: true
t.datetime :closes_at, index: true
t.integer :kind, null: false, index: true
t.references :current_post, foreign_key: { to_table: :posts }, index: true
t.datetime :current_post_started_at
t.integer :next_comment_no, null: false, default: 1
t.references :host_user, foreign_key: { to_table: :users }
t.references :created_by_user, null: false, foreign_key: { to_table: :users }, index: true
t.timestamps
t.datetime :discarded_at, index: true
end
end
end

+ 12
- 0
backend/db/migrate/20260316083500_create_theatre_comments.rb View File

@@ -0,0 +1,12 @@
class CreateTheatreComments < ActiveRecord::Migration[8.0]
def change
create_table :theatre_comments, primary_key: [:theatre_id, :no] do |t|
t.references :theatre, null: false, foreign_key: { to_table: :theatres }
t.integer :no, null: false
t.references :user, foreign_key: { to_table: :users }
t.text :content, null: false
t.timestamps
t.datetime :discarded_at, index: true
end
end
end

+ 12
- 0
backend/db/migrate/20260317015000_create_theatre_watching_users.rb View File

@@ -0,0 +1,12 @@
class CreateTheatreWatchingUsers < ActiveRecord::Migration[8.0]
def change
create_table :theatre_watching_users, primary_key: [:theatre_id, :user_id] do |t|
t.references :theatre, null: false, foreign_key: { to_table: :theatres }
t.references :user, null: false, foreign_key: { to_table: :users }, index: true
t.datetime :expires_at, null: false, index: true
t.timestamps

t.index [:theatre_id, :expires_at]
end
end
end

+ 55
- 1
backend/db/schema.rb View File

@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.


ActiveRecord::Schema[8.0].define(version: 2026_03_11_232300) do
ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false t.string "name", null: false
t.string "record_type", null: false t.string "record_type", null: false
@@ -167,6 +167,53 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_11_232300) do
t.index ["tag_name_id"], name: "index_tags_on_tag_name_id", unique: true t.index ["tag_name_id"], name: "index_tags_on_tag_name_id", unique: true
end end


create_table "theatre_comments", primary_key: ["theatre_id", "no"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "theatre_id", null: false
t.integer "no", null: false
t.bigint "user_id"
t.text "content", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["discarded_at"], name: "index_theatre_comments_on_discarded_at"
t.index ["theatre_id"], name: "index_theatre_comments_on_theatre_id"
t.index ["user_id"], name: "index_theatre_comments_on_user_id"
end

create_table "theatre_watching_users", primary_key: ["theatre_id", "user_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "theatre_id", null: false
t.bigint "user_id", null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["expires_at"], name: "index_theatre_watching_users_on_expires_at"
t.index ["theatre_id", "expires_at"], name: "index_theatre_watching_users_on_theatre_id_and_expires_at"
t.index ["theatre_id"], name: "index_theatre_watching_users_on_theatre_id"
t.index ["user_id"], name: "index_theatre_watching_users_on_user_id"
end

create_table "theatres", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name"
t.datetime "opens_at", null: false
t.datetime "closes_at"
t.integer "kind", null: false
t.bigint "current_post_id"
t.datetime "current_post_started_at"
t.integer "next_comment_no", default: 1, null: false
t.bigint "host_user_id"
t.bigint "created_by_user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["closes_at"], name: "index_theatres_on_closes_at"
t.index ["created_by_user_id"], name: "index_theatres_on_created_by_user_id"
t.index ["current_post_id"], name: "index_theatres_on_current_post_id"
t.index ["discarded_at"], name: "index_theatres_on_discarded_at"
t.index ["host_user_id"], name: "index_theatres_on_host_user_id"
t.index ["kind"], name: "index_theatres_on_kind"
t.index ["opens_at"], name: "index_theatres_on_opens_at"
end

create_table "user_ips", primary_key: ["user_id", "ip_address_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| create_table "user_ips", primary_key: ["user_id", "ip_address_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "user_id", null: false t.bigint "user_id", null: false
t.bigint "ip_address_id", null: false t.bigint "ip_address_id", null: false
@@ -262,6 +309,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_11_232300) do
add_foreign_key "tag_similarities", "tags" add_foreign_key "tag_similarities", "tags"
add_foreign_key "tag_similarities", "tags", column: "target_tag_id" add_foreign_key "tag_similarities", "tags", column: "target_tag_id"
add_foreign_key "tags", "tag_names" add_foreign_key "tags", "tag_names"
add_foreign_key "theatre_comments", "theatres"
add_foreign_key "theatre_comments", "users"
add_foreign_key "theatre_watching_users", "theatres"
add_foreign_key "theatre_watching_users", "users"
add_foreign_key "theatres", "posts", column: "current_post_id"
add_foreign_key "theatres", "users", column: "created_by_user_id"
add_foreign_key "theatres", "users", column: "host_user_id"
add_foreign_key "user_ips", "ip_addresses" add_foreign_key "user_ips", "ip_addresses"
add_foreign_key "user_ips", "users" add_foreign_key "user_ips", "users"
add_foreign_key "user_post_views", "posts" add_foreign_key "user_post_views", "posts"


+ 289
- 0
backend/spec/requests/theatres_spec.rb View File

@@ -0,0 +1,289 @@
require 'rails_helper'
require 'active_support/testing/time_helpers'


RSpec.describe 'Theatres API', type: :request do
include ActiveSupport::Testing::TimeHelpers

around do |example|
travel_to(Time.zone.parse('2026-03-18 21:00:00')) do
example.run
end
end

let(:member) { create(:user, :member, name: 'member user') }
let(:other_user) { create(:user, :member, name: 'other user') }

let!(:youtube_post) do
Post.create!(
title: 'youtube post',
url: 'https://www.youtube.com/watch?v=spec123'
)
end

let!(:other_post) do
Post.create!(
title: 'other post',
url: 'https://example.com/posts/1'
)
end

let!(:theatre) do
Theatre.create!(
name: 'spec theatre',
opens_at: Time.zone.parse('2026-03-18 20:00:00'),
kind: 0,
created_by_user: member
)
end

describe 'GET /theatres/:id' do
subject(:do_request) do
get "/theatres/#{theatre_id}"
end

context 'when theatre exists' do
let(:theatre_id) { theatre.id }

it 'returns theatre json' do
do_request

expect(response).to have_http_status(:ok)
expect(json).to include(
'id' => theatre.id,
'name' => 'spec theatre'
)
expect(json).to have_key('opens_at')
expect(json).to have_key('closes_at')
expect(json).to have_key('created_at')
expect(json).to have_key('updated_at')

expect(json['created_by_user']).to include(
'id' => member.id,
'name' => 'member user'
)
end
end

context 'when theatre does not exist' do
let(:theatre_id) { 999_999_999 }

it 'returns 404' do
do_request
expect(response).to have_http_status(:not_found)
end
end
end

describe 'PUT /theatres/:id/watching' do
subject(:do_request) do
put "/theatres/#{theatre_id}/watching"
end

let(:theatre_id) { theatre.id }

context 'when not logged in' do
it 'returns 401' do
sign_out
do_request
expect(response).to have_http_status(:unauthorized)
end
end

context 'when theatre does not exist' do
let(:theatre_id) { 999_999_999 }

it 'returns 404' do
sign_in_as(member)
do_request
expect(response).to have_http_status(:not_found)
end
end

context 'when theatre has no host yet' do
before do
sign_in_as(member)
end

it 'creates watching row, assigns current user as host, and returns current theatre info' do
expect { do_request }
.to change { TheatreWatchingUser.count }.by(1)

expect(response).to have_http_status(:ok)

theatre.reload
watch = TheatreWatchingUser.find_by!(theatre: theatre, user: member)

expect(theatre.host_user_id).to eq(member.id)
expect(watch.expires_at).to be_within(1.second).of(30.seconds.from_now)

expect(json).to eq(
'host_flg' => true,
'post_id' => nil,
'post_started_at' => nil
)
end
end

context 'when current user is already watching' do
let!(:watching_row) do
TheatreWatchingUser.create!(
theatre: theatre,
user: member,
expires_at: 5.seconds.from_now
)
end

before do
sign_in_as(member)
end

it 'refreshes expires_at without creating another row' do
expect { do_request }
.not_to change { TheatreWatchingUser.count }

expect(response).to have_http_status(:ok)

expect(watching_row.reload.expires_at)
.to be_within(1.second).of(30.seconds.from_now)
end
end

context 'when another active host exists' do
before do
TheatreWatchingUser.create!(
theatre: theatre,
user: other_user,
expires_at: 10.minutes.from_now
)
theatre.update!(host_user: other_user)
sign_in_as(member)
end

it 'does not steal host and returns host_flg false' do
expect { do_request }
.to change { TheatreWatchingUser.count }.by(1)

expect(response).to have_http_status(:ok)
expect(theatre.reload.host_user_id).to eq(other_user.id)

expect(json).to eq(
'host_flg' => false,
'post_id' => nil,
'post_started_at' => nil
)
end
end

context 'when host is set but no longer actively watching' do
let(:started_at) { 2.minutes.ago }

before do
TheatreWatchingUser.create!(
theatre: theatre,
user: other_user,
expires_at: 1.second.ago
)
theatre.update!(
host_user: other_user,
current_post: youtube_post,
current_post_started_at: started_at
)
sign_in_as(member)
end

it 'reassigns host to current user and returns current post info' do
expect { do_request }
.to change { TheatreWatchingUser.count }.by(1)

expect(response).to have_http_status(:ok)

theatre.reload
expect(theatre.host_user_id).to eq(member.id)

expect(json['host_flg']).to eq(true)
expect(json['post_id']).to eq(youtube_post.id)
expect(Time.zone.parse(json['post_started_at']))
.to be_within(1.second).of(started_at)
end
end
end

describe 'PATCH /theatres/:id/next_post' do
subject(:do_request) do
patch "/theatres/#{theatre_id}/next_post"
end

let(:theatre_id) { theatre.id }

context 'when not logged in' do
it 'returns 401' do
sign_out
do_request
expect(response).to have_http_status(:unauthorized)
end
end

context 'when theatre does not exist' do
let(:theatre_id) { 999_999_999 }

it 'returns 404' do
sign_in_as(member)
do_request
expect(response).to have_http_status(:not_found)
end
end

context 'when logged in but not host' do
before do
theatre.update!(host_user: other_user)
sign_in_as(member)
end

it 'returns 403' do
do_request
expect(response).to have_http_status(:forbidden)
end
end

context 'when current user is host' do
before do
theatre.update!(host_user: member)
sign_in_as(member)
end

it 'sets current_post to an eligible post and updates current_post_started_at' do
expect { do_request }
.to change { theatre.reload.current_post_id }
.from(nil).to(youtube_post.id)

expect(response).to have_http_status(:no_content)
expect(theatre.reload.current_post_started_at)
.to be_within(1.second).of(Time.current)
end
end

context 'when current user is host and no eligible post exists' do
before do
youtube_post.destroy!
theatre.update!(
host_user: member,
current_post: other_post,
current_post_started_at: 1.hour.ago
)
sign_in_as(member)
end

it 'still returns 204 and clears current_post' do
do_request

expect(response).to have_http_status(:no_content)

theatre.reload
expect(theatre.current_post_id).to be_nil
expect(theatre.current_post_started_at)
.to be_within(1.second).of(Time.current)
end
end
end
end

+ 2
- 0
frontend/src/App.tsx View File

@@ -19,6 +19,7 @@ import PostNewPage from '@/pages/posts/PostNewPage'
import PostSearchPage from '@/pages/posts/PostSearchPage' import PostSearchPage from '@/pages/posts/PostSearchPage'
import ServiceUnavailable from '@/pages/ServiceUnavailable' import ServiceUnavailable from '@/pages/ServiceUnavailable'
import SettingPage from '@/pages/users/SettingPage' import SettingPage from '@/pages/users/SettingPage'
import TheatreDetailPage from '@/pages/theatres/TheatreDetailPage'
import WikiDetailPage from '@/pages/wiki/WikiDetailPage' import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
import WikiDiffPage from '@/pages/wiki/WikiDiffPage' import WikiDiffPage from '@/pages/wiki/WikiDiffPage'
import WikiEditPage from '@/pages/wiki/WikiEditPage' import WikiEditPage from '@/pages/wiki/WikiEditPage'
@@ -47,6 +48,7 @@ const RouteTransitionWrapper = ({ user, setUser }: {
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/> <Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
<Route path="/posts/changes" element={<PostHistoryPage/>}/> <Route path="/posts/changes" element={<PostHistoryPage/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/> <Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage/>}/>
<Route path="/wiki" element={<WikiSearchPage/>}/> <Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/> <Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/> <Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>


+ 185
- 57
frontend/src/components/NicoViewer.tsx View File

@@ -1,78 +1,204 @@
import { useRef, useLayoutEffect, useEffect, useState } from 'react'
type Props = { id: string,
width: number,
height: number,
style?: CSSProperties }

import type { CSSProperties, FC } from 'react'


export default ((props: Props) => {
const { id, width, height, style = { } } = props
import { forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState } from 'react'

import type { CSSProperties, ForwardedRef } from 'react'

import type { NiconicoMetadata, NiconicoVideoInfo, NiconicoViewerHandle } from '@/types'

type NiconicoPlayerMessage =
| { eventName: 'enterProgrammaticFullScreen' }
| { eventName: 'exitProgrammaticFullScreen' }
| { eventName: 'loadComplete'; playerId?: string; data: { videoInfo: NiconicoVideoInfo } }
| { eventName: 'playerMetadataChange'; playerId?: string; data: NiconicoMetadata }
| { eventName: 'playerStatusChange' | 'statusChange'; playerId?: string; data?: unknown }
| { eventName: 'error'; playerId?: string; data?: unknown; code?: string; message?: string }

type NiconicoCommand =
| { eventName: 'play'; sourceConnectorType: 1; playerId: string }
| { eventName: 'pause'; sourceConnectorType: 1; playerId: string }
| { eventName: 'seek'; sourceConnectorType: 1; playerId: string; data: { time: number } }
| { eventName: 'mute'; sourceConnectorType: 1; playerId: string; data: { mute: boolean } }
| { eventName: 'volumeChange'; sourceConnectorType: 1; playerId: string;
data: { volume: number } }
| { eventName: 'commentVisibilityChange'; sourceConnectorType: 1; playerId: string;
data: { commentVisibility: boolean } }

const EMBED_ORIGIN = 'https://embed.nicovideo.jp'

type Props = {
id: string
width: number
height: number
style?: CSSProperties
onLoadComplete?: (info: NiconicoVideoInfo) => void
onMetadataChange?: (meta: NiconicoMetadata) => void }


export default forwardRef ((props: Props, ref: ForwardedRef<NiconicoViewerHandle>) => {
const { id, width, height, style = { }, onLoadComplete, onMetadataChange } = props


const iframeRef = useRef<HTMLIFrameElement> (null) const iframeRef = useRef<HTMLIFrameElement> (null)
const playerId = useMemo (() => `nico-${ id }-${ Math.random ().toString (36).slice (2) }`, [id])


const [screenWidth, setScreenWidth] = useState<CSSProperties['width']> () const [screenWidth, setScreenWidth] = useState<CSSProperties['width']> ()
const [screenHeight, setScreenHeight] = useState<CSSProperties['height']> () const [screenHeight, setScreenHeight] = useState<CSSProperties['height']> ()
const [landscape, setLandscape] = useState<boolean> (false) const [landscape, setLandscape] = useState<boolean> (false)
const [fullScreen, setFullScreen] = useState<boolean> (false) const [fullScreen, setFullScreen] = useState<boolean> (false)


const src = `https://embed.nicovideo.jp/watch/${id}?persistence=1&oldScript=1&referer=&from=0&allowProgrammaticFullScreen=1`;

const styleFullScreen: CSSProperties = fullScreen ? {
top: 0,
left: landscape ? 0 : '100%',
position: 'fixed',
width: screenWidth,
height: screenHeight,
zIndex: 2147483647,
maxWidth: 'none',
transformOrigin: '0% 0%',
transform: landscape ? 'none' : 'rotate(90deg)',
WebkitTransformOrigin: '0% 0%',
WebkitTransform: landscape ? 'none' : 'rotate(90deg)' } : {};

const margedStyle = {
border: 'none',
maxWidth: '100%',
...style,
...styleFullScreen }
const src =
`${ EMBED_ORIGIN }/watch/${ id }`
+ '?jsapi=1'
+ `&playerId=${ encodeURIComponent (playerId) }`
+ '&persistence=1'
+ '&oldScript=1'
+ '&referer='
+ '&from=0'
+ '&allowProgrammaticFullScreen=1'

const styleFullScreen: CSSProperties =
fullScreen
? { top: 0,
left: landscape ? 0 : '100%',
position: 'fixed',
width: screenWidth,
height: screenHeight,
zIndex: 2_147_483_647,
maxWidth: 'none',
transformOrigin: '0% 0%',
transform: landscape ? 'none' : 'rotate(90deg)',
WebkitTransformOrigin: '0% 0%',
WebkitTransform: landscape ? 'none' : 'rotate(90deg)' }
: { }

const margedStyle: CSSProperties =
{ border: 'none', maxWidth: '100%', ...style, ...styleFullScreen }

const postToPlayer = useCallback ((message: NiconicoCommand) => {
const win = iframeRef.current?.contentWindow
if (!(win))
return

win.postMessage (message, EMBED_ORIGIN)
}, [])

const play = useCallback (() => {
postToPlayer ({ eventName: 'play', sourceConnectorType: 1, playerId })
}, [playerId, postToPlayer])

const pause = useCallback (() => {
postToPlayer ({ eventName: 'pause', sourceConnectorType: 1, playerId })
}, [playerId, postToPlayer])

const seek = useCallback ((time: number) => {
postToPlayer ({ eventName: 'seek', sourceConnectorType: 1, playerId, data: { time } })
}, [playerId, postToPlayer])

const mute = useCallback (() => {
postToPlayer ({ eventName: 'mute', sourceConnectorType: 1, playerId, data: { mute: true } })
}, [playerId, postToPlayer])

const unmute = useCallback (() => {
postToPlayer ({ eventName: 'mute', sourceConnectorType: 1, playerId, data: { mute: false } })
}, [playerId, postToPlayer])

const setVolume = useCallback ((volume: number) => {
postToPlayer (
{ eventName: 'volumeChange', sourceConnectorType: 1, playerId, data: { volume } })
}, [playerId, postToPlayer])

const showComments = useCallback (() => {
postToPlayer (
{ eventName: 'commentVisibilityChange', sourceConnectorType: 1, playerId,
data: { commentVisibility: true } })
}, [playerId, postToPlayer])

const hideComments = useCallback (() => {
postToPlayer (
{ eventName: 'commentVisibilityChange', sourceConnectorType: 1, playerId,
data: { commentVisibility: false } })
}, [playerId, postToPlayer])

useImperativeHandle (
ref,
() => ({ play, pause, seek, mute, unmute, setVolume, showComments, hideComments }),
[play, pause, seek, mute, unmute, setVolume, showComments, hideComments])


useEffect (() => { useEffect (() => {
const onMessage = (event: MessageEvent<any>) => {
const onMessage = (event: MessageEvent<NiconicoPlayerMessage>) => {
if (!(iframeRef.current) if (!(iframeRef.current)
|| (event.source !== iframeRef.current.contentWindow))
return

if (event.data.eventName === 'enterProgrammaticFullScreen')
setFullScreen (true)
else if (event.data.eventName === 'exitProgrammaticFullScreen')
setFullScreen (false)
|| (event.source !== iframeRef.current.contentWindow)
|| (event.origin !== EMBED_ORIGIN))
return

const data = event.data

if (!(data)
|| typeof data !== 'object'
|| !('eventName' in data))
return

if (('playerId' in data)
&& data.playerId
&& data.playerId !== playerId)
return

if (data.eventName === 'enterProgrammaticFullScreen')
{
setFullScreen (true)
return
}

if (data.eventName === 'exitProgrammaticFullScreen')
{
setFullScreen (false)
return
}

if (data.eventName === 'loadComplete')
{
onLoadComplete?.(data.data.videoInfo)
return
}

if (data.eventName === 'playerMetadataChange')
{
onMetadataChange?.(data.data)
return
}

if (data.eventName === 'error')
console.error ('niconico player error:', data)
} }


addEventListener ('message', onMessage) addEventListener ('message', onMessage)


return () => removeEventListener ('message', onMessage) return () => removeEventListener ('message', onMessage)
}, [])
}, [onLoadComplete, onMetadataChange, playerId])


useLayoutEffect(() => {
useLayoutEffect (() => {
if (!(fullScreen)) if (!(fullScreen))
return return


const initialScrollX = scrollX const initialScrollX = scrollX
const initialScrollY = scrollY const initialScrollY = scrollY
let timer: NodeJS.Timeout
let timer: ReturnType<typeof setTimeout>
let ended = false let ended = false


const pollingResize = () => { const pollingResize = () => {
if (ended) if (ended)
return
return


const landscape = innerWidth >= innerHeight
const windowWidth = `${landscape ? innerWidth : innerHeight}px`
const windowHeight = `${landscape ? innerHeight : innerWidth}px`
const isLandscape = innerWidth >= innerHeight
const windowWidth = `${ isLandscape ? innerWidth : innerHeight }px`
const windowHeight = `${ isLandscape ? innerHeight : innerWidth }px`


setLandscape (landscape)
setLandscape (isLandscape)
setScreenWidth (windowWidth) setScreenWidth (windowWidth)
setScreenHeight (windowHeight) setScreenHeight (windowHeight)
timer = setTimeout (startPollingResize, 200) timer = setTimeout (startPollingResize, 200)
@@ -80,9 +206,9 @@ export default ((props: Props) => {


const startPollingResize = () => { const startPollingResize = () => {
if (requestAnimationFrame) if (requestAnimationFrame)
requestAnimationFrame (pollingResize)
requestAnimationFrame (pollingResize)
else else
pollingResize ()
pollingResize ()
} }


startPollingResize () startPollingResize ()
@@ -97,15 +223,17 @@ export default ((props: Props) => {
useEffect (() => { useEffect (() => {
if (!(fullScreen)) if (!(fullScreen))
return return

scrollTo (0, 0) scrollTo (0, 0)
}, [screenWidth, screenHeight, fullScreen]) }, [screenWidth, screenHeight, fullScreen])


return ( return (
<iframe ref={iframeRef}
src={src}
width={width}
height={height}
style={margedStyle}
allowFullScreen
allow="autoplay"/>)
}) satisfies FC<Props>
<iframe
ref={iframeRef}
src={src}
width={width}
height={height}
style={margedStyle}
allowFullScreen
allow="autoplay"/>)
})

+ 16
- 5
frontend/src/components/PostEmbed.tsx View File

@@ -4,14 +4,18 @@ import YoutubeEmbed from 'react-youtube'
import NicoViewer from '@/components/NicoViewer' import NicoViewer from '@/components/NicoViewer'
import TwitterEmbed from '@/components/TwitterEmbed' import TwitterEmbed from '@/components/TwitterEmbed'


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


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


type Props = { post: Post }
type Props = {
ref?: RefObject<NiconicoViewerHandle | null>
post: Post
onLoadComplete?: (info: NiconicoVideoInfo) => void
onMetadataChange?: (meta: NiconicoMetadata) => void }




export default (({ post }: Props) => {
export default (({ ref, post, onLoadComplete, onMetadataChange }: Props) => {
const url = new URL (post.url) const url = new URL (post.url)


switch (url.hostname.split ('.').slice (-2).join ('.')) switch (url.hostname.split ('.').slice (-2).join ('.'))
@@ -24,7 +28,14 @@ export default (({ post }: Props) => {


const [videoId] = mVideoId const [videoId] = mVideoId


return <NicoViewer id={videoId} width={640} height={360}/>
return (
<NicoViewer
ref={ref}
id={videoId}
width={640}
height={360}
onLoadComplete={onLoadComplete}
onMetadataChange={onMetadataChange}/>)
} }


case 'twitter.com': case 'twitter.com':


+ 3
- 0
frontend/src/components/TopNav.tsx View File

@@ -79,6 +79,9 @@ 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: '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' },


+ 8
- 3
frontend/src/pages/posts/PostDetailPage.tsx View File

@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { motion } from 'framer-motion' import { motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom' import { useParams } from 'react-router-dom'


@@ -21,7 +21,7 @@ import ServiceUnavailable from '@/pages/ServiceUnavailable'


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


import type { User } from '@/types'
import type { NiconicoViewerHandle, User } from '@/types'


type Props = { user: User | null } type Props = { user: User | null }


@@ -38,6 +38,8 @@ export default (({ user }: Props) => {


const qc = useQueryClient () const qc = useQueryClient ()


const embedRef = useRef<NiconicoViewerHandle> (null)

const [status, setStatus] = useState (200) const [status, setStatus] = useState (200)


const changeViewedFlg = useMutation ({ const changeViewedFlg = useMutation ({
@@ -120,7 +122,10 @@ export default (({ user }: Props) => {
className="object-cover w-full h-full"/> className="object-cover w-full h-full"/>
</motion.div>)} </motion.div>)}


<PostEmbed post={post}/>
<PostEmbed
ref={embedRef}
post={post}
onLoadComplete={() => embedRef.current?.play ()}/>
<Button onClick={() => changeViewedFlg.mutate ()} <Button onClick={() => changeViewedFlg.mutate ()}
disabled={changeViewedFlg.isPending} disabled={changeViewedFlg.isPending}
className={cn ('text-white', viewedClass)}> className={cn ('text-white', viewedClass)}>


+ 114
- 0
frontend/src/pages/theatres/TheatreDetailPage.tsx View File

@@ -0,0 +1,114 @@
import { useEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom'

import PostEmbed from '@/components/PostEmbed'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { apiGet, apiPatch, apiPut } from '@/lib/api'
import { fetchPost } from '@/lib/posts'

import type { FC } from 'react'

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

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


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

const embedRef = useRef<NiconicoViewerHandle> (null)

const [loading, setLoading] = useState (false)
const [theatre, setTheatre] = useState<Theatre | null> (null)
const [theatreInfo, setTheatreInfo] =
useState<TheatreInfo> ({ hostFlg: false, postId: null, postStartedAt: null })
const [post, setPost] = useState<Post | null> (null)
const [videoLength, setVideoLength] = useState (9_999_999_999)

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

void (async () => {
setTheatre (await apiGet<Theatre> (`/theatres/${ id }`))
}) ()

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 () => clearInterval (interval)
}, [id, theatreInfo.hostFlg, theatreInfo.postStartedAt, videoLength])

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

if (theatreInfo.postId == null)
{
void (async () => {
setLoading (true)
await apiPatch<void> (`/theatres/${ id }/next_post`)
setLoading (false)
}) ()
return
}
}, [id, loading, theatreInfo.hostFlg, theatreInfo.postId])

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

void (async () => {
setPost (await fetchPost (String (theatreInfo.postId)))
}) ()
}, [theatreInfo.postId, theatreInfo.postStartedAt])

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

const targetTime =
((new Date).getTime () - (new Date (theatreInfo.postStartedAt)).getTime ())

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

if (drift > 5_000)
embedRef.current?.seek (targetTime)
}

return (
<MainArea>
<Helmet>
{theatre && (
<title>
{'上映会場'
+ (theatre.name ? `『${ theatre.name }』` : ` #${ theatre.id }`)
+ ` | ${ SITE_TITLE }`}
</title>)}
</Helmet>

{post && (
<PostEmbed
ref={embedRef}
post={post}
onLoadComplete={info => {
embedRef.current?.play ()
setVideoLength (info.lengthInSeconds * 1_000)
}}
onMetadataChange={meta => {
syncPlayback (meta)
}}/>)}
</MainArea>)
}) satisfies FC

+ 40
- 0
frontend/src/types.ts View File

@@ -38,6 +38,37 @@ export type NicoTag = Tag & {
category: 'nico' category: 'nico'
linkedTags: Tag[] } linkedTags: Tag[] }


export type NiconicoMetadata = {
currentTime: number
duration: number
isVideoMetaDataLoaded: boolean
maximumBuffered: number
muted: boolean
showComment: boolean
volume: number }

export type NiconicoVideoInfo = {
title: string
videoId: string
lengthInSeconds: number
thumbnailUrl: string
description: string
viewCount: number
commentCount: number
mylistCount: number
postedAt: string
watchId: number }

export type NiconicoViewerHandle = {
play: () => void
pause: () => void
seek: (time: number) => void
mute: () => void
unmute: () => void
setVolume: (volume: number) => void
showComments: () => void
hideComments: () => void }

export type Post = { export type Post = {
id: number id: number
url: string url: string
@@ -75,6 +106,15 @@ export type Tag = {
children?: Tag[] children?: Tag[]
matchedAlias?: string | null } matchedAlias?: string | null }


export type Theatre = {
id: number
name: string | null
opensAt: string
closesAt: string | null
createdByUser: { id: number; name: string }
createdAt: string
updatedAt: string }

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


+ 1
- 1
frontend/vite.config.ts View File

@@ -10,7 +10,7 @@ export default defineConfig ({
server: { host: true, server: { host: true,
port: 5173, port: 5173,
strictPort: true, strictPort: true,
allowedHosts: ['hub.nizika.monster', 'localhost'],
allowedHosts: ['hub.nizika.monster', 'localhost', 'nico-dev.test'],
proxy: { '/api': { target: 'http://localhost:3002', proxy: { '/api': { target: 'http://localhost:3002',
changeOrigin: true, changeOrigin: true,
secure: false } }, secure: false } },


Loading…
Cancel
Save