Compare commits

..

1 Commits

Author SHA1 Message Date
みてるぞ 638dccad6d #90 2026-05-26 05:52:09 +09:00
30 changed files with 304 additions and 286 deletions
@@ -1,4 +1,7 @@
class ApplicationController < ActionController::API
rescue_from ActiveRecord::RecordInvalid, with: :render_record_invalid
rescue_from ActiveRecord::RecordNotUnique, with: :render_record_not_unique
before_action :reject_banned_ip_address!
before_action :authenticate_user
before_action :reject_banned_user!
@@ -25,6 +28,42 @@ class ApplicationController < ActionController::API
end
end
def render_bad_request message = 'リクエストが不正です.', field: nil, code: :bad_request
render_error(:bad_request, message, field:, code:)
end
def render_unprocessable_entity message = '入力を確認してください.', field: nil, code: :invalid
render_error(:unprocessable_entity, message, field:, code:)
end
def render_error status, message, field: nil, code: status
error = { code: code.to_s, message: }
error[:field] = field.to_s if field.present?
render json: { errors: [error] }, status:
end
def render_model_errors record, status: :unprocessable_entity
errors =
record.errors.map do |error|
{ code: error.type.to_s,
field: error.attribute.to_s,
message: error.full_message }
end
errors = [{ code: 'invalid', message: '入力を確認してください.' }] if errors.empty?
render json: { errors: }, status:
end
def render_record_invalid error
render_model_errors(error.record)
end
def render_record_not_unique _error = nil
render_unprocessable_entity('既に存在してゐます.', code: :taken)
end
def reject_banned_ip_address!
ip_address = IpAddress.find_by(ip_address: IPAddr.new(request.remote_ip).hton)
return unless ip_address&.banned?
@@ -37,4 +76,28 @@ class ApplicationController < ActionController::API
head :forbidden
end
def render_validation_error record = nil, fields: { }, base: []
errors = { }
if record
record.errors.messages.each do |attr, messages|
errors[attr] ||= []
errors[attr].concat(messages)
end
end
fields.each do |attr, messages|
errors[attr] ||= []
errors[attr].concat(Array(messages))
end
base_errors = Array(base) - Array(errors.delete(:base))
render json: { type: 'validation_error',
message: '入力内容を確認してください.',
errors:,
base_errors: },
status: :unprocessable_entity
end
end
@@ -2,7 +2,8 @@ class DeerjikistsController < ApplicationController
def show
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
return head :bad_request if platform.blank? || code.blank?
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
return render_bad_request('code は必須です.', field: :code) if code.blank?
deerjikist = Deerjikist
.joins(:tag)
@@ -22,7 +23,9 @@ class DeerjikistsController < ApplicationController
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
tag_id = params[:tag_id].to_i
return head :bad_request if platform.blank? || code.blank? || tag_id <= 0
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
return render_bad_request('code は必須です.', field: :code) if code.blank?
return render_bad_request('tag_id が不正です.', field: :tag_id) if tag_id <= 0
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
d.tag_id = tag_id
@@ -38,7 +41,8 @@ class DeerjikistsController < ApplicationController
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
return head :bad_request if platform.blank? || code.blank?
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
return render_bad_request('code は必須です.', field: :code) if code.blank?
Deerjikist.find([platform, code]).destroy!
@@ -40,7 +40,8 @@ class MaterialsController < ApplicationController
tag_name_raw = params[:tag].to_s.strip
file = params[:file]
url = params[:url].to_s.strip.presence
return head :bad_request if tag_name_raw.blank? || (file.blank? && url.blank?)
return render_bad_request('タグは必須です.', field: :tag) if tag_name_raw.blank?
return render_bad_request('ファイルまたは URL は必須です.') if file.blank? && url.blank?
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
tag = tag_name.tag
@@ -54,7 +55,7 @@ class MaterialsController < ApplicationController
if material.save
render json: MaterialRepr.base(material, host: request.base_url), status: :created
else
render json: { errors: material.errors.full_messages }, status: :unprocessable_entity
render_model_errors(material)
end
end
@@ -68,7 +69,8 @@ class MaterialsController < ApplicationController
tag_name_raw = params[:tag].to_s.strip
file = params[:file]
url = params[:url].to_s.strip.presence
return head :bad_request if tag_name_raw.blank? || (file.blank? && url.blank?)
return render_bad_request('タグは必須です.', field: :tag) if tag_name_raw.blank?
return render_bad_request('ファイルまたは URL は必須です.') if file.blank? && url.blank?
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
tag = tag_name.tag
@@ -84,7 +86,7 @@ class MaterialsController < ApplicationController
if material.save
render json: MaterialRepr.base(material, host: request.base_url)
else
render json: { errors: material.errors.full_messages }, status: :unprocessable_entity
render_model_errors(material)
end
end
@@ -30,12 +30,14 @@ class NicoTagsController < ApplicationController
id = params[:id].to_i
tag = Tag.find(id)
return head :bad_request unless tag.nico?
return render_bad_request('ニコニコ・タグを指定してください.', field: :id) unless tag.nico?
linked_tag_names = params[:tags].to_s.split
linked_tags = Tag.normalise_tags!(linked_tag_names, with_tagme: false,
with_no_deerjikist: false)
return head :bad_request if linked_tags.any? { |t| t.nico? }
if linked_tags.any? { |t| t.nico? }
return render_bad_request('ニコニコ・タグ同士は連携できません.', field: :tags)
end
ApplicationRecord.transaction do
TagVersioning.record_tag_snapshots!(linked_tags, created_by_user: current_user)
+12 -18
View File
@@ -44,8 +44,7 @@ class PostsController < ApplicationController
filtered_posts
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
.preload(:parents, :children,
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
.preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
.with_attached_thumbnail
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
@@ -96,8 +95,7 @@ class PostsController < ApplicationController
end
def random
post = filtered_posts.preload(:parents, :childern,
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
post = filtered_posts.preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
.order('RAND()')
.first
return head :not_found unless post
@@ -106,11 +104,7 @@ class PostsController < ApplicationController
end
def show
post = Post
.preload(:parents, :children)
.includes(:parents, :children,
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
.find_by(id: params[:id])
post = Post.includes(tags: [:deerjikists, :materials, { tag_name: :wiki_page }]).find_by(id: params[:id])
return head :not_found unless post
render json: PostRepr.base(post, current_user)
@@ -154,11 +148,11 @@ class PostsController < ApplicationController
post.reload
render json: PostRepr.base(post), status: :created
rescue Tag::NicoTagNormalisationError
head :bad_request
render_bad_request('ニコニコ・タグは直接指定できません.', field: :tags)
rescue ArgumentError => e
render json: { errors: [e.message] }, status: :unprocessable_entity
render_unprocessable_entity(e.message)
rescue ActiveRecord::RecordInvalid => e
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
render_model_errors(e.record)
end
def viewed
@@ -181,10 +175,10 @@ class PostsController < ApplicationController
force = bool?(:force)
merge = bool?(:merge)
return head :bad_request if force && merge
return render_bad_request('force と merge は同時に指定できません.') if force && merge
base_version_no = parse_base_version_no
return head :bad_request if !(force) && !(base_version_no)
return render_bad_request('base_version_no は必須です.', field: :base_version_no) if !(force) && !(base_version_no)
title = params[:title].presence
tag_names = params[:tags].to_s.split
@@ -244,11 +238,11 @@ class PostsController < ApplicationController
json['tags'] = build_tag_tree_for(post.tags)
render json:, status: :ok
rescue Tag::NicoTagNormalisationError
head :bad_request
render_bad_request('ニコニコ・タグは直接指定できません.', field: :tags)
rescue ArgumentError => e
render json: { errors: [e.message] }, status: :unprocessable_entity
render_validation_error(fields: { parent_post_ids: [e.message] })
rescue ActiveRecord::RecordInvalid => e
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
render_validation_error(e.record)
end
def changes
@@ -422,7 +416,7 @@ class PostsController < ApplicationController
def sync_parent_posts! post, parent_post_ids
if parent_post_ids.include?(post.id)
post.errors.add(:base, '自分自身を親投稿にはできません.')
post.errors.add(:parent_post_ids, '自分自身を親投稿にはできません.')
raise ActiveRecord::RecordInvalid, post
end
@@ -4,7 +4,7 @@ class PreviewController < ApplicationController
return head :unauthorized unless current_user
url = params[:url]
return head :bad_request unless url.present?
return render_bad_request('URL は必須です.', field: :url) unless url.present?
unless url.start_with?(/http(s)?:\/\//)
url = 'http://' + url
@@ -16,7 +16,7 @@ class PreviewController < ApplicationController
render json: { title: title }
rescue => e
render json: { error: e.message }, status: :bad_request
render_bad_request(e.message, field: :url)
end
def thumbnail
@@ -25,7 +25,7 @@ class PreviewController < ApplicationController
return head :unauthorized unless current_user
url = params[:url]
return head :bad_request if url.blank?
return render_bad_request('URL は必須です.', field: :url) if url.blank?
unless url.start_with?(/http(s)?:\/\//)
url = 'http://' + url
@@ -40,7 +40,8 @@ class PreviewController < ApplicationController
File.delete(path) rescue nil
send_file image.path, type: 'image/png', disposition: 'inline'
else
render json: { error: 'Failed to generate thumbnail' }, status: :internal_server_error
render_error(:internal_server_error, 'サムネールを生成できませんでした.',
code: :thumbnail_generation_failed)
end
end
end
@@ -5,11 +5,12 @@ class TagChildrenController < ApplicationController
parent_id = params[:parent_id]
child_id = params[:child_id]
return head :bad_request if parent_id.blank? || child_id.blank?
return render_bad_request('parent_id は必須です.', field: :parent_id) if parent_id.blank?
return render_bad_request('child_id は必須です.', field: :child_id) if child_id.blank?
parent = Tag.find(parent_id)
child = Tag.find(child_id)
return head :bad_request if parent.nico? || child.nico?
return render_bad_request('ニコニコ・タグの階層は変更できません.') if parent.nico? || child.nico?
ApplicationRecord.transaction do
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
@@ -27,11 +28,12 @@ class TagChildrenController < ApplicationController
parent_id = params[:parent_id]
child_id = params[:child_id]
return head :bad_request if parent_id.blank? || child_id.blank?
return render_bad_request('parent_id は必須です.', field: :parent_id) if parent_id.blank?
return render_bad_request('child_id は必須です.', field: :child_id) if child_id.blank?
parent = Tag.find(parent_id)
child = Tag.find(child_id)
return head :bad_request if parent.nico? || child.nico?
return render_bad_request('ニコニコ・タグの階層は変更できません.') if parent.nico? || child.nico?
ApplicationRecord.transaction do
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
+8 -10
View File
@@ -168,7 +168,7 @@ class TagsController < ApplicationController
def show_by_name
name = params[:name].to_s.strip
return head :bad_request if name.blank?
return render_bad_request('name は必須です.', field: :name) if name.blank?
tag = Tag.joins(:tag_name)
.includes(:tag_name, :materials, tag_name: :wiki_page)
@@ -192,7 +192,7 @@ class TagsController < ApplicationController
def deerjikists_by_name
name = params[:name].to_s.strip
return head :bad_request if name.blank?
return render_bad_request('name は必須です.', field: :name) if name.blank?
tag = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
@@ -228,7 +228,7 @@ class TagsController < ApplicationController
def materials_by_name
name = params[:name].to_s.strip
return head :bad_request if name.blank?
return render_bad_request('name は必須です.', field: :name) if name.blank?
tag = Tag.joins(:tag_name)
.includes(:tag_name, :materials, tag_name: :wiki_page)
@@ -247,17 +247,16 @@ class TagsController < ApplicationController
name = params[:name].to_s.strip
category = params[:category].to_s.strip
return head :unprocessable_entity if name.blank? || category.blank?
return render_unprocessable_entity('名前は必須です.', field: :name) if name.blank?
return render_unprocessable_entity('カテゴリは必須です.', field: :category) if category.blank?
if name != tag.name &&
tag.in?([Tag.tagme, Tag.bot, Tag.no_deerjikist, Tag.video, Tag.niconico])
return render json: { error: 'システム・タグの名称は変更できません.' },
status: :unprocessable_entity
return render_unprocessable_entity('システム・タグの名称は変更できません.', field: :name)
end
if tag.nico? || category == 'nico'
return render json: { error: 'ニコタグは変更できません.' },
status: :unprocessable_entity
return render_unprocessable_entity('ニコタグは変更できません.', field: :category)
end
alias_names = params[:aliases].to_s.split.uniq
@@ -302,8 +301,7 @@ class TagsController < ApplicationController
tag = Tag.find(params[:id])
if tag.nico? || (category.present? && category == 'nico')
return render json: { error: 'ニコタグは変更できません.' },
status: :unprocessable_entity
return render_unprocessable_entity('ニコタグは変更できません.', field: :category)
end
ApplicationRecord.transaction do
@@ -1,28 +1,21 @@
class TheatreCommentsController < ApplicationController
def index
limit = params[:limit].to_i
limit = 20 if limit <= 0
no_gt = params[:no_gt].to_i
no_gt = 0 if no_gt < 0
no_gt = 0 if no_gt.negative?
comments = TheatreComment
.where(theatre_id: params[:theatre_id])
.where('no > ?', no_gt)
.order(no: :desc)
.limit(limit)
render json: comments.map {
_1.as_json(include: { user: { only: [:id, :name] } })
.merge(content: _1.discarded? ? nil : _1.content, deleted: _1.discarded?)
}
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?
return render_unprocessable_entity('本文は必須です.', field: :content) if content.blank?
theatre = Theatre.find_by(id: params[:theatre_id])
return head :not_found unless theatre
@@ -36,18 +29,4 @@ class TheatreCommentsController < ApplicationController
render json: comment, status: :created
end
def destroy
return head :unauthorized unless current_user
theatre_id = params[:theatre_id].to_i
no = params[:id].to_i
comment = TheatreComment.find_by(theatre_id:, no:)
return head :not_found unless comment
comment.discard!
head :no_content
end
end
@@ -1,17 +0,0 @@
class TheatreProgrammesController < ApplicationController
def index
limit = params[:limit].to_i
limit = 100 if limit <= 0
position_gt = params[:position_gt].to_i
position_gt = 0 if position_gt < 0
programmes = TheatreProgramme
.where(theatre_id: params[:theatre_id])
.where('position > ?', position_gt)
.order(position: :desc).limit(100)
.limit(limit)
render json: programmes.as_json(include: { post: PostRepr::BASE })
end
end
@@ -43,14 +43,11 @@ class TheatresController < ApplicationController
return head :not_found unless theatre
return head :forbidden if theatre.host_user != current_user
ApplicationRecord.transaction do
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)
position = (theatre.programmes.maximum(:position) || 0) + 1
theatre.programmes.create!(position:, post:)
end
head :no_content
end
+2 -2
View File
@@ -42,12 +42,12 @@ class UsersController < ApplicationController
return head :unauthorized if user&.id != params[:id].to_i
name = params[:name]
return head :bad_request if name.blank?
return render_bad_request('名前は必須です.', field: :name) if name.blank?
if user.update(name:)
render json: user.slice(:id, :name, :inheritance_code, :role), status: :ok
else
render json: user.errors, status: :unprocessable_entity
render_model_errors(user)
end
end
@@ -46,7 +46,7 @@ class WikiPagesController < ApplicationController
def diff
id = params[:id]
return head :bad_request if id.blank?
return render_bad_request('id は必須です.', field: :id) if id.blank?
from = params[:from].presence
to = params[:to].presence
@@ -56,7 +56,7 @@ class WikiPagesController < ApplicationController
from_rev = from && page.wiki_revisions.find(from)
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
if ((from_rev && !(from_rev.content?)) || !(to_rev&.content?))
return head :unprocessable_entity
return render_unprocessable_entity('差分を表示できない版です.')
end
diffs = Diff::LCS.sdiff(from_rev&.body&.lines || [], to_rev.body.lines)
@@ -89,7 +89,8 @@ class WikiPagesController < ApplicationController
body = params[:body].to_s
message = params[:message].presence
return head :unprocessable_entity if title.blank? || body.blank?
return render_unprocessable_entity('タイトルは必須です.', field: :title) if title.blank?
return render_unprocessable_entity('本文は必須です.', field: :body) if body.blank?
tag_name = TagName.find_undiscard_or_create_by!(name: title)
@@ -101,8 +102,10 @@ class WikiPagesController < ApplicationController
message:)
render json: WikiPageRepr.base(page), status: :created
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
head :unprocessable_entity
rescue ActiveRecord::RecordInvalid => e
render_model_errors(e.record)
rescue ActiveRecord::RecordNotUnique
render_record_not_unique
end
def update
@@ -112,7 +115,8 @@ class WikiPagesController < ApplicationController
title = params[:title]&.strip
body = params[:body].to_s
return head :unprocessable_entity if title.blank? || body.blank?
return render_unprocessable_entity('タイトルは必須です.', field: :title) if title.blank?
return render_unprocessable_entity('本文は必須です.', field: :body) if body.blank?
page = WikiPage.find(params[:id])
base_revision_id = params[:base_revision_id].presence
+1 -1
View File
@@ -81,7 +81,7 @@ class Tag < ApplicationRecord
def material_id = materials.first&.id
def has_deerjikists = deerjikists.exists?
def has_deerjikists = deerjikists.present?
def self.tagme = find_or_create_by_tag_name!('タグ希望', category: :meta)
def self.bot = find_or_create_by_tag_name!('bot操作', category: :meta)
-2
View File
@@ -7,8 +7,6 @@ class Theatre < ApplicationRecord
class_name: 'TheatreWatchingUser', inverse_of: :theatre
has_many :watching_users, through: :active_theatre_watching_users, source: :user
has_many :programmes, class_name: 'TheatreProgramme'
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'
-6
View File
@@ -1,6 +0,0 @@
class TheatreProgramme < ApplicationRecord
self.primary_key = :theatre_id, :position
belongs_to :theatre
belongs_to :post
end
+1 -2
View File
@@ -87,8 +87,7 @@ Rails.application.routes.draw do
patch :next_post
end
resources :comments, controller: :theatre_comments, only: [:index, :create, :destroy]
resources :programmes, controller: :theatre_programmes, only: [:index]
resources :comments, controller: :theatre_comments, only: [:index, :create]
end
resources :materials, only: [:index, :show, :create, :update, :destroy]
@@ -1,10 +0,0 @@
class CreateTheatreProgrammes < ActiveRecord::Migration[8.0]
def change
create_table :theatre_programmes, primary_key: [:theatre_id, :position] do |t|
t.references :theatre, null: false, foreign_key: true
t.integer :position, null: false
t.references :post, null: false, foreign_key: true
t.datetime :created_at, null: false
end
end
end
+1 -13
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 2026_05_14_221900) do
ActiveRecord::Schema[8.0].define(version: 2026_05_07_213300) do
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -283,15 +283,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_05_14_221900) do
t.index ["user_id"], name: "index_theatre_comments_on_user_id"
end
create_table "theatre_programmes", primary_key: ["theatre_id", "position"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "theatre_id", null: false
t.integer "position", null: false
t.bigint "post_id", null: false
t.datetime "created_at", null: false
t.index ["post_id"], name: "index_theatre_programmes_on_post_id"
t.index ["theatre_id"], name: "index_theatre_programmes_on_theatre_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
@@ -299,7 +290,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_05_14_221900) do
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: "idx_on_theatre_id_skip_expires_at_4c8de1dd42"
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"
@@ -474,8 +464,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_05_14_221900) do
add_foreign_key "tags", "tag_names"
add_foreign_key "theatre_comments", "theatres"
add_foreign_key "theatre_comments", "users"
add_foreign_key "theatre_programmes", "posts"
add_foreign_key "theatre_programmes", "theatres"
add_foreign_key "theatre_watching_users", "theatres"
add_foreign_key "theatre_watching_users", "users"
add_foreign_key "theatres", "posts", column: "current_post_id"
@@ -0,0 +1,47 @@
require 'rails_helper'
RSpec.describe 'error responses', type: :request do
describe 'manual input errors' do
it 'returns a stable errors array for bad requests' do
user = create(:user)
sign_in_as(user)
put "/users/#{ user.id }", params: { name: ' ' }
expect(response).to have_http_status(:bad_request)
expect(json.fetch('errors')).to contain_exactly(
include('code' => 'bad_request',
'field' => 'name',
'message' => be_present))
end
it 'returns a stable errors array for unprocessable requests' do
member = create(:user, :member)
tag = create(:tag, :general, name: 'error_response_tag')
sign_in_as(member)
patch "/tags/#{ tag.id }", params: { category: 'nico' }
expect(response).to have_http_status(:unprocessable_entity)
expect(json.fetch('errors')).to contain_exactly(
include('code' => 'invalid',
'field' => 'category',
'message' => be_present))
end
end
describe 'model validation errors' do
it 'returns field, code, and message for model errors' do
user = create(:user)
sign_in_as(user)
put "/users/#{ user.id }", params: { name: 'a' * 256 }
expect(response).to have_http_status(:unprocessable_entity)
expect(json.fetch('errors')).to include(
include('code' => 'too_long',
'field' => 'name',
'message' => be_present))
end
end
end
+1 -1
View File
@@ -63,7 +63,7 @@ const RouteTransitionWrapper = ({ user, setUser }: {
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage user={user}/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage/>}/>
<Route path="/materials" element={<MaterialBasePage/>}>
<Route index element={<MaterialListPage/>}/>
<Route path="new" element={<MaterialNewPage/>}/>
+28 -2
View File
@@ -2,17 +2,23 @@ import { useEffect, useState } from 'react'
import PostFormTagsArea from '@/components/PostFormTagsArea'
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
import FieldError from '@/components/common/FieldError'
import Label from '@/components/common/Label'
import { useDialogue } from '@/components/dialogues/DialogueProvider'
import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast'
import { isApiError } from '@/lib/api'
import { extractValidationError } from '@/lib/apiErrors'
import { updatePost } from '@/lib/posts'
import type { FC, FormEvent } from 'react'
import type { FieldErrors } from '@/lib/apiErrors'
import type { Post, Tag } from '@/types'
type PostFormField =
'parentPostId' | 'tags' | 'originalCreatedFrom' | 'originalCreatedBefore'
const tagsToStr = (tags: Tag[]): string => {
const result: Tag[] = []
@@ -34,7 +40,9 @@ type Props = { post: Post
const PostEditForm: FC<Props> = ({ post, onSave }) => {
const [baseErrors, setBaseErrors] = useState<string[]> ([])
const [disabled, setDisabled] = useState (false)
const [fieldErrors, setFieldErrors] = useState<FieldErrors> ({ })
const [originalCreatedBefore, setOriginalCreatedBefore] =
useState<string | null> (post.originalCreatedBefore)
const [originalCreatedFrom, setOriginalCreatedFrom] =
@@ -47,6 +55,9 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
const dialogue = useDialogue ()
const update = async (...args: Parameters<typeof updatePost>) => {
setFieldErrors ({ })
setBaseErrors ([])
try
{
const data = await updatePost (...args)
@@ -67,10 +78,21 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
if (response?.status !== 409)
{
const validationError = extractValidationError (e)
if (validationError)
{
setFieldErrors (validationError.fieldErrors)
setBaseErrors (validationError.baseErrors)
toast ({ description: '更新はできなかったよ……' })
return
}
toast ({ title: '失敗……', description: '入力を確認してください.' })
return
}
const action = await dialogue.choice ({
title: '競合が発生しました.',
description: (
@@ -142,13 +164,15 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
value={parentPostIds}
onChange={e => setParentPostIds (e.target.value)}
className="w-full border p-2 rounded"/>
<FieldError messages={fieldErrors.url}/>
</div>
{/* タグ */}
<PostFormTagsArea
disabled={disabled}
tags={tags}
setTags={setTags}/>
setTags={setTags}
errors={fieldErrors.tags}/>
{/* オリジナルの作成日時 */}
<PostOriginalCreatedTimeField
@@ -156,7 +180,9 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
originalCreatedFrom={originalCreatedFrom}
setOriginalCreatedFrom={setOriginalCreatedFrom}
originalCreatedBefore={originalCreatedBefore}
setOriginalCreatedBefore={setOriginalCreatedBefore}/>
setOriginalCreatedBefore={setOriginalCreatedBefore}
fromErrors={fieldErrors.originalCreatedFrom}
beforeErrors={fieldErrors.originalCreatedBefore}/>
{/* 送信 */}
<Button
+5 -2
View File
@@ -3,6 +3,7 @@
import { useRef, useState } from 'react'
import TagSearchBox from '@/components/TagSearchBox'
import FieldError from '@/components/common/FieldError'
import Label from '@/components/common/Label'
import TextArea from '@/components/common/TextArea'
import { apiGet } from '@/lib/api'
@@ -33,10 +34,11 @@ const replaceToken = (value: string, start: number, end: number, text: string) =
type Props = Omit<ComponentPropsWithoutRef<'textarea'>, 'value' | 'onChange' | 'onBlur'> & {
tags: string
setTags: (tags: string) => void }
setTags: (tags: string) => void
errors?: string[] }
const PostFormTagsArea: FC<Props> = ({ tags, setTags, ...rest }) => {
const PostFormTagsArea: FC<Props> = ({ tags, setTags, errors, ...rest }) => {
const ref = useRef<HTMLTextAreaElement> (null)
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
@@ -96,6 +98,7 @@ const PostFormTagsArea: FC<Props> = ({ tags, setTags, ...rest }) => {
: [] as Tag[]}
activeIndex={-1}
onSelect={handleTagSelect}/>)}
<FieldError messages={errors}/>
</div>)
}
@@ -9,7 +9,9 @@ type Props = {
originalCreatedFrom: string | null
setOriginalCreatedFrom: (x: string | null) => void
originalCreatedBefore: string | null
setOriginalCreatedBefore: (x: string | null) => void }
setOriginalCreatedBefore: (x: string | null) => void
fromErrors?: string[]
beforeErrors?: string[] }
const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
@@ -19,6 +21,7 @@ const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
setOriginalCreatedBefore }) => (
<div>
<Label></Label>
<div className="my-1 flex">
<div className="w-80">
<DateTimeField
@@ -51,6 +54,8 @@ const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
</Button>
</div>
</div>
<FieldError messages={fromErrors}/>
<div className="my-1 flex">
<div className="w-80">
<DateTimeField
@@ -71,6 +76,7 @@ const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
</Button>
</div>
</div>
<FieldError messages={beforeErrors}/>
</div>)
export default PostOriginalCreatedTimeField
+7 -3
View File
@@ -55,6 +55,12 @@ export const menuOutline = ({ tag, wikiId, user, pathName }: {
{ name: '追加', to: '/materials/new' },
{ name: '全体履歴', to: '/materials/changes', visible: false },
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材集' }] },
{ 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: 'ヘルプ', to: '/wiki/ヘルプ:上映会' }] },
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
{ name: '検索', to: '/wiki' },
{ name: '新規', to: '/wiki/new' },
@@ -65,8 +71,6 @@ export const menuOutline = ({ tag, wikiId, user, pathName }: {
visible: wikiPageFlg },
{ name: '履歴', to: `/wiki/changes?id=${ wikiId }`, visible: wikiPageFlg },
{ name: '編輯', to: `/wiki/${ wikiId || wikiTitle }/edit`, visible: wikiPageFlg }] },
{ name: 'おたのしみ', visible: false, subMenu: [
{ name: '上映会 (β)', to: '/theatres/1' }] },
{ name: 'ユーザ', to: '/users/settings', visible: false, subMenu: [
{ name: '一覧', to: '/users', visible: false },
{ name: 'お前', to: `/users/${ user?.id }`, visible: false },
@@ -263,7 +267,7 @@ const TopNav: FC<Props> = ({ user }) => {
: { initial: { x: 40, y: -40, opacity: 0 },
animate: { x: 0, y: 0, opacity: 1 },
exit: { x: 40, y: -40, opacity: 0 } })}
className="z-10 h-full flex items-center px-3 font-bold w-28">
className="z-10 h-full flex items-center px-3 font-bold w-24">
<h2>{item.name}</h2>
</motion.div>
{item.subMenu
@@ -0,0 +1,17 @@
import type { FC } from 'react'
type Props = { messages?: string[] }
export const FieldError: FC<Props> = ({ messages }: Props) => {
if (!(messages?.length))
return null
return (
<ul className="mt-1 space-y-1 text-red-600 dark:text-red-400">
{messages.map ((message, i) => <li key={i}>{message}</li>)}
</ul>)
}
export default FieldError
+30
View File
@@ -0,0 +1,30 @@
import toCamel from 'camelcase-keys'
import { isApiError } from '@/lib/api'
export type FieldErrors = Partial<Record<string, string[]>>
export type ValidationError = { message: string
fieldErrors: FieldErrors
baseErrors: string[] }
type RawValidationError = { type?: string
message?: string
errors?: Record<string, string[]>
baseErrors?: string[] }
export const extractValidationError = (err: unknown) => {
if (!(isApiError (err)) || err.response?.status !== 422)
return null
const data = toCamel ((err.response.data ?? { }) as Record<string, unknown>,
{ deep: true }) as RawValidationError
if (data.type !== 'validation_error' && !(data.errors))
return null
return { message: data.message ?? '入力内容を確認してください.',
fieldErrors: (data.errors ?? { }) as FieldErrors,
baseErrors: data.baseErrors ?? [] }
}
@@ -3,7 +3,6 @@ import { motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom'
import PostEditForm from '@/components/PostEditForm'
import PostEmbed from '@/components/PostEmbed'
import PostList from '@/components/PostList'
+18 -117
View File
@@ -6,24 +6,20 @@ import ErrorScreen from '@/components/ErrorScreen'
import PostEmbed from '@/components/PostEmbed'
import PrefetchLink from '@/components/PrefetchLink'
import TagDetailSidebar from '@/components/TagDetailSidebar'
import SectionTitle from '@/components/common/SectionTitle'
import { useDialogue } from '@/components/dialogues/DialogueProvider'
import { Button } from '@/components/ui/button'
import MainArea from '@/components/layout/MainArea'
import SidebarComponent from '@/components/layout/SidebarComponent'
import { SITE_TITLE } from '@/config'
import { apiGet, apiDelete, apiPatch, apiPost, apiPut, isApiError } from '@/lib/api'
import { apiGet, apiPatch, apiPost, apiPut, isApiError } from '@/lib/api'
import { fetchPost } from '@/lib/posts'
import { dateString } from '@/lib/utils'
import type { FC, User } from 'react'
import type { FC } from 'react'
import type { NiconicoMetadata,
NiconicoViewerHandle,
Post,
Theatre,
TheatreComment,
TheatreProgramme } from '@/types'
TheatreComment } from '@/types'
type TheatreInfo = {
hostFlg: boolean
@@ -38,36 +34,9 @@ const INITIAL_THEATRE_INFO =
watchingUsers: [] as { id: number; name: string }[] } as const
const commentBox: ReactNode[] = (comment: TheatreComment) =>
[(
<div key={`${ comment.no }-content`} className="w-full">
{comment.deleted
? (
<span className="text-sm font-bold">
</span>)
: comment.content}
</div>),
(
<div key={`${ comment.no }-user`} className="w-full text-sm text-right">
by {comment.user
? (comment.user.name || `名もなきニジラー(#${ comment.user.id }`)
: '運営'}
</div>),
(
<div key={`${ comment.no }-createdAt`} className="w-full text-sm text-right">
{dateString (comment.createdAt)}
</div>)]
type Props = { user: User }
const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
const TheatreDetailPage: FC = () => {
const { id } = useParams ()
const dialogue = useDialogue ()
const commentsRef = useRef<HTMLDivElement> (null)
const embedRef = useRef<NiconicoViewerHandle> (null)
const loadingRef = useRef (false)
@@ -83,7 +52,6 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
const [theatre, setTheatre] = useState<Theatre | null> (null)
const [theatreInfo, setTheatreInfo] = useState<TheatreInfo> (INITIAL_THEATRE_INFO)
const [post, setPost] = useState<Post | null> (null)
const [programmes, setProgrammes] = useState<TheatreProgramme[]> ([])
const [videoLength, setVideoLength] = useState (0)
useEffect (() => {
@@ -150,7 +118,7 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
{
const newComments = await apiGet<TheatreComment[]> (
`/theatres/${ id }/comments`,
{ params: { no_gt: lastCommentNoRef.current, limit: '20' } })
{ params: { no_gt: lastCommentNoRef.current } })
if (!(cancelled) && newComments.length > 0)
{
@@ -246,24 +214,10 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
}
}) ()
void (async () => {
try
{
const data = await apiGet<TheatreProgramme[]> (
`/theatres/${ id }/programmes`, { params: { limit: '100' } })
if (!(cancelled))
setProgrammes (data)
}
catch (e)
{
console.error (e)
}
}) ()
return () => {
cancelled = true
}
}, [id, theatreInfo.postId])
}, [theatreInfo.postId])
const syncPlayback = (meta: NiconicoMetadata) => {
if (!(theatreInfo.postStartedAt))
@@ -279,30 +233,12 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
embedRef.current?.seek (targetTime)
}
const handleDelete = async (commentNo: number) => {
try
{
await apiDelete (`/theatres/${ id }/comments/${ commentNo }`)
setComments (prev => {
const rtn = [...prev]
const idx = rtn.findIndex (x => x.no === commentNo)
rtn[idx] = { ...rtn[idx], deleted: true }
return rtn
})
}
catch
{
;
}
}
if (status >= 400)
return <ErrorScreen status={status}/>
return (
<div className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
<Helmet>
<meta name="robots" content="noindex"/>
{theatre && (
<title>
{'上映会場'
@@ -334,22 +270,6 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
</PrefetchLink>
</div>
</>) : 'Loading...'}
<div>
<SectionTitle>
</SectionTitle>
<div>
{programmes.map ((programme, i) => (
<div key={i}>
<PrefetchLink to={`/posts/${ programme.post.id }`}>
{programme.post.title}
</PrefetchLink>
{dateString (programme.createdAt)}
</div>))}
</div>
</div>
</MainArea>
<SidebarComponent>
@@ -386,36 +306,18 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
className="overflow-x-hidden overflow-y-scroll text-wrap w-full
h-[32vh] md:h-[64vh] border rounded">
{comments.map (comment => (
<div
key={comment.no}
className="p-2 group relative rounded py-1 hover:bg-gray-100
dark:hover:bg-gray-800">
{(user && comment.user?.id === user.id && !(comment.deleted)) && (
<button
type="button"
className="absolute left-1 top-1 hidden rounded text-md text-red-600
hover:bg-red-100 group-hover:inline-block
dark:text-red-300 dark:hover:bg-red-950"
aria-label="コメントを削除"
onClick={async e => {
e.stopPropagation ()
if (!(await dialogue.confirm ({
title: 'このコメントを削除しますか?',
description: (
<div className="border border-black dark:border-white rounded
my-3 p-2 w-64">
{commentBox (comment)}
</div>),
confirmText: '削除',
variant: 'danger' })))
return
await handleDelete (comment.no)
}}>
&times;
</button>)}
{commentBox (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 || `名もなきニジラー(#${ comment.user.id }`)
: '運営'}
</div>
<div className="w-full text-sm text-right">
{dateString (comment.createdAt)}
</div>
</div>))}
</div>
</form>
@@ -443,5 +345,4 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
</div>)
}
export default TheatreDetailPage
+3 -16
View File
@@ -210,25 +210,12 @@ export type Theatre = {
createdAt: string
updatedAt: string }
export type TheatreComment =
| { theatreId: number
no: number
deteled: false
export type TheatreComment = {
theatreId: number,
no: number,
user: { id: number, name: string } | null
content: string
createdAt: string }
| { theatreId: number
no: number
deleted: true
user: { id: number, name: string } | null
content null,
createdAt: string }
export type TheatreProgramme = {
theatreId: number
position: number
post: Post
createdAt: string }
export type User = {
id: number