コミットを比較
4 コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| e4a047773a | |||
| 3a2fab5d11 | |||
| 528b786191 | |||
| d15e3d2221 |
@@ -11,15 +11,4 @@ class ApplicationController < ActionController::API
|
|||||||
code = request.headers['X-Transfer-Code'] || request.headers['HTTP_X_TRANSFER_CODE']
|
code = request.headers['X-Transfer-Code'] || request.headers['HTTP_X_TRANSFER_CODE']
|
||||||
@current_user = User.find_by(inheritance_code: code)
|
@current_user = User.find_by(inheritance_code: code)
|
||||||
end
|
end
|
||||||
|
|
||||||
def bool? key, default: false
|
|
||||||
return default if params[key].nil?
|
|
||||||
|
|
||||||
s = params[key].to_s.strip.downcase
|
|
||||||
if default
|
|
||||||
!(s.in?(['0', 'false', 'off', 'no']))
|
|
||||||
else
|
|
||||||
s.in?(['', '1', 'true', 'on', 'yes'])
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
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?
|
|
||||||
|
|
||||||
deerjikist = Deerjikist
|
|
||||||
.joins(:tag)
|
|
||||||
.includes(tag: :tag_name)
|
|
||||||
.find_by(platform:, code:)
|
|
||||||
if deerjikist
|
|
||||||
render json: DeerjikistRepr.base(deerjikist)
|
|
||||||
else
|
|
||||||
head :not_found
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
return head :unauthorized unless current_user
|
|
||||||
return head :forbidden unless current_user.gte_member?
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
|
|
||||||
d.tag_id = tag_id
|
|
||||||
d.save!
|
|
||||||
end
|
|
||||||
|
|
||||||
render json: DeerjikistRepr.base(deerjikist)
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
return head :unauthorized unless current_user
|
|
||||||
return head :forbidden unless current_user.gte_member?
|
|
||||||
|
|
||||||
platform = params[:platform].to_s.strip
|
|
||||||
code = params[:code].to_s.strip
|
|
||||||
return head :bad_request if platform.blank? || code.blank?
|
|
||||||
|
|
||||||
Deerjikist.find([platform, code]).destroy!
|
|
||||||
|
|
||||||
head :no_content
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
class NicoTagsController < ApplicationController
|
class NicoTagsController < ApplicationController
|
||||||
|
TAG_JSON = { only: [:id, :category, :post_count], methods: [:name, :has_wiki] }.freeze
|
||||||
|
|
||||||
def index
|
def index
|
||||||
limit = (params[:limit] || 20).to_i
|
limit = (params[:limit] || 20).to_i
|
||||||
cursor = params[:cursor].presence
|
cursor = params[:cursor].presence
|
||||||
|
|
||||||
q = Tag.nico_tags
|
q = Tag.nico_tags
|
||||||
.includes(:tag_name, tag_name: :wiki_page, linked_tags: { tag_name: :wiki_page })
|
.includes(:tag_name, linked_tags: :tag_name)
|
||||||
.order(updated_at: :desc)
|
.order(updated_at: :desc)
|
||||||
q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor
|
q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor
|
||||||
|
|
||||||
tags = q.limit(limit + 1).to_a
|
tags = q.limit(limit + 1)
|
||||||
|
|
||||||
next_cursor = nil
|
next_cursor = nil
|
||||||
if tags.size > limit
|
if tags.size > limit
|
||||||
@@ -17,15 +19,15 @@ class NicoTagsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
render json: { tags: tags.map { |tag|
|
render json: { tags: tags.map { |tag|
|
||||||
TagRepr.base(tag).merge(linked_tags: tag.linked_tags.map { |lt|
|
tag.as_json(TAG_JSON).merge(linked_tags: tag.linked_tags.map { |lt|
|
||||||
TagRepr.base(lt)
|
lt.as_json(TAG_JSON)
|
||||||
})
|
})
|
||||||
}, next_cursor: }
|
}, next_cursor: }
|
||||||
end
|
end
|
||||||
|
|
||||||
def update
|
def update
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
id = params[:id].to_i
|
id = params[:id].to_i
|
||||||
|
|
||||||
@@ -39,6 +41,6 @@ class NicoTagsController < ApplicationController
|
|||||||
tag.linked_tags = linked_tags
|
tag.linked_tags = linked_tags
|
||||||
tag.save!
|
tag.save!
|
||||||
|
|
||||||
render json: tag.linked_tags.map { |t| TagRepr.base(t) }, status: :ok
|
render json: tag.linked_tags.map { |t| t.as_json(TAG_JSON) }, status: :ok
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,88 +2,41 @@ class PostsController < ApplicationController
|
|||||||
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
||||||
|
|
||||||
def index
|
def index
|
||||||
url = params[:url].presence
|
|
||||||
title = params[:title].presence
|
|
||||||
original_created_from = params[:original_created_from].presence
|
|
||||||
original_created_to = params[:original_created_to].presence
|
|
||||||
created_between = params[:created_from].presence, params[:created_to].presence
|
|
||||||
updated_between = params[:updated_from].presence, params[:updated_to].presence
|
|
||||||
|
|
||||||
order = params[:order].to_s.split(':', 2).map(&:strip)
|
|
||||||
unless order[0].in?(['title', 'url', 'original_created_at', 'created_at', 'updated_at'])
|
|
||||||
order[0] = 'original_created_at'
|
|
||||||
end
|
|
||||||
unless order[1].in?(['asc', 'desc'])
|
|
||||||
order[1] =
|
|
||||||
if order[0].in?(['title', 'url'])
|
|
||||||
'asc'
|
|
||||||
else
|
|
||||||
'desc'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
page = (params[:page].presence || 1).to_i
|
page = (params[:page].presence || 1).to_i
|
||||||
limit = (params[:limit].presence || 20).to_i
|
limit = (params[:limit].presence || 20).to_i
|
||||||
|
cursor = params[:cursor].presence
|
||||||
|
|
||||||
page = 1 if page < 1
|
page = 1 if page < 1
|
||||||
limit = 1 if limit < 1
|
limit = 1 if limit < 1
|
||||||
|
|
||||||
offset = (page - 1) * limit
|
offset = (page - 1) * limit
|
||||||
|
|
||||||
pt_max_sql =
|
|
||||||
PostTag
|
|
||||||
.select('post_id, MAX(updated_at) AS max_updated_at')
|
|
||||||
.group('post_id')
|
|
||||||
.to_sql
|
|
||||||
|
|
||||||
updated_at_all_sql =
|
|
||||||
'GREATEST(posts.updated_at,' +
|
|
||||||
'COALESCE(pt_max.max_updated_at, posts.updated_at))'
|
|
||||||
|
|
||||||
q =
|
|
||||||
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(tags: { tag_name: :wiki_page })
|
|
||||||
.with_attached_thumbnail
|
|
||||||
|
|
||||||
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
|
||||||
q = q.where('posts.title LIKE ?', "%#{ title }%") if title
|
|
||||||
if original_created_from
|
|
||||||
q = q.where('posts.original_created_before > ?', original_created_from)
|
|
||||||
end
|
|
||||||
if original_created_to
|
|
||||||
q = q.where('posts.original_created_from <= ?', original_created_to)
|
|
||||||
end
|
|
||||||
q = q.where('posts.created_at >= ?', created_between[0]) if created_between[0]
|
|
||||||
q = q.where('posts.created_at <= ?', created_between[1]) if created_between[1]
|
|
||||||
if updated_between[0]
|
|
||||||
q = q.where("#{ updated_at_all_sql } >= ?", updated_between[0])
|
|
||||||
end
|
|
||||||
if updated_between[1]
|
|
||||||
q = q.where("#{ updated_at_all_sql } <= ?", updated_between[1])
|
|
||||||
end
|
|
||||||
|
|
||||||
sort_sql =
|
sort_sql =
|
||||||
case order[0]
|
'COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
|
||||||
when 'original_created_at'
|
|
||||||
'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE,' +
|
|
||||||
'posts.original_created_from,' +
|
'posts.original_created_from,' +
|
||||||
'posts.created_at)'
|
'posts.created_at)'
|
||||||
when 'updated_at'
|
q =
|
||||||
updated_at_all_sql
|
filtered_posts
|
||||||
|
.preload(tags: :tag_name)
|
||||||
|
.with_attached_thumbnail
|
||||||
|
.select("posts.*, #{ sort_sql } AS sort_ts")
|
||||||
|
.order(Arel.sql("#{ sort_sql } DESC"))
|
||||||
|
posts = (
|
||||||
|
if cursor
|
||||||
|
q.where("#{ sort_sql } < ?", Time.iso8601(cursor)).limit(limit + 1)
|
||||||
else
|
else
|
||||||
"posts.#{ order[0] }"
|
q.limit(limit).offset(offset)
|
||||||
end
|
end).to_a
|
||||||
posts = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, posts.id #{ order[1] }"))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset)
|
|
||||||
.to_a
|
|
||||||
|
|
||||||
q = q.except(:select, :order)
|
next_cursor = nil
|
||||||
|
if cursor && posts.length > limit
|
||||||
|
next_cursor = posts.last.read_attribute('sort_ts').iso8601(6)
|
||||||
|
posts = posts.first(limit)
|
||||||
|
end
|
||||||
|
|
||||||
render json: { posts: posts.map { |post|
|
render json: { posts: posts.map { |post|
|
||||||
PostRepr.base(post).merge(updated_at: post.updated_at_all).tap do |json|
|
post.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||||
|
methods: [:name] } }).tap do |json|
|
||||||
json['thumbnail'] =
|
json['thumbnail'] =
|
||||||
if post.thumbnail.attached?
|
if post.thumbnail.attached?
|
||||||
rails_storage_proxy_url(post.thumbnail, only_path: false)
|
rails_storage_proxy_url(post.thumbnail, only_path: false)
|
||||||
@@ -91,36 +44,50 @@ class PostsController < ApplicationController
|
|||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
}, count: q.group_values.present? ? q.count.size : q.count }
|
}, count: if filtered_posts.group_values.present?
|
||||||
|
filtered_posts.count.size
|
||||||
|
else
|
||||||
|
filtered_posts.count
|
||||||
|
end, next_cursor: }
|
||||||
end
|
end
|
||||||
|
|
||||||
def random
|
def random
|
||||||
post = filtered_posts.preload(tags: { tag_name: :wiki_page })
|
post = filtered_posts.preload(tags: :tag_name).order('RAND()').first
|
||||||
.order('RAND()')
|
|
||||||
.first
|
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
|
|
||||||
render json: PostRepr.base(post, current_user)
|
viewed = current_user&.viewed?(post) || false
|
||||||
|
|
||||||
|
render json: (post
|
||||||
|
.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||||
|
methods: [:name] } })
|
||||||
|
.merge(viewed:))
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
post = Post.includes(tags: { tag_name: :wiki_page }).find_by(id: params[:id])
|
post = Post.includes(tags: :tag_name).find(params[:id])
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
|
|
||||||
render json: PostRepr.base(post, current_user)
|
viewed = current_user&.viewed?(post) || false
|
||||||
.merge(tags: build_tag_tree_for(post.tags),
|
|
||||||
related: post.related(limit: 20))
|
json = post.as_json
|
||||||
|
json['tags'] = build_tag_tree_for(post.tags)
|
||||||
|
json['related'] = post.related(limit: 20)
|
||||||
|
json['viewed'] = viewed
|
||||||
|
|
||||||
|
render json:
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
|
# TODO: URL が正規のものがチェック,不正ならエラー
|
||||||
|
# TODO: URL は必須にする(タイトルは省略可).
|
||||||
# TODO: サイトに応じて thumbnail_base 設定
|
# TODO: サイトに応じて thumbnail_base 設定
|
||||||
title = params[:title].presence
|
title = params[:title].presence
|
||||||
url = params[:url]
|
url = params[:url]
|
||||||
thumbnail = params[:thumbnail]
|
thumbnail = params[:thumbnail]
|
||||||
tag_names = params[:tags].to_s.split
|
tag_names = params[:tags].to_s.split(' ')
|
||||||
original_created_from = params[:original_created_from]
|
original_created_from = params[:original_created_from]
|
||||||
original_created_before = params[:original_created_before]
|
original_created_before = params[:original_created_before]
|
||||||
|
|
||||||
@@ -132,14 +99,12 @@ class PostsController < ApplicationController
|
|||||||
tags = Tag.normalise_tags(tag_names)
|
tags = Tag.normalise_tags(tag_names)
|
||||||
tags = Tag.expand_parent_tags(tags)
|
tags = Tag.expand_parent_tags(tags)
|
||||||
sync_post_tags!(post, tags)
|
sync_post_tags!(post, tags)
|
||||||
|
render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||||
post.reload
|
methods: [:name] } }),
|
||||||
render json: PostRepr.base(post), status: :created
|
status: :created
|
||||||
else
|
else
|
||||||
render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
|
render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
|
||||||
end
|
end
|
||||||
rescue Tag::NicoTagNormalisationError
|
|
||||||
head :bad_request
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def viewed
|
def viewed
|
||||||
@@ -158,10 +123,10 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
def update
|
def update
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
title = params[:title].presence
|
title = params[:title].presence
|
||||||
tag_names = params[:tags].to_s.split
|
tag_names = params[:tags].to_s.split(' ')
|
||||||
original_created_from = params[:original_created_from]
|
original_created_from = params[:original_created_from]
|
||||||
original_created_before = params[:original_created_before]
|
original_created_before = params[:original_created_before]
|
||||||
|
|
||||||
@@ -171,21 +136,16 @@ class PostsController < ApplicationController
|
|||||||
Tag.normalise_tags(tag_names, with_tagme: false)
|
Tag.normalise_tags(tag_names, with_tagme: false)
|
||||||
tags = Tag.expand_parent_tags(tags)
|
tags = Tag.expand_parent_tags(tags)
|
||||||
sync_post_tags!(post, tags)
|
sync_post_tags!(post, tags)
|
||||||
|
|
||||||
post.reload
|
|
||||||
json = post.as_json
|
json = post.as_json
|
||||||
json['tags'] = build_tag_tree_for(post.tags)
|
json['tags'] = build_tag_tree_for(post.tags)
|
||||||
render json:, status: :ok
|
render json:, status: :ok
|
||||||
else
|
else
|
||||||
render json: post.errors, status: :unprocessable_entity
|
render json: post.errors, status: :unprocessable_entity
|
||||||
end
|
end
|
||||||
rescue Tag::NicoTagNormalisationError
|
|
||||||
head :bad_request
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def changes
|
def changes
|
||||||
id = params[:id].presence
|
id = params[:id]
|
||||||
tag_id = params[:tag].presence
|
|
||||||
page = (params[:page].presence || 1).to_i
|
page = (params[:page].presence || 1).to_i
|
||||||
limit = (params[:limit].presence || 20).to_i
|
limit = (params[:limit].presence || 20).to_i
|
||||||
|
|
||||||
@@ -196,26 +156,21 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
pts = PostTag.with_discarded
|
pts = PostTag.with_discarded
|
||||||
pts = pts.where(post_id: id) if id.present?
|
pts = pts.where(post_id: id) if id.present?
|
||||||
pts = pts.where(tag_id:) if tag_id.present?
|
pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
|
||||||
pts = pts.includes(:post, :created_user, :deleted_user,
|
|
||||||
tag: { tag_name: :wiki_page })
|
|
||||||
|
|
||||||
events = []
|
events = []
|
||||||
pts.each do |pt|
|
pts.each do |pt|
|
||||||
tag = TagRepr.base(pt.tag)
|
|
||||||
post = pt.post
|
|
||||||
|
|
||||||
events << Event.new(
|
events << Event.new(
|
||||||
post:,
|
post: pt.post,
|
||||||
tag:,
|
tag: pt.tag.as_json(only: [:id, :category], methods: [:name]),
|
||||||
user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
|
user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
|
||||||
change_type: 'add',
|
change_type: 'add',
|
||||||
timestamp: pt.created_at)
|
timestamp: pt.created_at)
|
||||||
|
|
||||||
if pt.discarded_at
|
if pt.discarded_at
|
||||||
events << Event.new(
|
events << Event.new(
|
||||||
post:,
|
post: pt.post,
|
||||||
tag:,
|
tag: pt.tag.as_json(only: [:id, :category], methods: [:name]),
|
||||||
user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
|
user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
|
||||||
change_type: 'remove',
|
change_type: 'remove',
|
||||||
timestamp: pt.discarded_at)
|
timestamp: pt.discarded_at)
|
||||||
@@ -224,13 +179,13 @@ class PostsController < ApplicationController
|
|||||||
events.sort_by!(&:timestamp)
|
events.sort_by!(&:timestamp)
|
||||||
events.reverse!
|
events.reverse!
|
||||||
|
|
||||||
render json: { changes: (events.slice(offset, limit) || []).as_json, count: events.size }
|
render json: { changes: events.slice(offset, limit).as_json, count: events.size }
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def filtered_posts
|
def filtered_posts
|
||||||
tag_names = params[:tags].to_s.split
|
tag_names = params[:tags].to_s.split(' ')
|
||||||
match_type = params[:match]
|
match_type = params[:match]
|
||||||
if tag_names.present?
|
if tag_names.present?
|
||||||
filter_posts_by_tags(tag_names, match_type)
|
filter_posts_by_tags(tag_names, match_type)
|
||||||
@@ -240,40 +195,16 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def filter_posts_by_tags tag_names, match_type
|
def filter_posts_by_tags tag_names, match_type
|
||||||
literals = tag_names.map do |raw_name|
|
posts = Post.joins(tags: :tag_name)
|
||||||
{ name: TagName.canonicalise(raw_name.sub(/\Anot:/i, '')).first,
|
|
||||||
negative: raw_name.downcase.start_with?('not:') }
|
|
||||||
end
|
|
||||||
|
|
||||||
return Post.all if literals.empty?
|
|
||||||
|
|
||||||
if match_type == 'any'
|
if match_type == 'any'
|
||||||
literals.reduce(Post.none) do |posts, literal|
|
posts.where(tag_names: { name: tag_names }).distinct
|
||||||
posts.or(tag_literal_relation(literal[:name], negative: literal[:negative]))
|
|
||||||
end
|
|
||||||
else
|
else
|
||||||
literals.reduce(Post.all) do |posts, literal|
|
posts.where(tag_names: { name: tag_names })
|
||||||
ids = tagged_post_ids_for(literal[:name])
|
.group('posts.id')
|
||||||
if literal[:negative]
|
.having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
|
||||||
posts.where.not(id: ids)
|
|
||||||
else
|
|
||||||
posts.where(id: ids)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def tag_literal_relation name, negative:
|
|
||||||
ids = tagged_post_ids_for(name)
|
|
||||||
if negative
|
|
||||||
Post.where.not(id: ids)
|
|
||||||
else
|
|
||||||
Post.where(id: ids)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def tagged_post_ids_for(name) =
|
|
||||||
Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
|
|
||||||
|
|
||||||
def sync_post_tags! post, desired_tags
|
def sync_post_tags! post, desired_tags
|
||||||
desired_tags.each do |t|
|
desired_tags.each do |t|
|
||||||
@@ -323,7 +254,8 @@ class PostsController < ApplicationController
|
|||||||
return nil unless tag
|
return nil unless tag
|
||||||
|
|
||||||
if path.include?(tag_id)
|
if path.include?(tag_id)
|
||||||
return TagRepr.base(tag).merge(children: [])
|
return tag.as_json(only: [:id, :category, :post_count],
|
||||||
|
methods: [:name]).merge(children: [])
|
||||||
end
|
end
|
||||||
|
|
||||||
if memo.key?(tag_id)
|
if memo.key?(tag_id)
|
||||||
@@ -335,7 +267,8 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
||||||
|
|
||||||
memo[tag_id] = TagRepr.base(tag).merge(children:)
|
memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
|
||||||
|
methods: [:name]).merge(children:)
|
||||||
end
|
end
|
||||||
|
|
||||||
root_ids.filter_map { |id| build_node.call(id, []) }
|
root_ids.filter_map { |id| build_node.call(id, []) }
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
class TagChildrenController < ApplicationController
|
|
||||||
def create
|
|
||||||
return head :unauthorized unless current_user
|
|
||||||
return head :forbidden unless current_user.admin?
|
|
||||||
|
|
||||||
parent_id = params[:parent_id]
|
|
||||||
child_id = params[:child_id]
|
|
||||||
return head :bad_request if parent_id.blank? || child_id.blank?
|
|
||||||
|
|
||||||
Tag.find(parent_id).children << Tag.find(child_id) rescue nil
|
|
||||||
|
|
||||||
head :no_content
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
return head :unauthorized unless current_user
|
|
||||||
return head :forbidden unless current_user.admin?
|
|
||||||
|
|
||||||
parent_id = params[:parent_id]
|
|
||||||
child_id = params[:child_id]
|
|
||||||
return head :bad_request if parent_id.blank? || child_id.blank?
|
|
||||||
|
|
||||||
Tag.find(parent_id).children.delete(Tag.find(child_id)) rescue nil
|
|
||||||
|
|
||||||
head :no_content
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -2,123 +2,32 @@ class TagsController < ApplicationController
|
|||||||
def index
|
def index
|
||||||
post_id = params[:post]
|
post_id = params[:post]
|
||||||
|
|
||||||
name = params[:name].presence
|
tags =
|
||||||
category = params[:category].presence
|
|
||||||
post_count_between = (params[:post_count_gte].presence || -1).to_i,
|
|
||||||
(params[:post_count_lte].presence || -1).to_i
|
|
||||||
post_count_between[0] = nil if post_count_between[0] < 0
|
|
||||||
post_count_between[1] = nil if post_count_between[1] < 0
|
|
||||||
created_between = params[:created_from].presence, params[:created_to].presence
|
|
||||||
updated_between = params[:updated_from].presence, params[:updated_to].presence
|
|
||||||
|
|
||||||
order = params[:order].to_s.split(':', 2).map(&:strip)
|
|
||||||
unless order[0].in?(['name', 'category', 'post_count', 'created_at', 'updated_at'])
|
|
||||||
order[0] = 'post_count'
|
|
||||||
end
|
|
||||||
unless order[1].in?(['asc', 'desc'])
|
|
||||||
order[1] = order[0].in?(['name', 'category']) ? 'asc' : 'desc'
|
|
||||||
end
|
|
||||||
|
|
||||||
page = (params[:page].presence || 1).to_i
|
|
||||||
limit = (params[:limit].presence || 20).to_i
|
|
||||||
|
|
||||||
page = 1 if page < 1
|
|
||||||
limit = 1 if limit < 1
|
|
||||||
|
|
||||||
offset = (page - 1) * limit
|
|
||||||
|
|
||||||
q =
|
|
||||||
if post_id.present?
|
if post_id.present?
|
||||||
Tag.joins(:posts, :tag_name)
|
Tag.joins(:posts).where(posts: { id: post_id })
|
||||||
else
|
else
|
||||||
Tag.joins(:tag_name)
|
Tag.all
|
||||||
end
|
end
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
q = q.where(posts: { id: post_id }) if post_id.present?
|
|
||||||
|
|
||||||
q = q.where('tag_names.name LIKE ?', "%#{ name }%") if name
|
render json: tags.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
q = q.where(category: category) if category
|
|
||||||
q = q.where('tags.post_count >= ?', post_count_between[0]) if post_count_between[0]
|
|
||||||
q = q.where('tags.post_count <= ?', post_count_between[1]) if post_count_between[1]
|
|
||||||
q = q.where('tags.created_at >= ?', created_between[0]) if created_between[0]
|
|
||||||
q = q.where('tags.created_at <= ?', created_between[1]) if created_between[1]
|
|
||||||
q = q.where('tags.updated_at >= ?', updated_between[0]) if updated_between[0]
|
|
||||||
q = q.where('tags.updated_at <= ?', updated_between[1]) if updated_between[1]
|
|
||||||
|
|
||||||
sort_sql =
|
|
||||||
case order[0]
|
|
||||||
when 'name'
|
|
||||||
'tag_names.name'
|
|
||||||
when 'category'
|
|
||||||
'CASE tags.category ' +
|
|
||||||
"WHEN 'deerjikist' THEN 0 " +
|
|
||||||
"WHEN 'meme' THEN 1 " +
|
|
||||||
"WHEN 'character' THEN 2 " +
|
|
||||||
"WHEN 'general' THEN 3 " +
|
|
||||||
"WHEN 'material' THEN 4 " +
|
|
||||||
"WHEN 'meta' THEN 5 " +
|
|
||||||
"WHEN 'nico' THEN 6 END"
|
|
||||||
else
|
|
||||||
"tags.#{ order[0] }"
|
|
||||||
end
|
|
||||||
tags = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, tags.id #{ order[1] }"))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset)
|
|
||||||
.to_a
|
|
||||||
|
|
||||||
render json: { tags: TagRepr.base(tags), count: q.size }
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def autocomplete
|
def autocomplete
|
||||||
q = params[:q].to_s.strip.sub(/\Anot:/i, '')
|
q = params[:q].to_s.strip
|
||||||
|
return render json: [] if q.blank?
|
||||||
|
|
||||||
with_nico = bool?(:nico, default: true)
|
tags = (Tag.joins(:tag_name).includes(:tag_name)
|
||||||
present_only = bool?(:present, default: true)
|
.where('(tags.category = ? AND tag_names.name LIKE ?) OR tag_names.name LIKE ?',
|
||||||
|
'nico', "nico:#{ q }%", "#{ q }%")
|
||||||
alias_rows =
|
.order(Arel.sql('post_count DESC, tag_names.name ASC'))
|
||||||
TagName
|
.limit(20))
|
||||||
.where('name LIKE ?', "#{ q }%")
|
render json: tags.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
.where.not(canonical_id: nil)
|
|
||||||
.pluck(:canonical_id, :name)
|
|
||||||
|
|
||||||
matched_alias_by_tag_name_id = { }
|
|
||||||
canonical_ids = []
|
|
||||||
|
|
||||||
alias_rows.each do |canonical_id, alias_name|
|
|
||||||
canonical_ids << canonical_id
|
|
||||||
matched_alias_by_tag_name_id[canonical_id] ||= alias_name
|
|
||||||
end
|
|
||||||
|
|
||||||
base = Tag.joins(:tag_name)
|
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
base = base.where('tags.post_count > 0') if present_only
|
|
||||||
|
|
||||||
canonical_hit =
|
|
||||||
base
|
|
||||||
.where(((with_nico ? '(tags.category = ? AND tag_names.name LIKE ?) OR ' : '') +
|
|
||||||
'tag_names.name LIKE ?'),
|
|
||||||
*(with_nico ? ['nico', "nico:#{ q }%"] : []), "#{ q }%")
|
|
||||||
|
|
||||||
tags =
|
|
||||||
if canonical_ids.present?
|
|
||||||
canonical_hit.or(base.where(tag_name_id: canonical_ids.uniq))
|
|
||||||
else
|
|
||||||
canonical_hit
|
|
||||||
end
|
|
||||||
|
|
||||||
tags = tags.order(Arel.sql('post_count DESC, tag_names.name')).limit(20).to_a
|
|
||||||
|
|
||||||
render json: tags.map { |tag|
|
|
||||||
TagRepr.base(tag).merge(matched_alias: matched_alias_by_tag_name_id[tag.tag_name_id])
|
|
||||||
}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
tag = Tag.joins(:tag_name)
|
tag = Tag.find_by(id: params[:id])
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
.find_by(id: params[:id])
|
|
||||||
if tag
|
if tag
|
||||||
render json: TagRepr.base(tag)
|
render json: tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
else
|
else
|
||||||
head :not_found
|
head :not_found
|
||||||
end
|
end
|
||||||
@@ -128,54 +37,11 @@ class TagsController < ApplicationController
|
|||||||
name = params[:name].to_s.strip
|
name = params[:name].to_s.strip
|
||||||
return head :bad_request if name.blank?
|
return head :bad_request if name.blank?
|
||||||
|
|
||||||
tag = Tag.joins(:tag_name)
|
tag = Tag.joins(:tag_name).includes(:tag_name).find_by(tag_names: { name: })
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
.find_by(tag_names: { name: })
|
|
||||||
if tag
|
if tag
|
||||||
render json: TagRepr.base(tag)
|
render json: tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
else
|
else
|
||||||
head :not_found
|
head :not_found
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def deerjikists
|
|
||||||
tag = Tag.joins(:tag_name)
|
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
.find_by(id: params[:id])
|
|
||||||
return head :not_found unless tag
|
|
||||||
|
|
||||||
render json: DeerjikistRepr.many(tag.deerjikists)
|
|
||||||
end
|
|
||||||
|
|
||||||
def deerjikists_by_name
|
|
||||||
name = params[:name].to_s.strip
|
|
||||||
return head :bad_request if name.blank?
|
|
||||||
|
|
||||||
tag = Tag.joins(:tag_name)
|
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
|
||||||
.find_by(tag_names: { name: })
|
|
||||||
return head :not_found unless tag
|
|
||||||
|
|
||||||
render json: DeerjikistRepr.many(tag.deerjikists)
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
return head :unauthorized unless current_user
|
|
||||||
return head :forbidden unless current_user.gte_member?
|
|
||||||
|
|
||||||
name = params[:name].presence
|
|
||||||
category = params[:category].presence
|
|
||||||
|
|
||||||
tag = Tag.find(params[:id])
|
|
||||||
|
|
||||||
if name.present?
|
|
||||||
tag.tag_name.update!(name:)
|
|
||||||
end
|
|
||||||
|
|
||||||
if category.present?
|
|
||||||
tag.update!(category:)
|
|
||||||
end
|
|
||||||
|
|
||||||
render json: TagRepr.base(tag)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
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: :desc)
|
|
||||||
|
|
||||||
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
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
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:,
|
|
||||||
watching_users: theatre.watching_users.as_json(only: [:id, :name]) }
|
|
||||||
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
|
|
||||||
@@ -2,20 +2,12 @@ class WikiPagesController < ApplicationController
|
|||||||
rescue_from Wiki::Commit::Conflict, with: :render_wiki_conflict
|
rescue_from Wiki::Commit::Conflict, with: :render_wiki_conflict
|
||||||
|
|
||||||
def index
|
def index
|
||||||
title = params[:title].to_s.strip
|
pages = WikiPage.all
|
||||||
if title.blank?
|
render json: pages.as_json(methods: [:title])
|
||||||
return render json: WikiPageRepr.base(WikiPage.joins(:tag_name).includes(:tag_name))
|
|
||||||
end
|
|
||||||
|
|
||||||
q = WikiPage.joins(:tag_name).includes(:tag_name)
|
|
||||||
.where('tag_names.name LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
|
|
||||||
render json: WikiPageRepr.base(q.limit(20))
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
page = WikiPage.joins(:tag_name)
|
page = WikiPage.find_by(id: params[:id])
|
||||||
.includes(:tag_name)
|
|
||||||
.find_by(id: params[:id])
|
|
||||||
render_wiki_page_or_404 page
|
render_wiki_page_or_404 page
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -23,7 +15,7 @@ class WikiPagesController < ApplicationController
|
|||||||
title = params[:title].to_s.strip
|
title = params[:title].to_s.strip
|
||||||
page = WikiPage.joins(:tag_name)
|
page = WikiPage.joins(:tag_name)
|
||||||
.includes(:tag_name)
|
.includes(:tag_name)
|
||||||
.find_by(tag_name: { name: title })
|
.find_by(tag_names: { name: title })
|
||||||
render_wiki_page_or_404 page
|
render_wiki_page_or_404 page
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -51,7 +43,7 @@ class WikiPagesController < ApplicationController
|
|||||||
from = params[:from].presence
|
from = params[:from].presence
|
||||||
to = params[:to].presence
|
to = params[:to].presence
|
||||||
|
|
||||||
page = WikiPage.joins(:tag_name).includes(:tag_name).find(id)
|
page = WikiPage.find(id)
|
||||||
|
|
||||||
from_rev = from && page.wiki_revisions.find(from)
|
from_rev = from && page.wiki_revisions.find(from)
|
||||||
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
|
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
|
||||||
@@ -83,20 +75,20 @@ class WikiPagesController < ApplicationController
|
|||||||
|
|
||||||
def create
|
def create
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
name = params[:title]&.strip
|
title = params[:title]&.strip
|
||||||
body = params[:body].to_s
|
body = params[:body].to_s
|
||||||
|
|
||||||
return head :unprocessable_entity if name.blank? || body.blank?
|
return head :unprocessable_entity if title.blank? || body.blank?
|
||||||
|
|
||||||
|
page = WikiPage.new(title:, created_user: current_user, updated_user: current_user)
|
||||||
|
|
||||||
tag_name = TagName.find_undiscard_or_create_by!(name:)
|
|
||||||
page = WikiPage.new(tag_name:, created_user: current_user, updated_user: current_user)
|
|
||||||
if page.save
|
if page.save
|
||||||
message = params[:message].presence
|
message = params[:message].presence
|
||||||
Wiki::Commit.content!(page:, body:, created_user: current_user, message:)
|
Wiki::Commit.content!(page:, body:, created_user: current_user, message:)
|
||||||
|
|
||||||
render json: WikiPageRepr.base(page), status: :created
|
render json: page.as_json(methods: [:title]), status: :created
|
||||||
else
|
else
|
||||||
render json: { errors: page.errors.full_messages },
|
render json: { errors: page.errors.full_messages },
|
||||||
status: :unprocessable_entity
|
status: :unprocessable_entity
|
||||||
@@ -105,7 +97,7 @@ class WikiPagesController < ApplicationController
|
|||||||
|
|
||||||
def update
|
def update
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
title = params[:title]&.strip
|
title = params[:title]&.strip
|
||||||
body = params[:body].to_s
|
body = params[:body].to_s
|
||||||
@@ -130,14 +122,19 @@ class WikiPagesController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def search
|
def search
|
||||||
index
|
title = params[:title].to_s.strip
|
||||||
|
|
||||||
|
q = WikiPage.joins(:tag_name).includes(:tag_name)
|
||||||
|
if title.present?
|
||||||
|
q = q.where('tag_names.name LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: q.limit(20).as_json(methods: [:title])
|
||||||
end
|
end
|
||||||
|
|
||||||
def changes
|
def changes
|
||||||
id = params[:id].presence
|
id = params[:id].presence
|
||||||
q = WikiRevision.joins(wiki_page: :tag_name)
|
q = WikiRevision.includes(:wiki_page, :created_user).order(id: :desc)
|
||||||
.includes(:created_user, wiki_page: :tag_name)
|
|
||||||
.order(id: :desc)
|
|
||||||
q = q.where(wiki_page_id: id) if id
|
q = q.where(wiki_page_id: id) if id
|
||||||
|
|
||||||
render json: q.limit(200).map { |rev|
|
render json: q.limit(200).map { |rev|
|
||||||
@@ -145,7 +142,7 @@ class WikiPagesController < ApplicationController
|
|||||||
pred: rev.base_revision_id,
|
pred: rev.base_revision_id,
|
||||||
succ: nil,
|
succ: nil,
|
||||||
wiki_page: { id: rev.wiki_page_id, title: rev.wiki_page.title },
|
wiki_page: { id: rev.wiki_page_id, title: rev.wiki_page.title },
|
||||||
user: rev.created_user && { id: rev.created_user.id, name: rev.created_user.name },
|
user: { id: rev.created_user.id, name: rev.created_user.name },
|
||||||
kind: rev.kind,
|
kind: rev.kind,
|
||||||
message: rev.message,
|
message: rev.message,
|
||||||
timestamp: rev.created_at }
|
timestamp: rev.created_at }
|
||||||
@@ -172,7 +169,8 @@ class WikiPagesController < ApplicationController
|
|||||||
succ = page.succ_revision_id(revision_id)
|
succ = page.succ_revision_id(revision_id)
|
||||||
updated_at = rev.created_at
|
updated_at = rev.created_at
|
||||||
|
|
||||||
render json: WikiPageRepr.base(page).merge(body:, revision_id:, pred:, succ:, updated_at:)
|
render json: page.as_json(methods: [:title])
|
||||||
|
.merge(body:, revision_id:, pred:, succ:, updated_at:)
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_revision page
|
def find_revision page
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
class Deerjikist < ApplicationRecord
|
|
||||||
self.primary_key = :platform, :code
|
|
||||||
|
|
||||||
belongs_to :tag
|
|
||||||
|
|
||||||
validates :platform, presence: true
|
|
||||||
validates :code, presence: true
|
|
||||||
validates :tag_id, presence: true
|
|
||||||
|
|
||||||
validate :tag_must_be_deerjikist
|
|
||||||
|
|
||||||
enum :platform, nico: 'nico', youtube: 'youtube'
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def tag_must_be_deerjikist
|
|
||||||
if tag && !(tag.deerjikist?)
|
|
||||||
errors.add :tag, 'タグはニジラー・カテゴリである必要があります.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
module MyDiscard
|
|
||||||
extend ActiveSupport::Concern
|
|
||||||
|
|
||||||
included { include Discard::Model }
|
|
||||||
|
|
||||||
class_methods do
|
|
||||||
def find_undiscard_or_create_by! attrs, &block
|
|
||||||
record = with_discarded.find_by(attrs)
|
|
||||||
|
|
||||||
if record&.discarded?
|
|
||||||
record.undiscard!
|
|
||||||
record.update_columns(created_at: record.reload.updated_at)
|
|
||||||
end
|
|
||||||
|
|
||||||
record or create!(attrs, &block)
|
|
||||||
rescue ActiveRecord::RecordNotUnique
|
|
||||||
retry
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
+19
-46
@@ -8,18 +8,16 @@ class Post < ApplicationRecord
|
|||||||
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
|
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
|
||||||
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
||||||
has_many :tags, through: :active_post_tags
|
has_many :tags, through: :active_post_tags
|
||||||
|
has_many :user_post_views, dependent: :destroy
|
||||||
has_many :user_post_views, dependent: :delete_all
|
has_many :post_similarities_as_post,
|
||||||
has_many :post_similarities, dependent: :delete_all
|
class_name: 'PostSimilarity',
|
||||||
|
foreign_key: :post_id
|
||||||
|
has_many :post_similarities_as_target_post,
|
||||||
|
class_name: 'PostSimilarity',
|
||||||
|
foreign_key: :target_post_id
|
||||||
has_one_attached :thumbnail
|
has_one_attached :thumbnail
|
||||||
|
|
||||||
before_validation :normalise_url
|
|
||||||
|
|
||||||
validates :url, presence: true, uniqueness: true
|
|
||||||
|
|
||||||
validate :validate_original_created_range
|
validate :validate_original_created_range
|
||||||
validate :url_must_be_http_url
|
|
||||||
|
|
||||||
def as_json options = { }
|
def as_json options = { }
|
||||||
super(options).merge({ thumbnail: thumbnail.attached? ?
|
super(options).merge({ thumbnail: thumbnail.attached? ?
|
||||||
@@ -30,15 +28,19 @@ class Post < ApplicationRecord
|
|||||||
super(options).merge(thumbnail: nil)
|
super(options).merge(thumbnail: nil)
|
||||||
end
|
end
|
||||||
|
|
||||||
def related limit: nil
|
def related(limit: nil)
|
||||||
ids = post_similarities.order(cos: :desc)
|
ids_with_cos =
|
||||||
ids = ids.limit(limit) if limit
|
post_similarities_as_post.select(:target_post_id, :cos)
|
||||||
ids = ids.pluck(:target_post_id)
|
.map { |ps| [ps.target_post_id, ps.cos] } +
|
||||||
return Post.none if ids.empty?
|
post_similarities_as_target_post.select(:post_id, :cos)
|
||||||
|
.map { |ps| [ps.post_id, ps.cos] }
|
||||||
|
|
||||||
Post.where(id: ids)
|
sorted = ids_with_cos.sort_by { |_, cos| -cos }
|
||||||
.with_attached_thumbnail
|
|
||||||
.order(Arel.sql("FIELD(posts.id, #{ ids.join(',') })"))
|
ids = sorted.map(&:first)
|
||||||
|
ids = ids.first(limit) if limit
|
||||||
|
|
||||||
|
Post.where(id: ids).index_by(&:id).values_at(*ids)
|
||||||
end
|
end
|
||||||
|
|
||||||
def resized_thumbnail!
|
def resized_thumbnail!
|
||||||
@@ -67,33 +69,4 @@ class Post < ApplicationRecord
|
|||||||
errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
|
errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def url_must_be_http_url
|
|
||||||
begin
|
|
||||||
u = URI.parse(url)
|
|
||||||
rescue URI::InvalidURIError
|
|
||||||
errors.add(:url, 'URL が不正です.')
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
if !(u in URI::HTTP) || u.host.blank?
|
|
||||||
errors.add(:url, 'URL が不正です.')
|
|
||||||
return
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def normalise_url
|
|
||||||
return if url.blank?
|
|
||||||
|
|
||||||
self.url = url.strip
|
|
||||||
|
|
||||||
u = URI.parse(url)
|
|
||||||
return unless u in URI::HTTP
|
|
||||||
|
|
||||||
u.host = u.host.downcase if u.host
|
|
||||||
u.path = u.path.sub(/\/\Z/, '') if u.path.present?
|
|
||||||
self.url = u.to_s
|
|
||||||
rescue URI::InvalidURIError
|
|
||||||
;
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
class PostSimilarity < ApplicationRecord
|
class PostSimilarity < ApplicationRecord
|
||||||
self.primary_key = :post_id, :target_post_id
|
belongs_to :post, class_name: 'Post', foreign_key: 'post_id'
|
||||||
|
belongs_to :target_post, class_name: 'Post', foreign_key: 'target_post_id'
|
||||||
belongs_to :post
|
|
||||||
belongs_to :target_post, class_name: 'Post'
|
|
||||||
end
|
end
|
||||||
|
|||||||
+34
-122
@@ -1,112 +1,80 @@
|
|||||||
class Tag < ApplicationRecord
|
class Tag < ApplicationRecord
|
||||||
include MyDiscard
|
has_many :post_tags, dependent: :delete_all, inverse_of: :tag
|
||||||
|
|
||||||
class NicoTagNormalisationError < ArgumentError
|
|
||||||
;
|
|
||||||
end
|
|
||||||
|
|
||||||
default_scope -> { kept }
|
|
||||||
|
|
||||||
has_many :post_tags, inverse_of: :tag
|
|
||||||
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :tag
|
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :tag
|
||||||
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
||||||
has_many :posts, through: :active_post_tags
|
has_many :posts, through: :active_post_tags
|
||||||
|
has_many :tag_aliases, dependent: :destroy
|
||||||
|
|
||||||
has_many :nico_tag_relations, foreign_key: :nico_tag_id, dependent: :destroy
|
has_many :nico_tag_relations, foreign_key: :nico_tag_id, dependent: :destroy
|
||||||
has_many :linked_tags, through: :nico_tag_relations, source: :tag
|
has_many :linked_tags, through: :nico_tag_relations, source: :tag
|
||||||
|
|
||||||
has_many :reversed_nico_tag_relations,
|
has_many :reversed_nico_tag_relations, class_name: 'NicoTagRelation',
|
||||||
class_name: 'NicoTagRelation', foreign_key: :tag_id, dependent: :destroy
|
foreign_key: :tag_id,
|
||||||
|
dependent: :destroy
|
||||||
has_many :linked_nico_tags, through: :reversed_nico_tag_relations, source: :nico_tag
|
has_many :linked_nico_tags, through: :reversed_nico_tag_relations, source: :nico_tag
|
||||||
|
|
||||||
has_many :tag_implications, foreign_key: :parent_tag_id, dependent: :destroy
|
has_many :tag_implications, foreign_key: :parent_tag_id, dependent: :destroy
|
||||||
has_many :children, through: :tag_implications, source: :tag
|
has_many :children, through: :tag_implications, source: :tag
|
||||||
|
|
||||||
has_many :reversed_tag_implications,
|
has_many :reversed_tag_implications, class_name: 'TagImplication',
|
||||||
class_name: 'TagImplication', foreign_key: :tag_id, dependent: :destroy
|
foreign_key: :tag_id,
|
||||||
|
dependent: :destroy
|
||||||
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
||||||
|
|
||||||
has_many :tag_similarities, dependent: :delete_all
|
|
||||||
has_many :tag_similarities_as_target,
|
|
||||||
class_name: 'TagSimilarity', foreign_key: :target_tag_id, dependent: :delete_all
|
|
||||||
|
|
||||||
has_many :deerjikists, dependent: :delete_all
|
|
||||||
|
|
||||||
belongs_to :tag_name
|
belongs_to :tag_name
|
||||||
delegate :wiki_page, to: :tag_name
|
|
||||||
|
|
||||||
delegate :name, to: :tag_name, allow_nil: true
|
delegate :name, to: :tag_name, allow_nil: true
|
||||||
validates :tag_name, presence: true
|
validates :tag_name, presence: true
|
||||||
|
|
||||||
enum :category, deerjikist: 'deerjikist',
|
enum :category, { deerjikist: 'deerjikist',
|
||||||
meme: 'meme',
|
meme: 'meme',
|
||||||
character: 'character',
|
character: 'character',
|
||||||
general: 'general',
|
general: 'general',
|
||||||
material: 'material',
|
material: 'material',
|
||||||
nico: 'nico',
|
nico: 'nico',
|
||||||
meta: 'meta'
|
meta: 'meta' }
|
||||||
|
|
||||||
validates :category, presence: true, inclusion: { in: Tag.categories.keys }
|
validates :category, presence: true, inclusion: { in: Tag.categories.keys }
|
||||||
|
|
||||||
validate :nico_tag_name_must_start_with_nico
|
validate :nico_tag_name_must_start_with_nico
|
||||||
validate :tag_name_must_be_canonical
|
|
||||||
validate :category_must_be_deerjikist_with_deerjikists
|
|
||||||
|
|
||||||
scope :nico_tags, -> { nico }
|
scope :nico_tags, -> { where(category: :nico) }
|
||||||
|
|
||||||
CATEGORY_PREFIXES = {
|
CATEGORY_PREFIXES = {
|
||||||
'general:' => :general,
|
'gen:' => 'general',
|
||||||
'gen:' => :general,
|
'djk:' => 'deerjikist',
|
||||||
'deerjikist:' => :deerjikist,
|
'meme:' => 'meme',
|
||||||
'djk:' => :deerjikist,
|
'chr:' => 'character',
|
||||||
'meme:' => :meme,
|
'mtr:' => 'material',
|
||||||
'character:' => :character,
|
'meta:' => 'meta' }.freeze
|
||||||
'chr:' => :character,
|
|
||||||
'material:' => :material,
|
|
||||||
'mtr:' => :material,
|
|
||||||
'meta:' => :meta }.freeze
|
|
||||||
|
|
||||||
def name= val
|
def name= val
|
||||||
(self.tag_name ||= build_tag_name).name = val
|
(self.tag_name ||= build_tag_name).name = val
|
||||||
end
|
end
|
||||||
|
|
||||||
def has_wiki = wiki_page.present?
|
def has_wiki
|
||||||
|
tag_name&.wiki_page.present?
|
||||||
|
end
|
||||||
|
|
||||||
def self.tagme
|
def self.tagme
|
||||||
@tagme ||= find_or_create_by_tag_name!('タグ希望', category: :meta)
|
@tagme ||= find_or_create_by_tag_name!('タグ希望', category: 'meta')
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.bot
|
def self.bot
|
||||||
@bot ||= find_or_create_by_tag_name!('bot操作', category: :meta)
|
@bot ||= find_or_create_by_tag_name!('bot操作', category: 'meta')
|
||||||
end
|
|
||||||
|
|
||||||
def self.no_deerjikist
|
|
||||||
@no_deerjikist ||= find_or_create_by_tag_name!('ニジラー情報不詳', category: :meta)
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.video
|
|
||||||
@video ||= find_or_create_by_tag_name!('動画', category: :meta)
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.niconico
|
|
||||||
@niconico ||= find_or_create_by_tag_name!('ニコニコ', category: :meta)
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.normalise_tags tag_names, with_tagme: true, deny_nico: true
|
|
||||||
if deny_nico && tag_names.any? { |n| n.downcase.start_with?('nico:') }
|
|
||||||
raise NicoTagNormalisationError
|
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.normalise_tags tag_names, with_tagme: true
|
||||||
tags = tag_names.map do |name|
|
tags = tag_names.map do |name|
|
||||||
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.downcase.start_with?(p) } || ['', nil]
|
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.start_with?(p) } || ['', nil]
|
||||||
name = TagName.canonicalise(name.sub(/\A#{ pf }/i, '')).first
|
name.delete_prefix!(pf)
|
||||||
find_or_create_by_tag_name!(name, category: (cat || :general)).tap do |tag|
|
find_or_create_by_tag_name!(name, category: (cat || 'general')).tap do |tag|
|
||||||
tag.update!(category: cat) if cat && tag.category != cat
|
if cat && tag.category != cat
|
||||||
|
tag.update!(category: cat)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
|
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
|
||||||
tags << Tag.no_deerjikist if tags.all? { |t| !(t.deerjikist?) }
|
|
||||||
tags.uniq(&:id)
|
tags.uniq(&:id)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -133,76 +101,20 @@ class Tag < ApplicationRecord
|
|||||||
(result + tags).uniq { |t| t.id }
|
(result + tags).uniq { |t| t.id }
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.find_or_create_by_tag_name! name, category:
|
def self.find_or_create_by_tag_name!(name, category:)
|
||||||
tn = TagName.find_undiscard_or_create_by!(name: name.to_s.strip)
|
tn = TagName.find_or_create_by!(name: name.to_s.strip)
|
||||||
tn = tn.canonical if tn.canonical_id?
|
Tag.find_or_create_by!(tag_name_id: tn.id) do |t|
|
||||||
|
|
||||||
Tag.find_undiscard_or_create_by!(tag_name_id: tn.id) do |t|
|
|
||||||
t.category = category
|
t.category = category
|
||||||
end
|
end
|
||||||
rescue ActiveRecord::RecordNotUnique
|
|
||||||
retry
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.merge_tags! target_tag, source_tags
|
|
||||||
target_tag => Tag
|
|
||||||
|
|
||||||
Tag.transaction do
|
|
||||||
Array(source_tags).compact.uniq.each do |source_tag|
|
|
||||||
source_tag => Tag
|
|
||||||
|
|
||||||
next if source_tag == target_tag
|
|
||||||
|
|
||||||
source_tag.post_tags.kept.find_each do |source_pt|
|
|
||||||
post_id = source_pt.post_id
|
|
||||||
source_pt.discard_by!(nil)
|
|
||||||
unless PostTag.kept.exists?(post_id:, tag: target_tag)
|
|
||||||
PostTag.create!(post_id:, tag: target_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
source_tag_name = source_tag.tag_name
|
|
||||||
|
|
||||||
if source_tag_name.wiki_page.present?
|
|
||||||
raise ActiveRecord::RecordInvalid.new(source_tag_name)
|
|
||||||
end
|
|
||||||
|
|
||||||
source_tag.discard!
|
|
||||||
|
|
||||||
if source_tag.nico?
|
|
||||||
source_tag_name.discard!
|
|
||||||
else
|
|
||||||
source_tag_name.update_columns(canonical_id: target_tag.tag_name_id,
|
|
||||||
updated_at: Time.current)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# 投稿件数を再集計
|
|
||||||
target_tag.update_columns(post_count: PostTag.kept.where(tag: target_tag).count)
|
|
||||||
end
|
|
||||||
|
|
||||||
target_tag.reload
|
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def nico_tag_name_must_start_with_nico
|
def nico_tag_name_must_start_with_nico
|
||||||
n = name.to_s
|
n = name.to_s
|
||||||
if ((nico? && !(n.downcase.start_with?('nico:'))) ||
|
if ((category == 'nico' && !(n.start_with?('nico:'))) ||
|
||||||
(!(nico?) && n.downcase.start_with?('nico:')))
|
(category != 'nico' && n.start_with?('nico:')))
|
||||||
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
|
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def tag_name_must_be_canonical
|
|
||||||
if tag_name&.canonical_id?
|
|
||||||
errors.add :tag_name, 'tag_names へは実体を示す必要があります.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def category_must_be_deerjikist_with_deerjikists
|
|
||||||
if !(deerjikist?) && deerjikists.exists?
|
|
||||||
errors.add :category, 'ニジラーと紐づいてゐるタグはニジラー・カテゴリである必要があります.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
class TagAlias < ApplicationRecord
|
||||||
|
belongs_to :tag
|
||||||
|
|
||||||
|
validates :tag_id, presence: true
|
||||||
|
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
|
||||||
|
end
|
||||||
@@ -1,8 +1,4 @@
|
|||||||
class TagName < ApplicationRecord
|
class TagName < ApplicationRecord
|
||||||
include MyDiscard
|
|
||||||
|
|
||||||
default_scope -> { kept }
|
|
||||||
|
|
||||||
has_one :tag
|
has_one :tag
|
||||||
has_one :wiki_page
|
has_one :wiki_page
|
||||||
|
|
||||||
@@ -10,44 +6,4 @@ class TagName < ApplicationRecord
|
|||||||
has_many :aliases, class_name: 'TagName', foreign_key: :canonical_id
|
has_many :aliases, class_name: 'TagName', foreign_key: :canonical_id
|
||||||
|
|
||||||
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
|
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
|
||||||
|
|
||||||
validate :canonical_must_be_canonical
|
|
||||||
validate :alias_name_must_not_have_prefix
|
|
||||||
validate :canonical_must_not_be_present_with_tag_or_wiki_page
|
|
||||||
validate :name_must_be_sanitised
|
|
||||||
|
|
||||||
def self.canonicalise names
|
|
||||||
names = Array(names).map { |n| n.to_s.strip }.reject(&:blank?)
|
|
||||||
return [] if names.blank?
|
|
||||||
|
|
||||||
tns = TagName.includes(:canonical).where(name: names).index_by(&:name)
|
|
||||||
|
|
||||||
names.map { |name| tns[name]&.canonical&.name || name }.uniq
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def canonical_must_be_canonical
|
|
||||||
if canonical&.canonical_id?
|
|
||||||
errors.add :canonical, 'canonical は実体を示す必要があります.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def alias_name_must_not_have_prefix
|
|
||||||
if canonical_id? && name.to_s.include?(':')
|
|
||||||
errors.add :name, 'エーリアス名にプレフィクスを含むことはできません.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def canonical_must_not_be_present_with_tag_or_wiki_page
|
|
||||||
if canonical_id? && (tag || wiki_page)
|
|
||||||
errors.add :canonical, 'タグもしくは Wiki の参照がある名前はエーリアスになれません.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def name_must_be_sanitised
|
|
||||||
if name? && name != TagNameSanitisationRule.sanitise(name)
|
|
||||||
errors.add :name, '名前に使用できない文字が含まれてゐます.'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
class TagNameSanitisationRule < ApplicationRecord
|
|
||||||
include Discard::Model
|
|
||||||
|
|
||||||
self.primary_key = :priority
|
|
||||||
|
|
||||||
default_scope -> { kept }
|
|
||||||
|
|
||||||
validates :source_pattern, presence: true, uniqueness: true
|
|
||||||
|
|
||||||
validate :source_pattern_must_be_regexp
|
|
||||||
|
|
||||||
class << self
|
|
||||||
def sanitise(name) =
|
|
||||||
rules.reduce(name.dup) { |name, (pattern, replacement)| name.gsub(pattern, replacement) }
|
|
||||||
|
|
||||||
def apply!
|
|
||||||
TagName.find_each do |tn|
|
|
||||||
name = sanitise(tn.name)
|
|
||||||
next if name == tn.name
|
|
||||||
|
|
||||||
TagName.transaction do
|
|
||||||
existing_tn = TagName.find_by(name:)
|
|
||||||
if existing_tn
|
|
||||||
existing_tn = existing_tn.canonical || existing_tn
|
|
||||||
next if existing_tn.id == tn.id
|
|
||||||
|
|
||||||
existing_tag = Tag.find_by(tag_name_id: existing_tn.id)
|
|
||||||
source_tag = Tag.find_by(tag_name_id: tn.id)
|
|
||||||
|
|
||||||
if existing_tag
|
|
||||||
Tag.merge_tags!(existing_tag, source_tag) if tn.tag
|
|
||||||
elsif source_tag
|
|
||||||
source_tag.update_columns(tag_name_id: existing_tn.id, updated_at: Time.current)
|
|
||||||
end
|
|
||||||
tn.discard!
|
|
||||||
|
|
||||||
next
|
|
||||||
end
|
|
||||||
|
|
||||||
# TagName 側の自動サニタイズを回避
|
|
||||||
tn.update_columns(name:, updated_at: Time.current)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def rules = kept.order(:priority).map { |r| [Regexp.new(r.source_pattern), r.replacement] }
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def source_pattern_must_be_regexp
|
|
||||||
Regexp.new(source_pattern)
|
|
||||||
rescue RegexpError
|
|
||||||
errors.add :source_pattern, '変な正規表現だね〜(笑)'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
class TagSimilarity < ApplicationRecord
|
class TagSimilarity < ApplicationRecord
|
||||||
self.primary_key = :tag_id, :target_tag_id
|
belongs_to :tag, class_name: 'Tag', foreign_key: 'tag_id'
|
||||||
|
belongs_to :target_tag, class_name: 'Tag', foreign_key: 'target_tag_id'
|
||||||
belongs_to :tag
|
|
||||||
belongs_to :target_tag, class_name: 'Tag'
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
class TheatreComment < ApplicationRecord
|
|
||||||
include Discard::Model
|
|
||||||
|
|
||||||
self.primary_key = :theatre_id, :no
|
|
||||||
|
|
||||||
belongs_to :theatre
|
|
||||||
belongs_to :user
|
|
||||||
end
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,23 +1,29 @@
|
|||||||
class User < ApplicationRecord
|
class User < ApplicationRecord
|
||||||
enum :role, guest: 'guest', member: 'member', admin: 'admin'
|
enum :role, { guest: 'guest', member: 'member', admin: 'admin' }
|
||||||
|
|
||||||
validates :name, length: { maximum: 255 }
|
validates :name, length: { maximum: 255 }
|
||||||
validates :inheritance_code, presence: true, length: { maximum: 64 }
|
validates :inheritance_code, presence: true, length: { maximum: 64 }
|
||||||
validates :role, presence: true, inclusion: { in: roles.keys }
|
validates :role, presence: true, inclusion: { in: roles.keys }
|
||||||
validates :banned, inclusion: { in: [true, false] }
|
validates :banned, inclusion: { in: [true, false] }
|
||||||
|
|
||||||
has_many :created_posts,
|
has_many :posts
|
||||||
class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
|
|
||||||
has_many :settings
|
has_many :settings
|
||||||
has_many :user_ips, dependent: :destroy
|
has_many :user_ips, dependent: :destroy
|
||||||
has_many :ip_addresses, through: :user_ips
|
has_many :ip_addresses, through: :user_ips
|
||||||
has_many :user_post_views, dependent: :destroy
|
has_many :user_post_views, dependent: :destroy
|
||||||
has_many :viewed_posts, through: :user_post_views, source: :post
|
has_many :viewed_posts, through: :user_post_views, source: :post
|
||||||
has_many :created_wiki_pages,
|
has_many :created_wiki_pages, class_name: 'WikiPage', foreign_key: 'created_user_id', dependent: :nullify
|
||||||
class_name: 'WikiPage', foreign_key: :created_user_id, dependent: :nullify
|
has_many :updated_wiki_pages, class_name: 'WikiPage', foreign_key: 'updated_user_id', dependent: :nullify
|
||||||
has_many :updated_wiki_pages,
|
|
||||||
class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify
|
|
||||||
|
|
||||||
def viewed?(post) = user_post_views.exists?(post_id: post.id)
|
def viewed? post
|
||||||
def gte_member? = member? || admin?
|
user_post_views.exists? post_id: post.id
|
||||||
|
end
|
||||||
|
|
||||||
|
def member?
|
||||||
|
['member', 'admin'].include?(role)
|
||||||
|
end
|
||||||
|
|
||||||
|
def admin?
|
||||||
|
role == 'admin'
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
class UserIp < ApplicationRecord
|
class UserIp < ApplicationRecord
|
||||||
self.primary_key = :user_id, :ip_address_id
|
|
||||||
|
|
||||||
belongs_to :user
|
belongs_to :user
|
||||||
belongs_to :ip_address
|
belongs_to :ip_address
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
class UserPostView < ApplicationRecord
|
class UserPostView < ApplicationRecord
|
||||||
self.primary_key = :user_id, :post_id
|
|
||||||
|
|
||||||
belongs_to :user
|
belongs_to :user
|
||||||
belongs_to :post
|
belongs_to :post
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ class WikiLine < ApplicationRecord
|
|||||||
sha = Digest::SHA256.hexdigest(body)
|
sha = Digest::SHA256.hexdigest(body)
|
||||||
now = Time.current
|
now = Time.current
|
||||||
|
|
||||||
upsert(sha256: sha, body:, created_at: now, updated_at: now)
|
upsert({ sha256: sha, body:, created_at: now, updated_at: now })
|
||||||
|
|
||||||
find_by!(sha256: sha)
|
find_by!(sha256: sha)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,10 +2,6 @@ require 'set'
|
|||||||
|
|
||||||
|
|
||||||
class WikiPage < ApplicationRecord
|
class WikiPage < ApplicationRecord
|
||||||
include MyDiscard
|
|
||||||
|
|
||||||
default_scope -> { kept }
|
|
||||||
|
|
||||||
has_many :wiki_revisions, dependent: :destroy
|
has_many :wiki_revisions, dependent: :destroy
|
||||||
belongs_to :created_user, class_name: 'User'
|
belongs_to :created_user, class_name: 'User'
|
||||||
belongs_to :updated_user, class_name: 'User'
|
belongs_to :updated_user, class_name: 'User'
|
||||||
@@ -18,13 +14,17 @@ class WikiPage < ApplicationRecord
|
|||||||
belongs_to :tag_name
|
belongs_to :tag_name
|
||||||
validates :tag_name, presence: true
|
validates :tag_name, presence: true
|
||||||
|
|
||||||
def title = tag_name.name
|
def title
|
||||||
|
tag_name.name
|
||||||
|
end
|
||||||
|
|
||||||
def title= val
|
def title= val
|
||||||
(self.tag_name ||= build_tag_name).name = val
|
(self.tag_name ||= build_tag_name).name = val
|
||||||
end
|
end
|
||||||
|
|
||||||
def current_revision = wiki_revisions.order(id: :desc).first
|
def current_revision
|
||||||
|
wiki_revisions.order(id: :desc).first
|
||||||
|
end
|
||||||
|
|
||||||
def body
|
def body
|
||||||
rev = current_revision
|
rev = current_revision
|
||||||
@@ -49,8 +49,11 @@ class WikiPage < ApplicationRecord
|
|||||||
page
|
page
|
||||||
end
|
end
|
||||||
|
|
||||||
def pred_revision_id(revision_id) =
|
def pred_revision_id revision_id
|
||||||
wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
|
wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
|
||||||
def succ_revision_id(revision_id) =
|
end
|
||||||
|
|
||||||
|
def succ_revision_id revision_id
|
||||||
wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
|
wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ class WikiRevision < ApplicationRecord
|
|||||||
has_many :wiki_revision_lines, dependent: :delete_all
|
has_many :wiki_revision_lines, dependent: :delete_all
|
||||||
has_many :wiki_lines, through: :wiki_revision_lines
|
has_many :wiki_lines, through: :wiki_revision_lines
|
||||||
|
|
||||||
enum :kind, content: 0, redirect: 1
|
enum :kind, { content: 0, redirect: 1 }
|
||||||
|
|
||||||
validates :kind, presence: true
|
validates :kind, presence: true
|
||||||
validates :lines_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
validates :lines_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
# frozen_string_literal: true
|
|
||||||
|
|
||||||
|
|
||||||
module DeerjikistRepr
|
|
||||||
BASE = { only: [:platform, :code], include: { tag: TagRepr::BASE } }.freeze
|
|
||||||
|
|
||||||
module_function
|
|
||||||
|
|
||||||
def base deerjikist
|
|
||||||
deerjikist.as_json(BASE)
|
|
||||||
end
|
|
||||||
|
|
||||||
def many deerjikists
|
|
||||||
deerjikists.map { |d| base(d) }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
# frozen_string_literal: true
|
|
||||||
|
|
||||||
|
|
||||||
module PostRepr
|
|
||||||
BASE = { include: { tags: TagRepr::BASE, uploaded_user: UserRepr::BASE } }.freeze
|
|
||||||
|
|
||||||
module_function
|
|
||||||
|
|
||||||
def base post, current_user = nil
|
|
||||||
json = post.as_json(BASE)
|
|
||||||
return json.merge(viewed: false) unless current_user
|
|
||||||
|
|
||||||
viewed = current_user.viewed?(post)
|
|
||||||
json.merge(viewed:)
|
|
||||||
end
|
|
||||||
|
|
||||||
def many posts, current_user = nil
|
|
||||||
posts.map { |p| base(p, current_user) }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# frozen_string_literal: true
|
|
||||||
|
|
||||||
|
|
||||||
module TagRepr
|
|
||||||
BASE = { only: [:id, :category, :post_count, :created_at, :updated_at],
|
|
||||||
methods: [:name, :has_wiki] }.freeze
|
|
||||||
|
|
||||||
module_function
|
|
||||||
|
|
||||||
def base tag
|
|
||||||
tag.as_json(BASE)
|
|
||||||
end
|
|
||||||
|
|
||||||
def many tags
|
|
||||||
tags.map { |t| base(t) }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# frozen_string_literal: true
|
|
||||||
|
|
||||||
|
|
||||||
module UserRepr
|
|
||||||
BASE = { only: [:id, :name] }.freeze
|
|
||||||
|
|
||||||
module_function
|
|
||||||
|
|
||||||
def base user
|
|
||||||
user.as_json(BASE)
|
|
||||||
end
|
|
||||||
|
|
||||||
def many users
|
|
||||||
users.map { |u| base(u) }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# frozen_string_literal: true
|
|
||||||
|
|
||||||
|
|
||||||
module WikiPageRepr
|
|
||||||
BASE = { methods: [:title] }.freeze
|
|
||||||
|
|
||||||
module_function
|
|
||||||
|
|
||||||
def base wiki_page
|
|
||||||
wiki_page.as_json(BASE)
|
|
||||||
end
|
|
||||||
|
|
||||||
def many wiki_pages
|
|
||||||
wiki_pages.map { |p| base(p) }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
module Similarity
|
|
||||||
class Calc
|
|
||||||
def self.call model, tgt
|
|
||||||
similarity_model = "#{ model.name }Similarity".constantize
|
|
||||||
|
|
||||||
# 最大保存件数
|
|
||||||
n = 20
|
|
||||||
|
|
||||||
similarity_model.delete_all
|
|
||||||
|
|
||||||
posts = model.includes(tgt).select(:id).to_a
|
|
||||||
|
|
||||||
tag_ids = { }
|
|
||||||
tag_cnts = { }
|
|
||||||
|
|
||||||
posts.each do |p|
|
|
||||||
arr = p.public_send(tgt).map(&:id).sort
|
|
||||||
tag_ids[p.id] = arr
|
|
||||||
tag_cnts[p.id] = arr.size
|
|
||||||
end
|
|
||||||
|
|
||||||
intersection_size = -> a, b do
|
|
||||||
i = 0
|
|
||||||
j = 0
|
|
||||||
cnt = 0
|
|
||||||
while i < a.size && j < b.size
|
|
||||||
a_i = a[i]
|
|
||||||
b_j = b[j]
|
|
||||||
if a_i == b_j
|
|
||||||
cnt += 1
|
|
||||||
i += 1
|
|
||||||
j += 1
|
|
||||||
elsif a_i < b_j
|
|
||||||
i += 1
|
|
||||||
else
|
|
||||||
j += 1
|
|
||||||
end
|
|
||||||
end
|
|
||||||
cnt
|
|
||||||
end
|
|
||||||
|
|
||||||
push_topk = -> list, cos, target_id do
|
|
||||||
return if list.size >= n && cos <= list[-1][0]
|
|
||||||
|
|
||||||
idx = nil
|
|
||||||
list.each_with_index do |(c, tid), i|
|
|
||||||
if tid == target_id
|
|
||||||
idx = i
|
|
||||||
break
|
|
||||||
end
|
|
||||||
end
|
|
||||||
if idx
|
|
||||||
return if cos <= list[idx][0]
|
|
||||||
list.delete_at(idx)
|
|
||||||
end
|
|
||||||
|
|
||||||
insert_at = list.size
|
|
||||||
list.each_with_index do |(c, _), i|
|
|
||||||
if cos > c
|
|
||||||
insert_at = i
|
|
||||||
break
|
|
||||||
end
|
|
||||||
end
|
|
||||||
list.insert(insert_at, [cos, target_id])
|
|
||||||
list.pop if list.size > n
|
|
||||||
end
|
|
||||||
|
|
||||||
top = Hash.new { |h, key| h[key] = [] }
|
|
||||||
|
|
||||||
ids = posts.map(&:id)
|
|
||||||
ids.each_with_index do |post_id, i|
|
|
||||||
a = tag_ids[post_id]
|
|
||||||
a_cnt = tag_cnts[post_id]
|
|
||||||
|
|
||||||
((i + 1)...ids.size).each do |j|
|
|
||||||
target_id = ids[j]
|
|
||||||
b = tag_ids[target_id]
|
|
||||||
b_cnt = tag_cnts[target_id]
|
|
||||||
|
|
||||||
norm = Math.sqrt(a_cnt * b_cnt)
|
|
||||||
cos = norm.zero? ? 0.0 : intersection_size.(a, b).fdiv(norm)
|
|
||||||
|
|
||||||
push_topk.(top[post_id], cos, target_id)
|
|
||||||
push_topk.(top[target_id], cos, post_id)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
buf = []
|
|
||||||
flush = -> do
|
|
||||||
return if buf.empty?
|
|
||||||
similarity_model.insert_all!(buf)
|
|
||||||
buf.clear
|
|
||||||
end
|
|
||||||
|
|
||||||
top.each do |post_id, list|
|
|
||||||
list.each do |cos, target_post_id|
|
|
||||||
buf << { "#{ model.name.underscore }_id".to_sym => post_id,
|
|
||||||
"target_#{ model.name.underscore }_id".to_sym => target_post_id,
|
|
||||||
cos: }
|
|
||||||
flush.call if buf.size >= 1_000
|
|
||||||
end
|
|
||||||
end
|
|
||||||
flush.call
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -28,8 +28,4 @@
|
|||||||
# enabled: "ON"
|
# enabled: "ON"
|
||||||
|
|
||||||
en:
|
en:
|
||||||
activerecord:
|
hello: "Hello world"
|
||||||
errors:
|
|
||||||
messages:
|
|
||||||
record_invalid: "Validation failed: %{errors}"
|
|
||||||
taken: 'イキスギ!'
|
|
||||||
|
|||||||
+2
-34
@@ -1,23 +1,10 @@
|
|||||||
Rails.application.routes.draw do
|
Rails.application.routes.draw do
|
||||||
resources :nico_tags, path: 'tags/nico', only: [:index, :update]
|
resources :nico_tags, path: 'tags/nico', only: [:index, :update]
|
||||||
|
|
||||||
scope 'tags/:parent_id/children', controller: :tag_children do
|
resources :tags, only: [:index, :show] do
|
||||||
post ':child_id', action: :create
|
|
||||||
delete ':child_id', action: :destroy
|
|
||||||
end
|
|
||||||
|
|
||||||
resources :tags, only: [:index, :show, :update] do
|
|
||||||
collection do
|
collection do
|
||||||
get :autocomplete
|
get :autocomplete
|
||||||
|
get 'name/:name', action: :show_by_name
|
||||||
scope :name do
|
|
||||||
get ':name/deerjikists', action: :deerjikists_by_name
|
|
||||||
get ':name', action: :show_by_name
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
member do
|
|
||||||
get :deerjikists
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -62,23 +49,4 @@ Rails.application.routes.draw do
|
|||||||
post 'code/renew', action: :renew
|
post 'code/renew', action: :renew
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
resources :deerjikists, only: [] do
|
|
||||||
collection do
|
|
||||||
scope ':platform/:code' do
|
|
||||||
get '', action: :show
|
|
||||||
put '', action: :update
|
|
||||||
delete '', action: :destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
resources :theatres, only: [:show] do
|
|
||||||
member do
|
|
||||||
put :watching
|
|
||||||
patch :next_post
|
|
||||||
end
|
|
||||||
|
|
||||||
resources :comments, controller: :theatre_comments, only: [:index, :create]
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
class AddUniqueIndexToUrlInPosts < ActiveRecord::Migration[7.1]
|
|
||||||
def change
|
|
||||||
change_column :posts, :url, :string, limit: 768
|
|
||||||
add_index :posts, :url, unique: true, name: 'index_posts_on_url'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
class ChangePostSimilaritiesToCompositePk < ActiveRecord::Migration[8.0]
|
|
||||||
def up
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
post_similarities
|
|
||||||
MODIFY COLUMN id BIGINT NOT NULL
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
post_similarities
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_column :post_similarities, :id
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
post_similarities
|
|
||||||
ADD PRIMARY KEY (post_id, target_post_id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
post_similarities
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
post_similarities
|
|
||||||
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
|
|
||||||
, ADD PRIMARY KEY (id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
class ChangeTagSimilaritiesToCompositePk < ActiveRecord::Migration[8.0]
|
|
||||||
def up
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
tag_similarities
|
|
||||||
MODIFY COLUMN id BIGINT NOT NULL
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
tag_similarities
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_column :tag_similarities, :id
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
tag_similarities
|
|
||||||
ADD PRIMARY KEY (tag_id, target_tag_id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
tag_similarities
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
tag_similarities
|
|
||||||
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
|
|
||||||
, ADD PRIMARY KEY (id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
class AddIndexToPostSimilarities < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
remove_index :post_similarities, name: 'index_post_similarities_on_post_id'
|
|
||||||
|
|
||||||
add_index :post_similarities, [:post_id, :cos],
|
|
||||||
order: { cos: :desc },
|
|
||||||
name: 'index_post_similarities_on_post_id_and_cos'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
class AddIndexToTagSimilarities < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
remove_index :tag_similarities, name: 'index_tag_similarities_on_tag_id'
|
|
||||||
|
|
||||||
add_index :tag_similarities, [:tag_id, :cos],
|
|
||||||
order: { cos: :desc },
|
|
||||||
name: 'index_tag_similarities_on_tag_id_and_cos'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
class AddUniqueIndexToIpAddresses < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
add_index :ip_addresses, :ip_address, unique: true, name: 'index_ip_addresses_on_ip_address'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
class ChangeUserIpsToCompositePk < ActiveRecord::Migration[8.0]
|
|
||||||
def up
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_ips
|
|
||||||
MODIFY COLUMN id BIGINT NOT NULL
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_ips
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_column :user_ips, :id
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_ips
|
|
||||||
ADD PRIMARY KEY (user_id, ip_address_id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_index :user_ips, name: 'index_user_ips_on_user_id'
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_ips
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_ips
|
|
||||||
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
|
|
||||||
, ADD PRIMARY KEY (id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
add_index :user_ips, :user_id, name: 'index_user_ips_on_user_id'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
class ChangeUserPostViewsToCompositePk < ActiveRecord::Migration[8.0]
|
|
||||||
def up
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_post_views
|
|
||||||
MODIFY COLUMN id BIGINT NOT NULL
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_post_views
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_column :user_post_views, :id
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_post_views
|
|
||||||
ADD PRIMARY KEY (user_id, post_id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
remove_index :user_post_views, name: 'index_user_post_views_on_user_id'
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_post_views
|
|
||||||
DROP PRIMARY KEY
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
execute <<~SQL
|
|
||||||
ALTER TABLE
|
|
||||||
user_post_views
|
|
||||||
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
|
|
||||||
, ADD PRIMARY KEY (id)
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
add_index :user_post_views, :user_id, name: 'index_user_post_views_on_user_id'
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
class CreateDeerjikists < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
create_table :deerjikists, primary_key: [:platform, :code] do |t|
|
|
||||||
t.string :platform, null: false, limit: 16
|
|
||||||
t.string :code, null: false
|
|
||||||
t.references :tag, null: false
|
|
||||||
t.timestamps
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
class CreateTagNameSanitisationRules < ActiveRecord::Migration[8.0]
|
|
||||||
def up
|
|
||||||
create_table :tag_name_sanitisation_rules, id: :integer, primary_key: :priority do |t|
|
|
||||||
t.string :source_pattern, null: false
|
|
||||||
t.string :replacement, null: false
|
|
||||||
t.timestamps
|
|
||||||
t.datetime :discarded_at
|
|
||||||
t.index :source_pattern, unique: true
|
|
||||||
t.index :discarded_at
|
|
||||||
end
|
|
||||||
|
|
||||||
now = ActiveRecord::Base.connection.quote(Time.current)
|
|
||||||
execute <<~SQL
|
|
||||||
INSERT INTO
|
|
||||||
tag_name_sanitisation_rules(priority, source_pattern, replacement, created_at, updated_at)
|
|
||||||
VALUES
|
|
||||||
(10, '\\\\*', '_', #{ now }, #{ now })
|
|
||||||
, (20, '\\\\?', '_', #{ now }, #{ now })
|
|
||||||
, (25, '\\\\/', '_', #{ now }, #{ now })
|
|
||||||
, (30, '_+', '_', #{ now }, #{ now })
|
|
||||||
, (40, '_$', '', #{ now }, #{ now })
|
|
||||||
, (45, '^([^:]+\\\\:)?_', '\\\\1', #{ now }, #{ now })
|
|
||||||
, (50, '^([^:]+\\\\:)?$', '\\\\1null', #{ now }, #{ now })
|
|
||||||
;
|
|
||||||
SQL
|
|
||||||
end
|
|
||||||
|
|
||||||
def down
|
|
||||||
drop_table :tag_name_sanitisation_rules
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
class AddDiscardedAtToTags < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
add_column :tags, :discarded_at, :datetime
|
|
||||||
add_index :tags, :discarded_at
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
class AddDiscardedAtToTagNames < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
add_column :tag_names, :discarded_at, :datetime
|
|
||||||
add_index :tag_names, :discarded_at
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
class AddDiscardedAtToWikiPages < ActiveRecord::Migration[8.0]
|
|
||||||
def change
|
|
||||||
add_column :wiki_pages, :discarded_at, :datetime
|
|
||||||
add_index :wiki_pages, :discarded_at
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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
|
|
||||||
生成ファイル
+10
-89
@@ -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_17_015000) do
|
ActiveRecord::Schema[8.0].define(version: 2026_01_12_111800) 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
|
||||||
@@ -39,21 +39,11 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
|
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "deerjikists", primary_key: ["platform", "code"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
|
||||||
t.string "platform", limit: 16, null: false
|
|
||||||
t.string "code", null: false
|
|
||||||
t.bigint "tag_id", null: false
|
|
||||||
t.datetime "created_at", null: false
|
|
||||||
t.datetime "updated_at", null: false
|
|
||||||
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
|
|
||||||
end
|
|
||||||
|
|
||||||
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.binary "ip_address", limit: 16, null: false
|
t.binary "ip_address", limit: 16, null: false
|
||||||
t.boolean "banned", default: false, null: false
|
t.boolean "banned", default: false, null: false
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["ip_address"], name: "index_ip_addresses_on_ip_address", unique: true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "nico_tag_relations", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "nico_tag_relations", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -65,11 +55,11 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.index ["tag_id"], name: "index_nico_tag_relations_on_tag_id"
|
t.index ["tag_id"], name: "index_nico_tag_relations_on_tag_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "post_similarities", primary_key: ["post_id", "target_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "post_similarities", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.bigint "post_id", null: false
|
t.bigint "post_id", null: false
|
||||||
t.bigint "target_post_id", null: false
|
t.bigint "target_post_id", null: false
|
||||||
t.float "cos", null: false
|
t.float "cos", null: false
|
||||||
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos", order: { cos: :desc }
|
t.index ["post_id"], name: "index_post_similarities_on_post_id"
|
||||||
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
|
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -95,7 +85,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
|
|
||||||
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "title"
|
t.string "title"
|
||||||
t.string "url", limit: 768, null: false
|
t.string "url", limit: 2000, null: false
|
||||||
t.string "thumbnail_base", limit: 2000
|
t.string "thumbnail_base", limit: 2000
|
||||||
t.bigint "parent_id"
|
t.bigint "parent_id"
|
||||||
t.bigint "uploaded_user_id"
|
t.bigint "uploaded_user_id"
|
||||||
@@ -105,7 +95,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["parent_id"], name: "index_posts_on_parent_id"
|
t.index ["parent_id"], name: "index_posts_on_parent_id"
|
||||||
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
|
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
|
||||||
t.index ["url"], name: "index_posts_on_url", unique: true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -127,32 +116,20 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.index ["tag_id"], name: "index_tag_implications_on_tag_id"
|
t.index ["tag_id"], name: "index_tag_implications_on_tag_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "tag_name_sanitisation_rules", primary_key: "priority", id: :integer, charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
|
||||||
t.string "source_pattern", null: false
|
|
||||||
t.string "replacement", null: false
|
|
||||||
t.datetime "created_at", null: false
|
|
||||||
t.datetime "updated_at", null: false
|
|
||||||
t.datetime "discarded_at"
|
|
||||||
t.index ["discarded_at"], name: "index_tag_name_sanitisation_rules_on_discarded_at"
|
|
||||||
t.index ["source_pattern"], name: "index_tag_name_sanitisation_rules_on_source_pattern", unique: true
|
|
||||||
end
|
|
||||||
|
|
||||||
create_table "tag_names", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "tag_names", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.bigint "canonical_id"
|
t.bigint "canonical_id"
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.datetime "discarded_at"
|
|
||||||
t.index ["canonical_id"], name: "index_tag_names_on_canonical_id"
|
t.index ["canonical_id"], name: "index_tag_names_on_canonical_id"
|
||||||
t.index ["discarded_at"], name: "index_tag_names_on_discarded_at"
|
|
||||||
t.index ["name"], name: "index_tag_names_on_name", unique: true
|
t.index ["name"], name: "index_tag_names_on_name", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "tag_similarities", primary_key: ["tag_id", "target_tag_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "tag_similarities", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.bigint "tag_id", null: false
|
t.bigint "tag_id", null: false
|
||||||
t.bigint "target_tag_id", null: false
|
t.bigint "target_tag_id", null: false
|
||||||
t.float "cos", null: false
|
t.float "cos", null: false
|
||||||
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos", order: { cos: :desc }
|
t.index ["tag_id"], name: "index_tag_similarities_on_tag_id"
|
||||||
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
|
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -162,72 +139,25 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.integer "post_count", default: 0, null: false
|
t.integer "post_count", default: 0, null: false
|
||||||
t.datetime "discarded_at"
|
|
||||||
t.index ["discarded_at"], name: "index_tags_on_discarded_at"
|
|
||||||
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|
|
create_table "user_ips", 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|
|
|
||||||
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
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["ip_address_id"], name: "index_user_ips_on_ip_address_id"
|
t.index ["ip_address_id"], name: "index_user_ips_on_ip_address_id"
|
||||||
|
t.index ["user_id"], name: "index_user_ips_on_user_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "user_post_views", primary_key: ["user_id", "post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "user_post_views", 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 "post_id", null: false
|
t.bigint "post_id", null: false
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["post_id"], name: "index_user_post_views_on_post_id"
|
t.index ["post_id"], name: "index_user_post_views_on_post_id"
|
||||||
|
t.index ["user_id"], name: "index_user_post_views_on_user_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -253,9 +183,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
|
|||||||
t.bigint "updated_user_id", null: false
|
t.bigint "updated_user_id", null: false
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.datetime "discarded_at"
|
|
||||||
t.index ["created_user_id"], name: "index_wiki_pages_on_created_user_id"
|
t.index ["created_user_id"], name: "index_wiki_pages_on_created_user_id"
|
||||||
t.index ["discarded_at"], name: "index_wiki_pages_on_discarded_at"
|
|
||||||
t.index ["tag_name_id"], name: "index_wiki_pages_on_tag_name_id", unique: true
|
t.index ["tag_name_id"], name: "index_wiki_pages_on_tag_name_id", unique: true
|
||||||
t.index ["updated_user_id"], name: "index_wiki_pages_on_updated_user_id"
|
t.index ["updated_user_id"], name: "index_wiki_pages_on_updated_user_id"
|
||||||
end
|
end
|
||||||
@@ -309,13 +237,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) 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"
|
||||||
|
|||||||
@@ -1,6 +1,28 @@
|
|||||||
namespace :post_similarity do
|
namespace :post_similarity do
|
||||||
desc '関聯投稿テーブル作成'
|
desc '関聯投稿テーブル作成'
|
||||||
task calc: :environment do
|
task calc: :environment do
|
||||||
Similarity::Calc.call(Post, :tags)
|
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
|
||||||
|
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
|
||||||
|
cos = -> a, b do
|
||||||
|
na = norm.(a)
|
||||||
|
nb = norm.(b)
|
||||||
|
if na.zero? || nb.zero?
|
||||||
|
0.0
|
||||||
|
else
|
||||||
|
dot.(a, b) / na / nb
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
posts = Post.includes(:tags).to_a
|
||||||
|
posts.each_with_index do |post, i|
|
||||||
|
existence_of_tags = post.tags.index_with(1)
|
||||||
|
((i + 1)...posts.size).each do |j|
|
||||||
|
target_post = posts[j]
|
||||||
|
existence_of_target_tags = target_post.tags.index_with(1)
|
||||||
|
PostSimilarity.find_or_initialize_by(post:, target_post:).tap { |ps|
|
||||||
|
ps.cos = cos.(existence_of_tags, existence_of_target_tags)
|
||||||
|
}.save!
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,6 +1,28 @@
|
|||||||
namespace :tag_similarity do
|
namespace :tag_similarity do
|
||||||
desc '関聯タグ・テーブル作成'
|
desc '関聯タグ・テーブル作成'
|
||||||
task calc: :environment do
|
task calc: :environment do
|
||||||
Similarity::Calc.call(Tag, :posts)
|
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
|
||||||
|
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
|
||||||
|
cos = -> a, b do
|
||||||
|
na = norm.(a)
|
||||||
|
nb = norm.(b)
|
||||||
|
if na.zero? || nb.zero?
|
||||||
|
0.0
|
||||||
|
else
|
||||||
|
dot.(a, b) / na / nb
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
tags = Tag.includes(:posts).to_a
|
||||||
|
tags.each_with_index do |tag, i|
|
||||||
|
existence_of_posts = tag.posts.index_with(1)
|
||||||
|
((i + 1)...tags.size).each do |j|
|
||||||
|
target_tag = tags[j]
|
||||||
|
existence_of_target_posts = target_tag.posts.index_with(1)
|
||||||
|
TagSimilarity.find_or_initialize_by(tag:, target_tag:).tap { |ts|
|
||||||
|
ts.cos = cos.(existence_of_posts, existence_of_target_posts)
|
||||||
|
}.save!
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
namespace :nico do
|
namespace :nico do
|
||||||
desc 'ニコニコ DB 同期'
|
desc 'ニコニコ DB 同期'
|
||||||
task sync: :environment do
|
task sync: :environment do
|
||||||
require 'json'
|
|
||||||
require 'nokogiri'
|
|
||||||
require 'open-uri'
|
|
||||||
require 'open3'
|
require 'open3'
|
||||||
|
require 'open-uri'
|
||||||
|
require 'nokogiri'
|
||||||
require 'set'
|
require 'set'
|
||||||
require 'time'
|
|
||||||
|
|
||||||
fetch_thumbnail = -> url do
|
fetch_thumbnail = -> url do
|
||||||
html = URI.open(url, read_timeout: 60, 'User-Agent' => 'Mozilla/5.0').read
|
html = URI.open(url, read_timeout: 60, 'User-Agent' => 'Mozilla/5.0').read
|
||||||
@@ -15,12 +13,12 @@ namespace :nico do
|
|||||||
doc.at('meta[name="thumbnail"]')&.[]('content').presence
|
doc.at('meta[name="thumbnail"]')&.[]('content').presence
|
||||||
end
|
end
|
||||||
|
|
||||||
def sync_post_tags! post, desired_tag_ids, current_tag_ids: nil
|
def sync_post_tags! post, desired_tag_ids, current_ids: nil
|
||||||
current_tag_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
current_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||||
desired_tag_ids = desired_tag_ids.compact.to_set
|
desired_ids = desired_tag_ids.compact.to_set
|
||||||
|
|
||||||
to_add = desired_tag_ids - current_tag_ids
|
to_add = desired_ids - current_ids
|
||||||
to_remove = current_tag_ids - desired_tag_ids
|
to_remove = current_ids - desired_ids
|
||||||
|
|
||||||
Tag.where(id: to_add.to_a).find_each do |tag|
|
Tag.where(id: to_add.to_a).find_each do |tag|
|
||||||
begin
|
begin
|
||||||
@@ -42,49 +40,18 @@ namespace :nico do
|
|||||||
{ 'MYSQL_USER' => mysql_user, 'MYSQL_PASS' => mysql_pass },
|
{ 'MYSQL_USER' => mysql_user, 'MYSQL_PASS' => mysql_pass },
|
||||||
'python3', "#{ nizika_nico_path }/get_videos.py")
|
'python3', "#{ nizika_nico_path }/get_videos.py")
|
||||||
|
|
||||||
unless status.success?
|
abort unless status.success?
|
||||||
warn stderr
|
|
||||||
abort
|
|
||||||
end
|
|
||||||
|
|
||||||
data = JSON.parse(stdout)
|
data = JSON.parse(stdout)
|
||||||
data.each do |datum|
|
data.each do |datum|
|
||||||
code = datum['code']
|
code = datum['code']
|
||||||
post =
|
post = Post.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
||||||
Post
|
|
||||||
.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
|
||||||
.first
|
.first
|
||||||
|
unless post
|
||||||
title = datum['title']
|
title = datum['title']
|
||||||
original_created_at = datum['uploaded_at'] &&
|
|
||||||
Time.strptime(datum['uploaded_at'], '%Y-%m-%d %H:%M:%S')
|
|
||||||
original_created_from = original_created_at&.change(sec: 0)
|
|
||||||
original_created_before = original_created_from&.+(1.minute)
|
|
||||||
|
|
||||||
if post
|
|
||||||
attrs = { title:, original_created_from:, original_created_before: }
|
|
||||||
|
|
||||||
unless post.thumbnail.attached?
|
|
||||||
thumbnail_base = fetch_thumbnail.(post.url) rescue nil
|
|
||||||
if thumbnail_base.present?
|
|
||||||
post.thumbnail.attach(
|
|
||||||
io: URI.open(thumbnail_base),
|
|
||||||
filename: File.basename(URI.parse(thumbnail_base).path),
|
|
||||||
content_type: 'image/jpeg')
|
|
||||||
attrs[:thumbnail_base] = thumbnail_base
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
post.assign_attributes(attrs)
|
|
||||||
if post.changed?
|
|
||||||
post.save!
|
|
||||||
post.resized_thumbnail! if post.thumbnail.attached?
|
|
||||||
end
|
|
||||||
else
|
|
||||||
url = "https://www.nicovideo.jp/watch/#{ code }"
|
url = "https://www.nicovideo.jp/watch/#{ code }"
|
||||||
thumbnail_base = fetch_thumbnail.(url) rescue nil
|
thumbnail_base = fetch_thumbnail.(url) rescue nil
|
||||||
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil,
|
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil)
|
||||||
original_created_from:, original_created_before:)
|
|
||||||
if thumbnail_base.present?
|
if thumbnail_base.present?
|
||||||
post.thumbnail.attach(
|
post.thumbnail.attach(
|
||||||
io: URI.open(thumbnail_base),
|
io: URI.open(thumbnail_base),
|
||||||
@@ -93,53 +60,35 @@ namespace :nico do
|
|||||||
end
|
end
|
||||||
post.save!
|
post.save!
|
||||||
post.resized_thumbnail!
|
post.resized_thumbnail!
|
||||||
sync_post_tags!(post, [Tag.tagme.id, Tag.bot.id, Tag.niconico.id, Tag.video.id])
|
sync_post_tags!(post, [Tag.tagme.id])
|
||||||
end
|
end
|
||||||
|
|
||||||
tags = post.tags
|
kept_ids = PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||||
# 既存のタグ Id. 集合
|
kept_non_nico_ids = post.tags.where.not(category: 'nico').pluck(:id).to_set
|
||||||
kept_tag_ids = tags.pluck(:id).to_set
|
|
||||||
# うち内部タグ Id. 集合
|
|
||||||
kept_non_nico_tag_ids = tags.not_nico.pluck(:id).to_set
|
|
||||||
|
|
||||||
# 記載すべき外部タグ Id. および連携される内部タグ Id. のリスト
|
|
||||||
desired_nico_tag_based_ids = []
|
|
||||||
# 記載すべき内部タグ Id. のリスト
|
|
||||||
desired_non_nico_tag_ids = []
|
|
||||||
|
|
||||||
|
desired_nico_ids = []
|
||||||
|
desired_non_nico_ids = []
|
||||||
datum['tags'].each do |raw|
|
datum['tags'].each do |raw|
|
||||||
name = TagNameSanitisationRule.sanitise("nico:#{ raw }")
|
name = "nico:#{ raw }"
|
||||||
tag = Tag.find_or_create_by_tag_name!(name, category: :nico)
|
tag = Tag.find_or_create_by_tag_name!(name, category: 'nico')
|
||||||
desired_nico_tag_based_ids << tag.id
|
desired_nico_ids << tag.id
|
||||||
|
unless tag.id.in?(kept_ids)
|
||||||
# 新たに記載される外部タグと連携される内部タグを記載
|
|
||||||
unless tag.id.in?(kept_tag_ids)
|
|
||||||
linked_ids = tag.linked_tags.pluck(:id)
|
linked_ids = tag.linked_tags.pluck(:id)
|
||||||
desired_non_nico_tag_ids.concat(linked_ids)
|
desired_non_nico_ids.concat(linked_ids)
|
||||||
desired_nico_tag_based_ids.concat(linked_ids)
|
desired_nico_ids.concat(linked_ids)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
desired_nico_ids.uniq!
|
||||||
|
|
||||||
deerjikist = Deerjikist.find_by(platform: :nico, code: datum['user'])
|
desired_all_ids = kept_non_nico_ids.to_a + desired_nico_ids
|
||||||
if deerjikist
|
desired_non_nico_ids.concat(kept_non_nico_ids.to_a)
|
||||||
desired_non_nico_tag_ids << deerjikist.tag_id
|
desired_non_nico_ids.uniq!
|
||||||
desired_nico_tag_based_ids << deerjikist.tag_id
|
if kept_non_nico_ids.to_set != desired_non_nico_ids.to_set
|
||||||
elsif !(Tag.where(id: kept_non_nico_tag_ids).where(category: :deerjikist).exists?)
|
desired_all_ids << Tag.bot.id
|
||||||
desired_non_nico_tag_ids << Tag.no_deerjikist.id
|
|
||||||
desired_nico_tag_based_ids << Tag.no_deerjikist.id
|
|
||||||
end
|
end
|
||||||
|
desired_all_ids.uniq!
|
||||||
|
|
||||||
desired_nico_tag_based_ids.uniq!
|
sync_post_tags!(post, desired_all_ids, current_ids: kept_ids)
|
||||||
|
|
||||||
desired_all_tag_ids = kept_non_nico_tag_ids.to_a + desired_nico_tag_based_ids
|
|
||||||
desired_non_nico_tag_ids.concat(kept_non_nico_tag_ids.to_a)
|
|
||||||
desired_non_nico_tag_ids.uniq!
|
|
||||||
if kept_non_nico_tag_ids != desired_non_nico_tag_ids.to_set
|
|
||||||
desired_all_tag_ids << Tag.bot.id
|
|
||||||
end
|
|
||||||
desired_all_tag_ids.uniq!
|
|
||||||
|
|
||||||
sync_post_tags!(post, desired_all_tag_ids, current_tag_ids: kept_tag_ids)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,22 +1,12 @@
|
|||||||
FactoryBot.define do
|
FactoryBot.define do
|
||||||
factory :tag do
|
factory :tag do
|
||||||
transient do
|
category { 'general' }
|
||||||
name { nil }
|
|
||||||
end
|
|
||||||
|
|
||||||
category { :general }
|
|
||||||
post_count { 0 }
|
post_count { 0 }
|
||||||
association :tag_name
|
association :tag_name
|
||||||
|
|
||||||
after(:build) do |tag, evaluator|
|
|
||||||
tag.name = evaluator.name if evaluator.name.present?
|
|
||||||
end
|
|
||||||
|
|
||||||
trait :nico do
|
trait :nico do
|
||||||
category { :nico }
|
category { 'nico' }
|
||||||
transient do
|
tag_name { association(:tag_name, name: "nico:#{ SecureRandom.hex(4) }") }
|
||||||
name { "nico:#{ SecureRandom.hex(4) }" }
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
FactoryBot.define do
|
|
||||||
factory :theatre_comment do
|
|
||||||
association :theatre
|
|
||||||
association :user
|
|
||||||
sequence (:no) { |n| n }
|
|
||||||
content { 'test comment' }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
FactoryBot.define do
|
|
||||||
factory :theatre do
|
|
||||||
name { 'Test Theatre' }
|
|
||||||
kind { 1 }
|
|
||||||
opens_at { Time.current }
|
|
||||||
closes_at { 1.day.from_now }
|
|
||||||
next_comment_no { 1 }
|
|
||||||
|
|
||||||
association :created_by_user, factory: :user
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -7,9 +7,5 @@ FactoryBot.define do
|
|||||||
trait :member do
|
trait :member do
|
||||||
role { "member" }
|
role { "member" }
|
||||||
end
|
end
|
||||||
|
|
||||||
trait :admin do
|
|
||||||
role { 'admin' }
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
RSpec.describe TagNameSanitisationRule, type: :model do
|
|
||||||
describe '.sanitise' do
|
|
||||||
before do
|
|
||||||
described_class.create!(priority: 10, source_pattern: '_', replacement: '')
|
|
||||||
described_class.create!(priority: 20, source_pattern: 'ABC', replacement: 'abc')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'applies sanitisation rules sequentially in priority order' do
|
|
||||||
expect(described_class.sanitise('A_B_C')).to eq('abc')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'does not fail when a rule does not match' do
|
|
||||||
expect { described_class.sanitise('xyz') }.not_to raise_error
|
|
||||||
expect(described_class.sanitise('xyz')).to eq('xyz')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'validations' do
|
|
||||||
it 'is invalid when source_pattern is not a valid regexp' do
|
|
||||||
rule = described_class.new(priority: 10, source_pattern: '[', replacement: '')
|
|
||||||
expect(rule).to be_invalid
|
|
||||||
expect(rule.errors[:source_pattern]).to be_present
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe '.apply!' do
|
|
||||||
before do
|
|
||||||
described_class.create!(priority: 10, source_pattern: '_', replacement: '')
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when no conflicting tag_name exists' do
|
|
||||||
let!(:tag_name) do
|
|
||||||
TagName.create!(name: 'tmp').tap do |tn|
|
|
||||||
tn.update_columns(name: 'foo_bar', updated_at: Time.current)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'renames the tag_name' do
|
|
||||||
described_class.apply!
|
|
||||||
expect(tag_name.reload.name).to eq('foobar')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when a conflicting canonical tag_name exists' do
|
|
||||||
let!(:existing) { TagName.create!(name: 'foobar') }
|
|
||||||
let!(:source) do
|
|
||||||
TagName.create!(name: 'tmp').tap do |tn|
|
|
||||||
tn.update_columns(name: 'foo_bar', updated_at: Time.current)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'deletes the source tag_name' do
|
|
||||||
described_class.apply!
|
|
||||||
expect(TagName.exists?(source.id)).to be(false)
|
|
||||||
expect(existing.reload.name).to eq('foobar')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when the source tag_name has a tag and the existing one has no tag' do
|
|
||||||
let!(:existing) { TagName.create!(name: 'foobar') }
|
|
||||||
let!(:source_tag) { create(:tag, name: 'tmp', category: :general) }
|
|
||||||
let!(:source_tag_name_id) { source_tag.tag_name_id }
|
|
||||||
|
|
||||||
before do
|
|
||||||
source_tag.tag_name.update_columns(name: 'foo_bar', updated_at: Time.current)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'moves the tag to the existing tag_name' do
|
|
||||||
described_class.apply!
|
|
||||||
expected_tag_name_id = existing.canonical_id || existing.id
|
|
||||||
expect(source_tag.reload.tag_name_id).to eq(expected_tag_name_id)
|
|
||||||
expect(TagName.exists?(source_tag_name_id)).to be(false)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when both source and existing tag_names have tags' do
|
|
||||||
let!(:existing_tn) { TagName.create!(name: 'foobar') }
|
|
||||||
let!(:existing_tag) { Tag.create!(tag_name: existing_tn, category: :general) }
|
|
||||||
|
|
||||||
let!(:source_tn) { TagName.create!(name: 'tmp') }
|
|
||||||
let!(:source_tag) { Tag.create!(tag_name: source_tn, category: :general) }
|
|
||||||
let!(:source_tag_name_id) { source_tn.id }
|
|
||||||
|
|
||||||
before do
|
|
||||||
source_tn.update_columns(name: 'foo_bar', updated_at: Time.current)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'merges the source tag into the existing tag and deletes the source tag_name' do
|
|
||||||
expect(TagName.find_by(name: 'foobar')&.tag&.id).to eq(existing_tag.id)
|
|
||||||
expect(TagName.find_by(name: 'foo_bar')&.tag&.id).to eq(source_tag.id)
|
|
||||||
|
|
||||||
described_class.apply!
|
|
||||||
|
|
||||||
expect(Tag.exists?(source_tag.id)).to be(false)
|
|
||||||
expect(TagName.exists?(source_tag.tag_name_id)).to be(false)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
RSpec.describe Tag, type: :model do
|
|
||||||
describe '.merge_tags!' do
|
|
||||||
let!(:target_tag) { create(:tag, category: :general) }
|
|
||||||
let!(:source_tag) { create(:tag, category: :general) }
|
|
||||||
let!(:source_tag_name) { source_tag.tag_name }
|
|
||||||
|
|
||||||
let!(:post_record) do
|
|
||||||
Post.create!(url: 'https://example.com/posts/1', title: 'test post')
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when merging a simple source tag' do
|
|
||||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
|
||||||
|
|
||||||
it 'discards the source post_tag, creates an active target post_tag, discards the source tag, and aliases the source tag_name' do
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag])
|
|
||||||
|
|
||||||
source_pt = PostTag.with_discarded.find(source_post_tag.id)
|
|
||||||
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
|
|
||||||
|
|
||||||
expect(source_pt.discarded_at).to be_present
|
|
||||||
expect(source_pt.tag_id).to eq(source_tag.id)
|
|
||||||
expect(active_target).to be_present
|
|
||||||
|
|
||||||
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
|
|
||||||
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
|
|
||||||
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
|
|
||||||
expect(target_tag.reload.post_count).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when the target already has the same post_tag' do
|
|
||||||
let!(:target_post_tag) { PostTag.create!(post: post_record, tag: target_tag) }
|
|
||||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
|
||||||
|
|
||||||
it 'discards the source post_tag, keeps one active target post_tag, discards the source tag, and aliases the source tag_name' do
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag])
|
|
||||||
|
|
||||||
source_pt = PostTag.with_discarded.find(source_post_tag.id)
|
|
||||||
active = PostTag.kept.where(post_id: post_record.id, tag_id: target_tag.id)
|
|
||||||
|
|
||||||
expect(source_pt.discarded_at).to be_present
|
|
||||||
expect(source_pt.tag_id).to eq(source_tag.id)
|
|
||||||
expect(active.count).to eq(1)
|
|
||||||
expect(active.first.id).to eq(target_post_tag.id)
|
|
||||||
|
|
||||||
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
|
|
||||||
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
|
|
||||||
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
|
|
||||||
expect(target_tag.reload.post_count).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when source_tags includes the target itself' do
|
|
||||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
|
||||||
|
|
||||||
it 'ignores the target in source_tags while still merging the source tag' do
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag, target_tag])
|
|
||||||
|
|
||||||
source_pt = PostTag.with_discarded.find(source_post_tag.id)
|
|
||||||
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
|
|
||||||
|
|
||||||
expect(Tag.find(target_tag.id)).to be_present
|
|
||||||
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
|
|
||||||
expect(source_pt.discarded_at).to be_present
|
|
||||||
expect(source_pt.tag_id).to eq(source_tag.id)
|
|
||||||
expect(active_target).to be_present
|
|
||||||
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
|
|
||||||
expect(target_tag.reload.post_count).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when the source tag_name is invalid under sanitisation rules' do
|
|
||||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
|
||||||
let!(:sanitisation_rule) do
|
|
||||||
TagNameSanitisationRule.create!(
|
|
||||||
priority: 99_999,
|
|
||||||
source_pattern: 'INVALIDTOKEN',
|
|
||||||
replacement: ''
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
before do
|
|
||||||
source_tag_name.update_columns(
|
|
||||||
name: "#{ source_tag_name.name }INVALIDTOKEN",
|
|
||||||
updated_at: Time.current
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'still merges, but discards the source tag_name instead of aliasing it' do
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag])
|
|
||||||
|
|
||||||
source_pt = PostTag.with_discarded.find(source_post_tag.id)
|
|
||||||
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
|
|
||||||
discarded_source_tag_name = TagName.with_discarded.find(source_tag_name.id)
|
|
||||||
|
|
||||||
expect(source_pt.discarded_at).to be_present
|
|
||||||
expect(source_pt.tag_id).to eq(source_tag.id)
|
|
||||||
expect(active_target).to be_present
|
|
||||||
|
|
||||||
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
|
|
||||||
expect(target_tag.reload.post_count).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when the source tag_name has a wiki_page' do
|
|
||||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
|
||||||
let!(:wiki_page) do
|
|
||||||
WikiPage.create!(
|
|
||||||
tag_name: source_tag_name,
|
|
||||||
created_user: create_admin_user!,
|
|
||||||
updated_user: create_admin_user!
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'rolls back the transaction' do
|
|
||||||
expect {
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag])
|
|
||||||
}.to raise_error(ActiveRecord::RecordInvalid)
|
|
||||||
|
|
||||||
expect(Tag.with_discarded.find(source_tag.id)).not_to be_discarded
|
|
||||||
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
|
|
||||||
expect(PostTag.kept.find(source_post_tag.id).tag_id).to eq(source_tag.id)
|
|
||||||
expect(PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)).to be_nil
|
|
||||||
expect(source_tag_name.reload.canonical_id).to be_nil
|
|
||||||
expect(target_tag.reload.post_count).to eq(0)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when merging a nico source tag' do
|
|
||||||
let!(:target_tag) { create(:tag, category: :nico, name: 'nico:foo') }
|
|
||||||
let!(:source_tag) { create(:tag, category: :nico, name: 'nico:bar') }
|
|
||||||
let!(:source_tag_name_id) { source_tag.tag_name_id }
|
|
||||||
|
|
||||||
it 'discards the source tag_name instead of aliasing it' do
|
|
||||||
described_class.merge_tags!(target_tag, [source_tag])
|
|
||||||
|
|
||||||
discarded_source_tag = Tag.with_discarded.find(source_tag.id)
|
|
||||||
discarded_source_tag_name = TagName.with_discarded.find(source_tag_name_id)
|
|
||||||
|
|
||||||
expect(discarded_source_tag).to be_discarded
|
|
||||||
expect(discarded_source_tag_name).to be_discarded
|
|
||||||
expect(discarded_source_tag_name.canonical_id).to be_nil
|
|
||||||
expect(target_tag.reload.post_count).to eq(0)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
RSpec.describe 'Deerjikists API', type: :request do
|
|
||||||
let(:platform) { 'nico' }
|
|
||||||
let(:code) { 'deerjika-bot' }
|
|
||||||
|
|
||||||
let!(:tag1) { create(:tag, category: :deerjikist) }
|
|
||||||
let!(:tag2) { create(:tag, category: :deerjikist) }
|
|
||||||
|
|
||||||
let(:member) { create(:user, :member) }
|
|
||||||
let(:guest) { create(:user, role: :guest) }
|
|
||||||
|
|
||||||
describe 'GET /deerjikists/:platform/:code' do
|
|
||||||
subject(:do_request) do
|
|
||||||
get "/deerjikists/#{ platform }/#{ code }"
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when deerjikist exists' do
|
|
||||||
before do
|
|
||||||
Deerjikist.create!(platform:, code:, tag: tag1)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns 200 and deerjikist json' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json).to be_a(Hash)
|
|
||||||
expect(json['platform']).to eq(platform)
|
|
||||||
expect(json['code']).to eq(code)
|
|
||||||
|
|
||||||
expect(json['tag']).to be_a(Hash)
|
|
||||||
expect(json['tag']['id']).to eq(tag1.id)
|
|
||||||
expect(json['tag']['name']).to eq(tag1.name)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when deerjikist does not exist' do
|
|
||||||
it 'returns 404' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:not_found)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when platform or code become blank after strip' do
|
|
||||||
it 'returns 400' do
|
|
||||||
get '/deerjikists/%20/%20'
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'PUT /deerjikists/:platform/:code' do
|
|
||||||
subject(:do_request) do
|
|
||||||
put "/deerjikists/#{ platform }/#{ code }", params: payload
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:payload) { { tag_id: tag1.id } }
|
|
||||||
|
|
||||||
context 'when not legged in' do
|
|
||||||
it 'returns 401' do
|
|
||||||
sign_out
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when logged in but not member' do
|
|
||||||
it 'returns 403' do
|
|
||||||
sign_in_as guest
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when member' do
|
|
||||||
before do
|
|
||||||
sign_in_as member
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when params invalid' do
|
|
||||||
it 'returns 400 when tag_id is missing or invalid' do
|
|
||||||
put "/deerjikists/#{ platform }/#{ code }", params: { tag_id: 0 }
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns 400 when platform or code blank after strip' do
|
|
||||||
put '/deerjikists/%20/%20', params: { tag_id: tag1.id }
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when creating new deerjikist' do
|
|
||||||
it 'creates and returns 200 with json' do
|
|
||||||
expect { do_request }.to change { Deerjikist.count }.by(1)
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
d = Deerjikist.find_by(platform:, code:)
|
|
||||||
expect(d).to be_present
|
|
||||||
expect(d.tag_id).to eq(tag1.id)
|
|
||||||
|
|
||||||
expect(json['platform']).to eq(platform)
|
|
||||||
expect(json['code']).to eq(code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when updating existing deerjikist' do
|
|
||||||
before do
|
|
||||||
Deerjikist.create!(platform:, code:, tag: tag1)
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:payload) { { tag_id: tag2.id } }
|
|
||||||
|
|
||||||
it 'updates tag_id and returns 200' do
|
|
||||||
expect { do_request }.not_to change { Deerjikist.count }
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
d = Deerjikist.find_by(platform:, code:)
|
|
||||||
expect(d.tag_id).to eq(tag2.id)
|
|
||||||
|
|
||||||
expect(json['platform']).to eq(platform)
|
|
||||||
expect(json['code']).to eq(code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'DELETE /deerjikists/:platform/:code' do
|
|
||||||
subject(:do_request) do
|
|
||||||
delete "/deerjikists/#{ platform }/#{ code }"
|
|
||||||
end
|
|
||||||
|
|
||||||
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 logged in but not member' do
|
|
||||||
it 'returns 403' do
|
|
||||||
sign_in_as guest
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when member' do
|
|
||||||
before do
|
|
||||||
sign_in_as member
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns 400 when platform/code blank after strip' do
|
|
||||||
delete '/deerjikists/%20/%20'
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when deerjikist exists' do
|
|
||||||
before do
|
|
||||||
Deerjikist.create!(platform: platform, code: code, tag: tag1)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'destroys and returns 204' do
|
|
||||||
expect {
|
|
||||||
do_request
|
|
||||||
}.to change { Deerjikist.exists?(platform: platform, code: code) }
|
|
||||||
.from(true).to(false)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:no_content)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when deerjikist does not exist' do
|
|
||||||
it 'returns 404' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:not_found)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
include ActiveSupport::Testing::TimeHelpers
|
|
||||||
|
|
||||||
require 'rails_helper'
|
require 'rails_helper'
|
||||||
require 'set'
|
require 'set'
|
||||||
|
|
||||||
|
|
||||||
RSpec.describe 'Posts API', type: :request do
|
RSpec.describe 'Posts API', type: :request do
|
||||||
# create / update で thumbnail.attach は走るが、
|
# create / update で thumbnail.attach は走るが、
|
||||||
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
||||||
@@ -16,7 +15,7 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
end
|
end
|
||||||
|
|
||||||
let!(:tag_name) { TagName.create!(name: 'spec_tag') }
|
let!(:tag_name) { TagName.create!(name: 'spec_tag') }
|
||||||
let!(:tag) { Tag.create!(tag_name: tag_name, category: :general) }
|
let!(:tag) { Tag.create!(tag_name: tag_name, category: 'general') }
|
||||||
|
|
||||||
let!(:post_record) do
|
let!(:post_record) do
|
||||||
Post.create!(title: 'spec post', url: 'https://example.com/spec').tap do |p|
|
Post.create!(title: 'spec post', url: 'https://example.com/spec').tap do |p|
|
||||||
@@ -28,21 +27,20 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
let!(:user) { create_member_user! }
|
let!(:user) { create_member_user! }
|
||||||
|
|
||||||
let!(:tag_name) { TagName.create!(name: "spec_tag") }
|
let!(:tag_name) { TagName.create!(name: "spec_tag") }
|
||||||
let!(:tag) { Tag.create!(tag_name:, category: :general) }
|
let!(:tag) { Tag.create!(tag_name:, category: "general") }
|
||||||
let!(:tag_name2) { TagName.create!(name: 'unko') }
|
let!(:tag_name2) { TagName.create!(name: 'unko') }
|
||||||
let!(:tag2) { Tag.create!(tag_name: tag_name2, category: :deerjikist) }
|
let!(:tag2) { Tag.create!(tag_name: tag_name2, category: 'deerjikist') }
|
||||||
let!(:alias_tag_name) { TagName.create!(name: 'manko', canonical: tag_name) }
|
|
||||||
|
|
||||||
let!(:hit_post) do
|
let!(:hit_post) do
|
||||||
Post.create!(uploaded_user: user, title: "hello spec world",
|
Post.create!(uploaded_user: user, title: "hello spec world",
|
||||||
url: 'https://example.com/spec2').tap do |p|
|
url: 'https://example.com/spec').tap do |p|
|
||||||
PostTag.create!(post: p, tag:)
|
PostTag.create!(post: p, tag:)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
let!(:miss_post) do
|
let!(:miss_post) do
|
||||||
Post.create!(uploaded_user: user, title: "unrelated title",
|
Post.create!(uploaded_user: user, title: "unrelated title",
|
||||||
url: 'https://example.com/spec3').tap do |p|
|
url: 'https://example.com/spec2').tap do |p|
|
||||||
PostTag.create!(post: p, tag: tag2)
|
PostTag.create!(post: p, tag: tag2)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -56,9 +54,9 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
# 全postの全tagが name を含むこと
|
# 全postの全tagが name を含むこと
|
||||||
expect(posts).not_to be_empty
|
expect(posts).not_to be_empty
|
||||||
posts.each do |p|
|
posts.each do |p|
|
||||||
expect(p['tags']).to be_an(Array)
|
expect(p["tags"]).to be_an(Array)
|
||||||
p['tags'].each do |t|
|
p["tags"].each do |t|
|
||||||
expect(t).to include('name', 'category', 'has_wiki')
|
expect(t).to include("name", "category")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
expect(json['count']).to be_an(Integer)
|
expect(json['count']).to be_an(Integer)
|
||||||
@@ -73,38 +71,11 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
get "/posts", params: { tags: "spec_tag" }
|
get "/posts", params: { tags: "spec_tag" }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
posts = json.fetch('posts')
|
ids = json.fetch("posts").map { |p| p["id"] }
|
||||||
ids = posts.map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(hit_post.id)
|
expect(ids).to include(hit_post.id)
|
||||||
expect(ids).not_to include(miss_post.id)
|
expect(ids).not_to include(miss_post.id)
|
||||||
expect(json['count']).to be_an(Integer)
|
expect(json['count']).to be_an(Integer)
|
||||||
|
|
||||||
posts.each do |p|
|
|
||||||
expect(p['tags']).to be_an(Array)
|
|
||||||
p['tags'].each do |t|
|
|
||||||
expect(t).to include('name', 'category', 'has_wiki')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it "filters posts by q (hit case by alias)" do
|
|
||||||
get "/posts", params: { tags: "manko" }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
posts = json.fetch('posts')
|
|
||||||
ids = posts.map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(hit_post.id)
|
|
||||||
expect(ids).not_to include(miss_post.id)
|
|
||||||
expect(json['count']).to be_an(Integer)
|
|
||||||
|
|
||||||
posts.each do |p|
|
|
||||||
expect(p['tags']).to be_an(Array)
|
|
||||||
p['tags'].each do |t|
|
|
||||||
expect(t).to include('name', 'category', 'has_wiki')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "returns empty posts when nothing matches" do
|
it "returns empty posts when nothing matches" do
|
||||||
@@ -115,321 +86,6 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(json.fetch('count')).to eq(0)
|
expect(json.fetch('count')).to eq(0)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
context 'when tags contain not:' do
|
|
||||||
let!(:foo_tag_name) { TagName.create!(name: 'not_spec_foo') }
|
|
||||||
let!(:foo_tag) { Tag.create!(tag_name: foo_tag_name, category: :general) }
|
|
||||||
|
|
||||||
let!(:bar_tag_name) { TagName.create!(name: 'not_spec_bar') }
|
|
||||||
let!(:bar_tag) { Tag.create!(tag_name: bar_tag_name, category: :general) }
|
|
||||||
|
|
||||||
let!(:baz_tag_name) { TagName.create!(name: 'not_spec_baz') }
|
|
||||||
let!(:baz_tag) { Tag.create!(tag_name: baz_tag_name, category: :general) }
|
|
||||||
|
|
||||||
let!(:foo_alias_tag_name) do
|
|
||||||
TagName.create!(name: 'not_spec_foo_alias', canonical: foo_tag_name)
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:foo_only_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'foo only',
|
|
||||||
url: 'https://example.com/not-spec-foo').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag: foo_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:bar_only_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'bar only',
|
|
||||||
url: 'https://example.com/not-spec-bar').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag: bar_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:baz_only_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'baz only',
|
|
||||||
url: 'https://example.com/not-spec-baz').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag: baz_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:foo_bar_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'foo bar',
|
|
||||||
url: 'https://example.com/not-spec-foo-bar').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag: foo_tag)
|
|
||||||
PostTag.create!(post: p, tag: bar_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:foo_baz_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'foo baz',
|
|
||||||
url: 'https://example.com/not-spec-foo-baz').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag: foo_tag)
|
|
||||||
PostTag.create!(post: p, tag: baz_tag)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:controlled_ids) do
|
|
||||||
[foo_only_post.id, bar_only_post.id, baz_only_post.id,
|
|
||||||
foo_bar_post.id, foo_baz_post.id]
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'supports not search' do
|
|
||||||
get '/posts', params: { tags: 'not:not_spec_foo' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[bar_only_post.id, baz_only_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'supports alias in not search' do
|
|
||||||
get '/posts', params: { tags: 'not:not_spec_foo_alias' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[bar_only_post.id, baz_only_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'treats multiple not terms as AND when match is omitted' do
|
|
||||||
get '/posts', params: { tags: 'not:not_spec_foo not:not_spec_bar' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[baz_only_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'treats multiple not terms as OR when match=any' do
|
|
||||||
get '/posts', params: { tags: 'not:not_spec_foo not:not_spec_bar', match: 'any' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[foo_only_post.id, bar_only_post.id, baz_only_post.id, foo_baz_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'supports mixed positive and negative search with AND' do
|
|
||||||
get '/posts', params: { tags: 'not_spec_foo not:not_spec_bar' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[foo_only_post.id, foo_baz_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'supports mixed positive and negative search with OR when match=any' do
|
|
||||||
get '/posts', params: { tags: 'not_spec_foo not:not_spec_bar', match: 'any' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json.fetch('posts').map { |p| p['id'] } & controlled_ids).to match_array(
|
|
||||||
[foo_only_post.id, baz_only_post.id, foo_bar_post.id, foo_baz_post.id]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when url is provided' do
|
|
||||||
let!(:url_hit_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'url hit',
|
|
||||||
url: 'https://example.com/needle-url-xyz').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:url_miss_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'url miss',
|
|
||||||
url: 'https://example.com/other-url').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by url substring' do
|
|
||||||
get '/posts', params: { url: 'needle-url-xyz' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(url_hit_post.id)
|
|
||||||
expect(ids).not_to include(url_miss_post.id)
|
|
||||||
expect(json.fetch('count')).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when title is provided' do
|
|
||||||
let!(:title_hit_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'needle-title-xyz',
|
|
||||||
url: 'https://example.com/title-hit').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:title_miss_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'other title',
|
|
||||||
url: 'https://example.com/title-miss').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by title substring' do
|
|
||||||
get '/posts', params: { title: 'needle-title-xyz' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(title_hit_post.id)
|
|
||||||
expect(ids).not_to include(title_miss_post.id)
|
|
||||||
expect(json.fetch('count')).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when created_from/created_to are provided' do
|
|
||||||
let(:t_created_hit) { Time.zone.local(2010, 1, 5, 12, 0, 0) }
|
|
||||||
let(:t_created_miss) { Time.zone.local(2012, 1, 5, 12, 0, 0) }
|
|
||||||
|
|
||||||
let!(:created_hit_post) do
|
|
||||||
travel_to(t_created_hit) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'created hit',
|
|
||||||
url: 'https://example.com/created-hit').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:created_miss_post) do
|
|
||||||
travel_to(t_created_miss) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'created miss',
|
|
||||||
url: 'https://example.com/created-miss').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by created_at range' do
|
|
||||||
get '/posts', params: {
|
|
||||||
created_from: Time.zone.local(2010, 1, 1, 0, 0, 0).iso8601,
|
|
||||||
created_to: Time.zone.local(2010, 12, 31, 23, 59, 59).iso8601
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(created_hit_post.id)
|
|
||||||
expect(ids).not_to include(created_miss_post.id)
|
|
||||||
expect(json.fetch('count')).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when updated_from/updated_to are provided' do
|
|
||||||
let(:t0) { Time.zone.local(2011, 2, 1, 12, 0, 0) }
|
|
||||||
let(:t1) { Time.zone.local(2011, 2, 10, 12, 0, 0) }
|
|
||||||
|
|
||||||
let!(:updated_hit_post) do
|
|
||||||
p = nil
|
|
||||||
travel_to(t0) do
|
|
||||||
p = Post.create!(uploaded_user: user, title: 'updated hit',
|
|
||||||
url: 'https://example.com/updated-hit').tap do |pp|
|
|
||||||
PostTag.create!(post: pp, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
travel_to(t1) do
|
|
||||||
p.update!(title: 'updated hit v2')
|
|
||||||
end
|
|
||||||
p
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:updated_miss_post) do
|
|
||||||
travel_to(Time.zone.local(2013, 1, 1, 12, 0, 0)) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'updated miss',
|
|
||||||
url: 'https://example.com/updated-miss').tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by updated_at range' do
|
|
||||||
get '/posts', params: {
|
|
||||||
updated_from: Time.zone.local(2011, 2, 5, 0, 0, 0).iso8601,
|
|
||||||
updated_to: Time.zone.local(2011, 2, 20, 23, 59, 59).iso8601
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(updated_hit_post.id)
|
|
||||||
expect(ids).not_to include(updated_miss_post.id)
|
|
||||||
expect(json.fetch('count')).to eq(1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when original_created_from/original_created_to are provided' do
|
|
||||||
# 注意: controller の現状ロジックに合わせてる
|
|
||||||
# original_created_from は `original_created_before > ?`
|
|
||||||
# original_created_to は `original_created_from <= ?`
|
|
||||||
|
|
||||||
let!(:oc_hit_post) do
|
|
||||||
Post.create!(uploaded_user: user, title: 'oc hit',
|
|
||||||
url: 'https://example.com/oc-hit',
|
|
||||||
original_created_from: Time.zone.local(2015, 1, 1, 0, 0, 0),
|
|
||||||
original_created_before: Time.zone.local(2015, 1, 10, 0, 0, 0)).tap do |p|
|
|
||||||
PostTag.create!(post: p, tag:)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# original_created_from の条件は「original_created_before > param」なので、
|
|
||||||
# before が param 以下になるようにする(ただし before >= from は守る)
|
|
||||||
let!(:oc_miss_post_for_from) do
|
|
||||||
Post.create!(
|
|
||||||
uploaded_user: user,
|
|
||||||
title: 'oc miss for from',
|
|
||||||
url: 'https://example.com/oc-miss-from',
|
|
||||||
original_created_from: Time.zone.local(2014, 12, 1, 0, 0, 0),
|
|
||||||
original_created_before: Time.zone.local(2015, 1, 1, 0, 0, 0)
|
|
||||||
).tap { |p| PostTag.create!(post: p, tag:) }
|
|
||||||
end
|
|
||||||
|
|
||||||
# original_created_to の条件は「original_created_from <= param」なので、
|
|
||||||
# from が param より後になるようにする(before >= from は守る)
|
|
||||||
let!(:oc_miss_post_for_to) do
|
|
||||||
Post.create!(
|
|
||||||
uploaded_user: user,
|
|
||||||
title: 'oc miss for to',
|
|
||||||
url: 'https://example.com/oc-miss-to',
|
|
||||||
original_created_from: Time.zone.local(2015, 2, 1, 0, 0, 0),
|
|
||||||
original_created_before: Time.zone.local(2015, 2, 10, 0, 0, 0)
|
|
||||||
).tap { |p| PostTag.create!(post: p, tag:) }
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by original_created_from (current controller behavior)' do
|
|
||||||
get '/posts', params: {
|
|
||||||
original_created_from: Time.zone.local(2015, 1, 5, 0, 0, 0).iso8601
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(oc_hit_post.id)
|
|
||||||
expect(ids).not_to include(oc_miss_post_for_from.id)
|
|
||||||
expect(json.fetch('count')).to eq(2)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters posts by original_created_to (current controller behavior)' do
|
|
||||||
get '/posts', params: {
|
|
||||||
original_created_to: Time.zone.local(2015, 1, 15, 0, 0, 0).iso8601
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
ids = json.fetch('posts').map { |p| p['id'] }
|
|
||||||
|
|
||||||
expect(ids).to include(oc_hit_post.id)
|
|
||||||
expect(ids).not_to include(oc_miss_post_for_to.id)
|
|
||||||
expect(json.fetch('count')).to eq(2)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'GET /posts/:id' do
|
describe 'GET /posts/:id' do
|
||||||
@@ -448,7 +104,7 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
|
|
||||||
# show は build_tag_tree_for を使うので、tags はツリー形式(children 付き)
|
# show は build_tag_tree_for を使うので、tags はツリー形式(children 付き)
|
||||||
node = json['tags'][0]
|
node = json['tags'][0]
|
||||||
expect(node).to include('id', 'name', 'category', 'post_count', 'children', 'has_wiki')
|
expect(node).to include('id', 'name', 'category', 'post_count', 'children')
|
||||||
expect(node['name']).to eq('spec_tag')
|
expect(node['name']).to eq('spec_tag')
|
||||||
|
|
||||||
expect(json).to have_key('related')
|
expect(json).to have_key('related')
|
||||||
@@ -471,7 +127,6 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
|
|
||||||
describe 'POST /posts' do
|
describe 'POST /posts' do
|
||||||
let(:member) { create(:user, :member) }
|
let(:member) { create(:user, :member) }
|
||||||
let!(:alias_tag_name) { TagName.create!(name: 'manko', canonical: tag_name) }
|
|
||||||
|
|
||||||
it '401 when not logged in' do
|
it '401 when not logged in' do
|
||||||
sign_out
|
sign_out
|
||||||
@@ -503,74 +158,6 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(json['tags']).to be_an(Array)
|
expect(json['tags']).to be_an(Array)
|
||||||
expect(json['tags'][0]).to have_key('name')
|
expect(json['tags'][0]).to have_key('name')
|
||||||
end
|
end
|
||||||
|
|
||||||
it '201 and creates post + tags when member and tags have aliases' do
|
|
||||||
sign_in_as(member)
|
|
||||||
|
|
||||||
post '/posts', params: {
|
|
||||||
title: 'new post',
|
|
||||||
url: 'https://example.com/new',
|
|
||||||
tags: 'manko', # 既存タグ名を投げる
|
|
||||||
thumbnail: dummy_upload
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:created)
|
|
||||||
expect(json).to include('id', 'title', 'url')
|
|
||||||
|
|
||||||
# tags が name を含むこと(API 側の serialization が正しいこと)
|
|
||||||
names = json.fetch('tags').map { |t| t['name'] }
|
|
||||||
expect(names).to include('spec_tag')
|
|
||||||
expect(names).not_to include('manko')
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when nico tag already exists in tags" do
|
|
||||||
before do
|
|
||||||
Tag.find_undiscard_or_create_by!(
|
|
||||||
tag_name: TagName.find_undiscard_or_create_by!(name: 'nico:nico_tag'),
|
|
||||||
category: :nico)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'return 400' do
|
|
||||||
sign_in_as(member)
|
|
||||||
|
|
||||||
post '/posts', params: {
|
|
||||||
title: 'new post',
|
|
||||||
url: 'https://example.com/nico_tag',
|
|
||||||
tags: 'nico:nico_tag',
|
|
||||||
thumbnail: dummy_upload }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when url is blank' do
|
|
||||||
it 'returns 422' do
|
|
||||||
sign_in_as(member)
|
|
||||||
|
|
||||||
post '/posts', params: {
|
|
||||||
title: 'new post',
|
|
||||||
url: ' ',
|
|
||||||
tags: 'spec_tag', # 既存タグ名を投げる
|
|
||||||
thumbnail: dummy_upload }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:unprocessable_entity)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when url is invalid' do
|
|
||||||
it 'returns 422' do
|
|
||||||
sign_in_as(member)
|
|
||||||
|
|
||||||
post '/posts', params: {
|
|
||||||
title: 'new post',
|
|
||||||
url: 'ぼざクリタグ広場',
|
|
||||||
tags: 'spec_tag', # 既存タグ名を投げる
|
|
||||||
thumbnail: dummy_upload
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:unprocessable_entity)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'PUT /posts/:id' do
|
describe 'PUT /posts/:id' do
|
||||||
@@ -593,7 +180,7 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
|
|
||||||
# 追加で別タグも作って、更新時に入れ替わることを見る
|
# 追加で別タグも作って、更新時に入れ替わることを見る
|
||||||
tn2 = TagName.create!(name: 'spec_tag_2')
|
tn2 = TagName.create!(name: 'spec_tag_2')
|
||||||
Tag.create!(tag_name: tn2, category: :general)
|
Tag.create!(tag_name: tn2, category: 'general')
|
||||||
|
|
||||||
put "/posts/#{post_record.id}", params: {
|
put "/posts/#{post_record.id}", params: {
|
||||||
title: 'updated title',
|
title: 'updated title',
|
||||||
@@ -608,24 +195,6 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
names = json['tags'].map { |n| n['name'] }
|
names = json['tags'].map { |n| n['name'] }
|
||||||
expect(names).to include('spec_tag_2')
|
expect(names).to include('spec_tag_2')
|
||||||
end
|
end
|
||||||
|
|
||||||
context "when nico tag already exists in tags" do
|
|
||||||
before do
|
|
||||||
Tag.find_undiscard_or_create_by!(
|
|
||||||
tag_name: TagName.find_undiscard_or_create_by!(name: 'nico:nico_tag'),
|
|
||||||
category: :nico)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'return 400' do
|
|
||||||
sign_in_as(member)
|
|
||||||
|
|
||||||
put "/posts/#{ post_record.id }", params: {
|
|
||||||
title: 'updated title',
|
|
||||||
tags: 'nico:nico_tag' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'GET /posts/random' do
|
describe 'GET /posts/random' do
|
||||||
@@ -650,7 +219,7 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
it 'returns add/remove events (history) for a post' do
|
it 'returns add/remove events (history) for a post' do
|
||||||
# add
|
# add
|
||||||
tn2 = TagName.create!(name: 'spec_tag2')
|
tn2 = TagName.create!(name: 'spec_tag2')
|
||||||
tag2 = Tag.create!(tag_name: tn2, category: :general)
|
tag2 = Tag.create!(tag_name: tn2, category: 'general')
|
||||||
pt = PostTag.create!(post: post_record, tag: tag2, created_user: member)
|
pt = PostTag.create!(post: post_record, tag: tag2, created_user: member)
|
||||||
|
|
||||||
# remove (discard)
|
# remove (discard)
|
||||||
@@ -667,93 +236,6 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(types).to include('add')
|
expect(types).to include('add')
|
||||||
expect(types).to include('remove')
|
expect(types).to include('remove')
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'filters history by tag' do
|
|
||||||
tn2 = TagName.create!(name: 'history_tag_hit')
|
|
||||||
tag2 = Tag.create!(tag_name: tn2, category: :general)
|
|
||||||
|
|
||||||
tn3 = TagName.create!(name: 'history_tag_miss')
|
|
||||||
tag3 = Tag.create!(tag_name: tn3, category: :general)
|
|
||||||
|
|
||||||
other_post = Post.create!(
|
|
||||||
title: 'other post',
|
|
||||||
url: 'https://example.com/history-other'
|
|
||||||
)
|
|
||||||
|
|
||||||
# hit: add
|
|
||||||
PostTag.create!(post: post_record, tag: tag2, created_user: member)
|
|
||||||
|
|
||||||
# hit: add + remove
|
|
||||||
pt2 = PostTag.create!(post: other_post, tag: tag2, created_user: member)
|
|
||||||
pt2.discard_by!(member)
|
|
||||||
|
|
||||||
# miss: add + remove
|
|
||||||
pt3 = PostTag.create!(post: post_record, tag: tag3, created_user: member)
|
|
||||||
pt3.discard_by!(member)
|
|
||||||
|
|
||||||
get '/posts/changes', params: { tag: tag2.id }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json).to include('changes', 'count')
|
|
||||||
expect(json['count']).to eq(3)
|
|
||||||
|
|
||||||
changes = json.fetch('changes')
|
|
||||||
|
|
||||||
expect(changes.map { |e| e.dig('tag', 'id') }.uniq).to eq([tag2.id])
|
|
||||||
expect(changes.map { |e| e['change_type'] }).to match_array(%w[add add remove])
|
|
||||||
expect(changes.map { |e| e.dig('post', 'id') }).to match_array([
|
|
||||||
post_record.id,
|
|
||||||
other_post.id,
|
|
||||||
other_post.id
|
|
||||||
])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters history by post and tag together' do
|
|
||||||
tn2 = TagName.create!(name: 'history_tag_combo_hit')
|
|
||||||
tag2 = Tag.create!(tag_name: tn2, category: :general)
|
|
||||||
|
|
||||||
tn3 = TagName.create!(name: 'history_tag_combo_miss')
|
|
||||||
tag3 = Tag.create!(tag_name: tn3, category: :general)
|
|
||||||
|
|
||||||
other_post = Post.create!(
|
|
||||||
title: 'other combo post',
|
|
||||||
url: 'https://example.com/history-combo-other'
|
|
||||||
)
|
|
||||||
|
|
||||||
# hit
|
|
||||||
PostTag.create!(post: post_record, tag: tag2, created_user: member)
|
|
||||||
|
|
||||||
# miss by post
|
|
||||||
pt2 = PostTag.create!(post: other_post, tag: tag2, created_user: member)
|
|
||||||
pt2.discard_by!(member)
|
|
||||||
|
|
||||||
# miss by tag
|
|
||||||
pt3 = PostTag.create!(post: post_record, tag: tag3, created_user: member)
|
|
||||||
pt3.discard_by!(member)
|
|
||||||
|
|
||||||
get '/posts/changes', params: { id: post_record.id, tag: tag2.id }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json).to include('changes', 'count')
|
|
||||||
expect(json['count']).to eq(1)
|
|
||||||
|
|
||||||
changes = json.fetch('changes')
|
|
||||||
expect(changes.size).to eq(1)
|
|
||||||
expect(changes[0]['change_type']).to eq('add')
|
|
||||||
expect(changes[0].dig('post', 'id')).to eq(post_record.id)
|
|
||||||
expect(changes[0].dig('tag', 'id')).to eq(tag2.id)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns empty history when tag does not match' do
|
|
||||||
tn2 = TagName.create!(name: 'history_tag_no_hit')
|
|
||||||
tag2 = Tag.create!(tag_name: tn2, category: :general)
|
|
||||||
|
|
||||||
get '/posts/changes', params: { tag: tag2.id }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json.fetch('changes')).to eq([])
|
|
||||||
expect(json.fetch('count')).to eq(0)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'POST /posts/:id/viewed' do
|
describe 'POST /posts/:id/viewed' do
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
require "rails_helper"
|
|
||||||
|
|
||||||
RSpec.describe "TagChildren", type: :request do
|
|
||||||
let!(:parent) { create(:tag) }
|
|
||||||
let!(:child) { create(:tag) }
|
|
||||||
|
|
||||||
# ここは君のUser factoryに合わせて調整
|
|
||||||
let(:user) { create_member_user! }
|
|
||||||
let(:admin) { create_admin_user! }
|
|
||||||
|
|
||||||
# current_user を ApplicationController でスタブ
|
|
||||||
def stub_current_user(user_or_nil)
|
|
||||||
allow_any_instance_of(ApplicationController)
|
|
||||||
.to receive(:current_user)
|
|
||||||
.and_return(user_or_nil)
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "POST /tag_children" do
|
|
||||||
subject(:do_request) do
|
|
||||||
post "/tags/#{ parent_id }/children/#{ child_id }"
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when not logged in" do
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 401" do
|
|
||||||
stub_current_user(nil)
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when logged in but not admin" do
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 403" do
|
|
||||||
stub_current_user(user)
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when admin and params are present" do
|
|
||||||
before { stub_current_user(admin) }
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 204 and adds child to parent.children" do
|
|
||||||
expect(parent.children).not_to include(child)
|
|
||||||
|
|
||||||
expect { do_request }
|
|
||||||
.to change { parent.reload.children.ids.include?(child.id) }
|
|
||||||
.from(false).to(true)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:no_content)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when Tag.find raises (invalid ids) it still returns 204" do
|
|
||||||
before { stub_current_user(admin) }
|
|
||||||
|
|
||||||
let(:parent_id) { -1 }
|
|
||||||
let(:child_id) { -1 }
|
|
||||||
|
|
||||||
it "returns 204 (rescue nil)" do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:no_content)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "DELETE /tag_children" do
|
|
||||||
subject(:do_request) do
|
|
||||||
delete "/tags/#{ parent_id }/children/#{ child_id }"
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when not logged in" do
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 401" do
|
|
||||||
stub_current_user(nil)
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when logged in but not admin" do
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 403" do
|
|
||||||
stub_current_user(user)
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when admin and params are present" do
|
|
||||||
before do
|
|
||||||
stub_current_user(admin)
|
|
||||||
parent.children << child
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:parent_id) { parent.id }
|
|
||||||
let(:child_id) { child.id }
|
|
||||||
|
|
||||||
it "returns 204 and removes child from parent.children" do
|
|
||||||
expect(parent.reload.children).to include(child)
|
|
||||||
|
|
||||||
expect { do_request }
|
|
||||||
.to change { parent.reload.children.ids.include?(child.id) }
|
|
||||||
.from(true).to(false)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:no_content)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context "when Tag.find raises (invalid ids) it still returns 204" do
|
|
||||||
before { stub_current_user(admin) }
|
|
||||||
|
|
||||||
let(:parent_id) { -1 }
|
|
||||||
let(:child_id) { -1 }
|
|
||||||
|
|
||||||
it "returns 204 (rescue nil)" do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:no_content)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
RSpec.describe 'Tags deerjikists API', type: :request do
|
|
||||||
let(:platform1) { 'nico' }
|
|
||||||
let(:code1) { 'deerjika-bot' }
|
|
||||||
let(:platform2) { 'youtube' }
|
|
||||||
let(:code2) { 'deerjika-bot.bsky.social' }
|
|
||||||
|
|
||||||
let!(:tag) { create(:tag, category: :deerjikist) }
|
|
||||||
|
|
||||||
before do
|
|
||||||
# show_by_name / deerjikists_by_name 用に名前を固定
|
|
||||||
tag.tag_name.update!(name: 'deerjika')
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'GET /tags/:id/deerjikists' do
|
|
||||||
subject(:do_request) do
|
|
||||||
get "/tags/#{ tag_id }/deerjikists"
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:tag_id) { tag.id }
|
|
||||||
|
|
||||||
context 'when tag exists and has no deerjikists' do
|
|
||||||
it 'returns 200 and empty array' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json).to eq([])
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when tag exists and has deerjikists' do
|
|
||||||
before do
|
|
||||||
Deerjikist.create!(platform: platform1, code: code1, tag: tag)
|
|
||||||
Deerjikist.create!(platform: platform2, code: code2, tag: tag)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns 200 and deerjikists array' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json).to be_a(Array)
|
|
||||||
expect(json.size).to eq(2)
|
|
||||||
|
|
||||||
expect(json.map { |h| [h['platform'], h['code']] }).to contain_exactly(
|
|
||||||
[platform1, code1],
|
|
||||||
[platform2, code2],
|
|
||||||
)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when tag does not exist' do
|
|
||||||
let(:tag_id) { 9_999_999 }
|
|
||||||
|
|
||||||
it 'returns 404' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:not_found)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'GET /tags/name/:name/deerjikists' do
|
|
||||||
subject(:do_request) do
|
|
||||||
get "/tags/name/#{ name }/deerjikists"
|
|
||||||
end
|
|
||||||
|
|
||||||
let(:name) { 'deerjika' }
|
|
||||||
|
|
||||||
context 'when name is blank after strip' do
|
|
||||||
let(:name) { '%20' }
|
|
||||||
|
|
||||||
it 'returns 400' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when tag does not exist for name' do
|
|
||||||
let(:name) { 'no-such-tag' }
|
|
||||||
|
|
||||||
it 'returns 404' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:not_found)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'when tag exists and has deerjikists' do
|
|
||||||
before do
|
|
||||||
Deerjikist.create!(platform: platform1, code: code1, tag: tag)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns 200 and deerjikists array' do
|
|
||||||
do_request
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json).to be_a(Array)
|
|
||||||
expect(json.size).to eq(1)
|
|
||||||
expect(json[0]['platform']).to eq(platform1)
|
|
||||||
expect(json[0]['code']).to eq(code1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -4,187 +4,18 @@ require 'rails_helper'
|
|||||||
|
|
||||||
RSpec.describe 'Tags API', type: :request do
|
RSpec.describe 'Tags API', type: :request do
|
||||||
let!(:tn) { TagName.create!(name: 'spec_tag') }
|
let!(:tn) { TagName.create!(name: 'spec_tag') }
|
||||||
let!(:tag) { Tag.create!(tag_name: tn, category: :general) }
|
let!(:tag) { Tag.create!(tag_name: tn, category: 'general') }
|
||||||
let!(:alias_tn) { TagName.create!(name: 'unko', canonical: tn) }
|
|
||||||
let!(:post) { Post.create!(url: 'https://example.com/unkounkounko') }
|
|
||||||
let!(:post_tag) { PostTag.create!(post:, tag:) }
|
|
||||||
let!(:tn2) { TagName.create!(name: 'unknown') }
|
|
||||||
let!(:tag2) { Tag.create!(tag_name: tn2, category: :general) }
|
|
||||||
|
|
||||||
def response_tags
|
|
||||||
json.fetch('tags')
|
|
||||||
end
|
|
||||||
|
|
||||||
def response_names
|
|
||||||
response_tags.map { |t| t.fetch('name') }
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'GET /tags' do
|
describe 'GET /tags' do
|
||||||
it 'returns tags with count and metadata' do
|
it 'returns tags with name' do
|
||||||
get '/tags'
|
get '/tags'
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json).to include('tags', 'count')
|
|
||||||
expect(response_tags).to be_an(Array)
|
|
||||||
expect(json['count']).to be_an(Integer)
|
|
||||||
expect(json['count']).to be >= response_tags.size
|
|
||||||
|
|
||||||
row = response_tags.find { |t| t['name'] == 'spec_tag' }
|
expect(json).to be_an(Array)
|
||||||
expect(row).to include(
|
expect(json).not_to be_empty
|
||||||
'id' => tag.id,
|
expect(json[0]).to have_key('name')
|
||||||
'name' => 'spec_tag',
|
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
||||||
'category' => 'general',
|
|
||||||
'post_count' => 1,
|
|
||||||
'has_wiki' => false)
|
|
||||||
expect(row).to have_key('created_at')
|
|
||||||
expect(row).to have_key('updated_at')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by post id' do
|
|
||||||
get '/tags', params: { post: post.id }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json['count']).to eq(1)
|
|
||||||
expect(response_names).to eq(['spec_tag'])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by partial name' do
|
|
||||||
get '/tags', params: { name: 'spec' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to include('spec_tag')
|
|
||||||
expect(response_names).not_to include('unknown')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by category' do
|
|
||||||
meme = Tag.create!(tag_name: TagName.create!(name: 'meme_only'), category: :meme)
|
|
||||||
|
|
||||||
get '/tags', params: { category: 'meme' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to eq(['meme_only'])
|
|
||||||
expect(response_tags.first['id']).to eq(meme.id)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by post_count range' do
|
|
||||||
low = Tag.create!(tag_name: TagName.create!(name: 'pc_low'), category: :general)
|
|
||||||
mid = Tag.create!(tag_name: TagName.create!(name: 'pc_mid'), category: :general)
|
|
||||||
high = Tag.create!(tag_name: TagName.create!(name: 'pc_high'), category: :general)
|
|
||||||
|
|
||||||
low.update_columns(post_count: 1)
|
|
||||||
mid.update_columns(post_count: 3)
|
|
||||||
high.update_columns(post_count: 5)
|
|
||||||
|
|
||||||
get '/tags', params: {
|
|
||||||
name: 'pc_',
|
|
||||||
post_count_gte: 2,
|
|
||||||
post_count_lte: 4,
|
|
||||||
order: 'post_count:asc',
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to eq(['pc_mid'])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by created_at range' do
|
|
||||||
old_tag = Tag.create!(tag_name: TagName.create!(name: 'created_old'), category: :general)
|
|
||||||
new_tag = Tag.create!(tag_name: TagName.create!(name: 'created_new'), category: :general)
|
|
||||||
|
|
||||||
old_time = Time.zone.local(2024, 1, 1, 0, 0, 0)
|
|
||||||
new_time = Time.zone.local(2024, 2, 1, 0, 0, 0)
|
|
||||||
|
|
||||||
old_tag.update_columns(created_at: old_time, updated_at: old_time)
|
|
||||||
new_tag.update_columns(created_at: new_time, updated_at: new_time)
|
|
||||||
|
|
||||||
get '/tags', params: {
|
|
||||||
name: 'created_',
|
|
||||||
created_from: Time.zone.local(2024, 1, 15, 0, 0, 0).iso8601,
|
|
||||||
order: 'created_at:asc',
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to eq(['created_new'])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'filters tags by updated_at range' do
|
|
||||||
old_tag = Tag.create!(tag_name: TagName.create!(name: 'updated_old'), category: :general)
|
|
||||||
new_tag = Tag.create!(tag_name: TagName.create!(name: 'updated_new'), category: :general)
|
|
||||||
|
|
||||||
old_time = Time.zone.local(2024, 3, 1, 0, 0, 0)
|
|
||||||
new_time = Time.zone.local(2024, 4, 1, 0, 0, 0)
|
|
||||||
|
|
||||||
old_tag.update_columns(created_at: old_time, updated_at: old_time)
|
|
||||||
new_tag.update_columns(created_at: new_time, updated_at: new_time)
|
|
||||||
|
|
||||||
get '/tags', params: {
|
|
||||||
name: 'updated_',
|
|
||||||
updated_to: Time.zone.local(2024, 3, 15, 0, 0, 0).iso8601,
|
|
||||||
order: 'updated_at:asc',
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to eq(['updated_old'])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'orders tags by custom category order' do
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_deerjikist'), category: :deerjikist)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_meme'), category: :meme)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_character'), category: :character)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_general'), category: :general)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_material'), category: :material)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'cat_meta'), category: :meta)
|
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'nico:cat_nico'), category: :nico)
|
|
||||||
|
|
||||||
get '/tags', params: { name: 'cat_', order: 'category:asc', limit: 20 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names).to eq(%w[
|
|
||||||
cat_deerjikist
|
|
||||||
cat_meme
|
|
||||||
cat_character
|
|
||||||
cat_general
|
|
||||||
cat_material
|
|
||||||
cat_meta
|
|
||||||
nico:cat_nico
|
|
||||||
])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'paginates and keeps total count' do
|
|
||||||
%w[pag_a pag_b pag_c].each do |name|
|
|
||||||
Tag.create!(tag_name: TagName.create!(name:), category: :general)
|
|
||||||
end
|
|
||||||
|
|
||||||
get '/tags', params: { name: 'pag_', order: 'name:asc', page: 2, limit: 2 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json['count']).to eq(3)
|
|
||||||
expect(response_names).to eq(%w[pag_c])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'falls back to default ordering when order is invalid' do
|
|
||||||
low = Tag.create!(tag_name: TagName.create!(name: 'fallback_low'), category: :general)
|
|
||||||
high = Tag.create!(tag_name: TagName.create!(name: 'fallback_high'), category: :general)
|
|
||||||
|
|
||||||
low.update_columns(post_count: 1)
|
|
||||||
high.update_columns(post_count: 9)
|
|
||||||
|
|
||||||
get '/tags', params: { name: 'fallback_', order: 'nope:sideways' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response_names.first).to eq('fallback_high')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'normalises invalid page and limit' do
|
|
||||||
%w[norm_a norm_b].each do |name|
|
|
||||||
Tag.create!(tag_name: TagName.create!(name:), category: :general)
|
|
||||||
end
|
|
||||||
|
|
||||||
get '/tags', params: { name: 'norm_', order: 'name:asc', page: 0, limit: 0 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(json['count']).to eq(2)
|
|
||||||
expect(response_tags.size).to eq(1)
|
|
||||||
expect(response_names).to eq(['norm_a'])
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -203,11 +34,7 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
expect(json).to include(
|
expect(json).to include(
|
||||||
'id' => tag.id,
|
'id' => tag.id,
|
||||||
'name' => 'spec_tag',
|
'name' => 'spec_tag',
|
||||||
'category' => 'general',
|
'category' => 'general')
|
||||||
'post_count' => 1,
|
|
||||||
'has_wiki' => false)
|
|
||||||
expect(json).to have_key('created_at')
|
|
||||||
expect(json).to have_key('updated_at')
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -229,21 +56,6 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
|
|
||||||
expect(json).to be_an(Array)
|
expect(json).to be_an(Array)
|
||||||
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
||||||
t = json.find { |x| x['name'] == 'spec_tag' }
|
|
||||||
expect(t).to have_key('matched_alias')
|
|
||||||
expect(t['matched_alias']).to be(nil)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'returns matching canonical tags by q with aliases' do
|
|
||||||
get '/tags/autocomplete', params: { q: 'unk' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(json).to be_an(Array)
|
|
||||||
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
|
||||||
t = json.find { |x| x['name'] == 'spec_tag' }
|
|
||||||
expect(t['matched_alias']).to eq('unko')
|
|
||||||
expect(json.map { |x| x['name'] }).not_to include('unknown')
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -253,14 +65,10 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
expect(json).to include(
|
expect(json).to have_key('id')
|
||||||
'id' => tag.id,
|
expect(json).to have_key('name')
|
||||||
'name' => 'spec_tag',
|
expect(json['id']).to eq(tag.id)
|
||||||
'category' => 'general',
|
expect(json['name']).to eq('spec_tag')
|
||||||
'post_count' => 1,
|
|
||||||
'has_wiki' => false)
|
|
||||||
expect(json).to have_key('created_at')
|
|
||||||
expect(json).to have_key('updated_at')
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'returns 404 when not found' do
|
it 'returns 404 when not found' do
|
||||||
@@ -268,95 +76,4 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
expect(response).to have_http_status(:not_found)
|
expect(response).to have_http_status(:not_found)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
let(:member_user) { create(:user) }
|
|
||||||
let(:non_member_user) { create(:user) }
|
|
||||||
|
|
||||||
def stub_current_user(user)
|
|
||||||
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
|
|
||||||
end
|
|
||||||
|
|
||||||
before do
|
|
||||||
allow(member_user).to receive(:gte_member?).and_return(true)
|
|
||||||
allow(non_member_user).to receive(:gte_member?).and_return(false)
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'PATCH /tags/:id' do
|
|
||||||
context '未ログイン' do
|
|
||||||
before { stub_current_user(nil) }
|
|
||||||
|
|
||||||
it '401 を返す' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: 'new' }
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'ログインしてゐるが member でない' do
|
|
||||||
before { stub_current_user(non_member_user) }
|
|
||||||
|
|
||||||
it '403 を返す' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: 'new' }
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
context 'member' do
|
|
||||||
before { stub_current_user(member_user) }
|
|
||||||
|
|
||||||
it 'name だけ更新できる' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: 'new' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
tag.reload
|
|
||||||
expect(tag.name).to eq('new')
|
|
||||||
expect(tag.category).to eq('general')
|
|
||||||
|
|
||||||
body = JSON.parse(response.body)
|
|
||||||
expect(body['id']).to eq(tag.id)
|
|
||||||
expect(body['name']).to eq('new')
|
|
||||||
expect(body['category']).to eq('general')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'category だけ更新できる' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { category: 'meme' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
tag.reload
|
|
||||||
expect(tag.name).to eq('spec_tag')
|
|
||||||
expect(tag.category).to eq('meme')
|
|
||||||
end
|
|
||||||
|
|
||||||
it '空文字は presence により無視され、更新は走らない(値が変わらない)' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: '', category: ' ' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
tag.reload
|
|
||||||
expect(tag.name).to eq('spec_tag')
|
|
||||||
expect(tag.category).to eq('general')
|
|
||||||
end
|
|
||||||
|
|
||||||
it '両方更新できる' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: 'n', category: 'meta' }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
tag.reload
|
|
||||||
expect(tag.name).to eq('n')
|
|
||||||
expect(tag.category).to eq('meta')
|
|
||||||
end
|
|
||||||
|
|
||||||
it '存在しない id だと RecordNotFound になる(通常は 404)' do
|
|
||||||
patch '/tags/999999999', params: { name: 'x' }
|
|
||||||
expect(response.status).to be_in([404, 500])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'バリデーションで update! が失敗したら(通常は 422 か 500)' do
|
|
||||||
patch "/tags/#{ tag.id }", params: { name: 'new', category: 'nico' }
|
|
||||||
expect(response.status).to be_in([422, 500])
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,150 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
RSpec.describe 'TheatreComments', type: :request do
|
|
||||||
def sign_in_as(user)
|
|
||||||
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'GET /theatres/:theatre_id/comments' do
|
|
||||||
let(:theatre) { create(:theatre) }
|
|
||||||
let(:other_theatre) { create(:theatre) }
|
|
||||||
let(:alice) { create(:user, name: 'Alice') }
|
|
||||||
let(:bob) { create(:user, name: 'Bob') }
|
|
||||||
|
|
||||||
let!(:comment_3) do
|
|
||||||
create(
|
|
||||||
:theatre_comment,
|
|
||||||
theatre: theatre,
|
|
||||||
no: 3,
|
|
||||||
user: alice,
|
|
||||||
content: 'third comment'
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:comment_1) do
|
|
||||||
create(
|
|
||||||
:theatre_comment,
|
|
||||||
theatre: theatre,
|
|
||||||
no: 1,
|
|
||||||
user: alice,
|
|
||||||
content: 'first comment'
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:comment_2) do
|
|
||||||
create(
|
|
||||||
:theatre_comment,
|
|
||||||
theatre: theatre,
|
|
||||||
no: 2,
|
|
||||||
user: bob,
|
|
||||||
content: 'second comment'
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
let!(:other_comment) do
|
|
||||||
create(
|
|
||||||
:theatre_comment,
|
|
||||||
theatre: other_theatre,
|
|
||||||
no: 1,
|
|
||||||
user: bob,
|
|
||||||
content: 'other theatre comment'
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'theatre_id で絞り込み、no_gt より大きいものを no 降順で返す' do
|
|
||||||
get "/theatres/#{theatre.id}/comments", params: { no_gt: 1 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response.parsed_body.map { |row| row['no'] }).to eq([3, 2])
|
|
||||||
expect(response.parsed_body.map { |row| row['content'] }).to eq([
|
|
||||||
'third comment',
|
|
||||||
'second comment'
|
|
||||||
])
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'user は id と name だけを含む' do
|
|
||||||
get "/theatres/#{theatre.id}/comments", params: { no_gt: 1 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
|
|
||||||
expect(response.parsed_body.first['user']).to eq({
|
|
||||||
'id' => alice.id,
|
|
||||||
'name' => 'Alice'
|
|
||||||
})
|
|
||||||
expect(response.parsed_body.first['user'].keys).to contain_exactly('id', 'name')
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'no_gt が負数なら 0 として扱う' do
|
|
||||||
get "/theatres/#{theatre.id}/comments", params: { no_gt: -100 }
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
|
||||||
expect(response.parsed_body.map { |row| row['no'] }).to eq([3, 2, 1])
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe 'POST /theatres/:theatre_id/comments' do
|
|
||||||
let(:user) { create(:user, name: 'Alice') }
|
|
||||||
let(:theatre) { create(:theatre, next_comment_no: 2) }
|
|
||||||
|
|
||||||
before do
|
|
||||||
create(
|
|
||||||
:theatre_comment,
|
|
||||||
theatre: theatre,
|
|
||||||
no: 1,
|
|
||||||
user: user,
|
|
||||||
content: 'existing comment'
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
it '未ログインなら 401 を返す' do
|
|
||||||
expect {
|
|
||||||
post "/theatres/#{theatre.id}/comments", params: { content: 'hello' }
|
|
||||||
}.not_to change(TheatreComment, :count)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'content が blank なら 422 を返す' do
|
|
||||||
sign_in_as(user)
|
|
||||||
|
|
||||||
expect {
|
|
||||||
post "/theatres/#{theatre.id}/comments", params: { content: ' ' }
|
|
||||||
}.not_to change(TheatreComment, :count)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:unprocessable_entity)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'theatre が存在しなければ 404 を返す' do
|
|
||||||
sign_in_as(user)
|
|
||||||
|
|
||||||
expect {
|
|
||||||
post '/theatres/999999/comments', params: { content: 'hello' }
|
|
||||||
}.not_to change(TheatreComment, :count)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:not_found)
|
|
||||||
end
|
|
||||||
|
|
||||||
it 'コメントを作成し、user を紐づけ、next_comment_no を進める' do
|
|
||||||
sign_in_as(user)
|
|
||||||
|
|
||||||
expect {
|
|
||||||
post "/theatres/#{theatre.id}/comments", params: { content: 'new comment' }
|
|
||||||
}.to change(TheatreComment, :count).by(1)
|
|
||||||
|
|
||||||
expect(response).to have_http_status(:created)
|
|
||||||
|
|
||||||
comment = TheatreComment.find_by!(theatre: theatre, no: 2)
|
|
||||||
|
|
||||||
expect(comment.user).to eq(user)
|
|
||||||
expect(comment.content).to eq('new comment')
|
|
||||||
expect(theatre.reload.next_comment_no).to eq(3)
|
|
||||||
|
|
||||||
expect(response.parsed_body.slice('theatre_id', 'no', 'user_id', 'content')).to eq({
|
|
||||||
'theatre_id' => theatre.id,
|
|
||||||
'no' => 2,
|
|
||||||
'user_id' => user.id,
|
|
||||||
'content' => 'new comment'
|
|
||||||
})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,307 +0,0 @@
|
|||||||
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 include(
|
|
||||||
'host_flg' => true,
|
|
||||||
'post_id' => nil,
|
|
||||||
'post_started_at' => nil
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(json.fetch('watching_users')).to contain_exactly(
|
|
||||||
{
|
|
||||||
'id' => member.id,
|
|
||||||
'name' => 'member user'
|
|
||||||
}
|
|
||||||
)
|
|
||||||
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 include(
|
|
||||||
'host_flg' => false,
|
|
||||||
'post_id' => nil,
|
|
||||||
'post_started_at' => nil
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(json.fetch('watching_users')).to contain_exactly(
|
|
||||||
{
|
|
||||||
'id' => member.id,
|
|
||||||
'name' => 'member user'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'id' => other_user.id,
|
|
||||||
'name' => 'other user'
|
|
||||||
}
|
|
||||||
)
|
|
||||||
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
|
|
||||||
@@ -8,9 +8,7 @@ RSpec.describe 'Wiki API', type: :request do
|
|||||||
|
|
||||||
let!(:tn) { TagName.create!(name: 'spec_wiki_title') }
|
let!(:tn) { TagName.create!(name: 'spec_wiki_title') }
|
||||||
let!(:page) do
|
let!(:page) do
|
||||||
WikiPage.create!(tag_name: tn, created_user: user, updated_user: user).tap do |p|
|
WikiPage.create!(tag_name: tn, created_user: user, updated_user: user)
|
||||||
Wiki::Commit.content!(page: p, body: 'init', created_user: user, message: 'init')
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'GET /wiki' do
|
describe 'GET /wiki' do
|
||||||
|
|||||||
@@ -5,11 +5,4 @@ module TestRecords
|
|||||||
role: 'member',
|
role: 'member',
|
||||||
banned: false)
|
banned: false)
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_admin_user!
|
|
||||||
User.create!(name: 'spec admin',
|
|
||||||
inheritance_code: SecureRandom.hex(16),
|
|
||||||
role: 'admin',
|
|
||||||
banned: false)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -8,11 +8,12 @@ RSpec.describe "nico:sync" do
|
|||||||
end
|
end
|
||||||
|
|
||||||
def create_tag!(name, category:)
|
def create_tag!(name, category:)
|
||||||
tn = TagName.find_undiscard_or_create_by!(name: name.to_s.strip)
|
tn = TagName.find_or_create_by!(name: name.to_s.strip)
|
||||||
Tag.find_undiscard_or_create_by!(tag_name_id: tn.id) { |t| t.category = category }
|
Tag.find_or_create_by!(tag_name_id: tn.id) { |t| t.category = category }
|
||||||
end
|
end
|
||||||
|
|
||||||
def link_nico_to_tag!(nico_tag, tag)
|
def link_nico_to_tag!(nico_tag, tag)
|
||||||
|
# NicoTagRelation がある前提(君の model からそう見える)
|
||||||
NicoTagRelation.create!(nico_tag_id: nico_tag.id, tag_id: tag.id)
|
NicoTagRelation.create!(nico_tag_id: nico_tag.id, tag_id: tag.id)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -34,12 +35,7 @@ RSpec.describe "nico:sync" do
|
|||||||
Tag.tagme
|
Tag.tagme
|
||||||
|
|
||||||
# pythonの出力(AAA が付く)
|
# pythonの出力(AAA が付く)
|
||||||
stub_python([{
|
stub_python([{ "code" => "sm9", "title" => "t", "tags" => ["AAA"] }])
|
||||||
'code' => 'sm9',
|
|
||||||
'title' => 't',
|
|
||||||
'tags' => ['AAA'],
|
|
||||||
'uploaded_at' => '2026-01-01 12:34:56',
|
|
||||||
'deleted_at' => '2026-01-31 00:00:00' }])
|
|
||||||
|
|
||||||
# 外部HTTPは今回「既存 post なので呼ばれない」はずだが、念のため塞ぐ
|
# 外部HTTPは今回「既存 post なので呼ばれない」はずだが、念のため塞ぐ
|
||||||
allow(URI).to receive(:open).and_return(StringIO.new("<html></html>"))
|
allow(URI).to receive(:open).and_return(StringIO.new("<html></html>"))
|
||||||
@@ -53,9 +49,6 @@ RSpec.describe "nico:sync" do
|
|||||||
expect(active_tag_names).to include("nico:AAA")
|
expect(active_tag_names).to include("nico:AAA")
|
||||||
expect(active_tag_names).to include("spec_linked")
|
expect(active_tag_names).to include("spec_linked")
|
||||||
|
|
||||||
expect(post.original_created_from).to eq(Time.iso8601('2026-01-01T03:34:00Z'))
|
|
||||||
expect(post.original_created_before).to eq(Time.iso8601('2026-01-01T03:35:00Z'))
|
|
||||||
|
|
||||||
# 差分が出るので bot が付く(kept_non_nico_ids != desired_non_nico_ids)
|
# 差分が出るので bot が付く(kept_non_nico_ids != desired_non_nico_ids)
|
||||||
expect(active_tag_names).to include("bot操作")
|
expect(active_tag_names).to include("bot操作")
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
|
|
||||||
RSpec.describe 'post_similarity:calc' do
|
|
||||||
include RakeTaskHelper
|
|
||||||
|
|
||||||
it 'calls Similarity::Calc with Post and :tags' do
|
|
||||||
# 必要最低限のデータ
|
|
||||||
t1 = Tag.create!(name: "t1")
|
|
||||||
t2 = Tag.create!(name: "t2")
|
|
||||||
t3 = Tag.create!(name: "t3")
|
|
||||||
|
|
||||||
p1 = Post.create!(url: "https://example.com/1")
|
|
||||||
p2 = Post.create!(url: "https://example.com/2")
|
|
||||||
p3 = Post.create!(url: "https://example.com/3")
|
|
||||||
|
|
||||||
# kept スコープが絡むなら、PostTag がデフォで kept になる前提
|
|
||||||
PostTag.create!(post: p1, tag: t1)
|
|
||||||
PostTag.create!(post: p1, tag: t2)
|
|
||||||
|
|
||||||
PostTag.create!(post: p2, tag: t1)
|
|
||||||
PostTag.create!(post: p2, tag: t3)
|
|
||||||
|
|
||||||
PostTag.create!(post: p3, tag: t3)
|
|
||||||
|
|
||||||
expect { run_rake_task("post_similarity:calc") }
|
|
||||||
.to change { PostSimilarity.count }.from(0)
|
|
||||||
|
|
||||||
ps = PostSimilarity.find_by!(post_id: p1.id, target_post_id: p2.id)
|
|
||||||
ps_rev = PostSimilarity.find_by!(post_id: p2.id, target_post_id: p1.id)
|
|
||||||
expect(ps_rev.cos).to eq(ps.cos)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
require 'rails_helper'
|
|
||||||
|
|
||||||
|
|
||||||
RSpec.describe 'tag_similarity:calc' do
|
|
||||||
include RakeTaskHelper
|
|
||||||
|
|
||||||
it 'calls Similarity::Calc with Tag and :posts' do
|
|
||||||
# 必要最低限のデータ
|
|
||||||
t1 = Tag.create!(name: "t1")
|
|
||||||
t2 = Tag.create!(name: "t2")
|
|
||||||
t3 = Tag.create!(name: "t3")
|
|
||||||
|
|
||||||
p1 = Post.create!(url: "https://example.com/1")
|
|
||||||
p2 = Post.create!(url: "https://example.com/2")
|
|
||||||
p3 = Post.create!(url: "https://example.com/3")
|
|
||||||
|
|
||||||
# kept スコープが絡むなら、PostTag がデフォで kept になる前提
|
|
||||||
PostTag.create!(post: p1, tag: t1)
|
|
||||||
PostTag.create!(post: p1, tag: t2)
|
|
||||||
|
|
||||||
PostTag.create!(post: p2, tag: t1)
|
|
||||||
PostTag.create!(post: p2, tag: t3)
|
|
||||||
|
|
||||||
PostTag.create!(post: p3, tag: t3)
|
|
||||||
|
|
||||||
expect { run_rake_task("tag_similarity:calc") }
|
|
||||||
.to change { TagSimilarity.count }.from(0)
|
|
||||||
|
|
||||||
ps = TagSimilarity.find_by!(tag_id: t1.id, target_tag_id: t2.id)
|
|
||||||
ps_rev = TagSimilarity.find_by!(tag_id: t2.id, target_tag_id: t1.id)
|
|
||||||
expect(ps_rev.cos).to eq(ps.cos)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
生成ファイル
+9
-133
@@ -9,14 +9,10 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
|
||||||
"@dnd-kit/modifiers": "^9.0.0",
|
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"@fontsource-variable/noto-sans-jp": "^5.2.9",
|
"@fontsource-variable/noto-sans-jp": "^5.2.9",
|
||||||
"@radix-ui/react-dialog": "^1.1.14",
|
"@radix-ui/react-dialog": "^1.1.14",
|
||||||
"@radix-ui/react-switch": "^1.2.5",
|
"@radix-ui/react-switch": "^1.2.5",
|
||||||
"@radix-ui/react-toast": "^1.2.14",
|
"@radix-ui/react-toast": "^1.2.14",
|
||||||
"@tanstack/react-query": "^5.90.2",
|
|
||||||
"axios": "^1.10.0",
|
"axios": "^1.10.0",
|
||||||
"camelcase-keys": "^9.1.3",
|
"camelcase-keys": "^9.1.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@@ -25,18 +21,16 @@
|
|||||||
"humps": "^2.0.1",
|
"humps": "^2.0.1",
|
||||||
"lucide-react": "^0.511.0",
|
"lucide-react": "^0.511.0",
|
||||||
"markdown-it": "^14.1.0",
|
"markdown-it": "^14.1.0",
|
||||||
"path-to-regexp": "^8.3.0",
|
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"react-dom": "^19.1.0",
|
"react-dom": "^19.1.0",
|
||||||
"react-helmet-async": "^2.0.5",
|
"react-helmet-async": "^2.0.5",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-markdown-editor-lite": "^1.3.4",
|
"react-markdown-editor-lite": "^1.3.4",
|
||||||
"react-router-dom": "^6.30.1",
|
"react-router-dom": "^6.30.0",
|
||||||
"react-youtube": "^10.1.0",
|
"react-youtube": "^10.1.0",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.3.0",
|
"tailwind-merge": "^3.3.0",
|
||||||
"unist-util-visit-parents": "^6.0.1",
|
"unist-util-visit-parents": "^6.0.1"
|
||||||
"zustand": "^5.0.8"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.25.0",
|
"@eslint/js": "^9.25.0",
|
||||||
@@ -377,59 +371,6 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@dnd-kit/accessibility": {
|
|
||||||
"version": "3.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
|
||||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=16.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@dnd-kit/core": {
|
|
||||||
"version": "6.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
|
||||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@dnd-kit/accessibility": "^3.1.1",
|
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"tslib": "^2.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=16.8.0",
|
|
||||||
"react-dom": ">=16.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@dnd-kit/modifiers": {
|
|
||||||
"version": "9.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz",
|
|
||||||
"integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"tslib": "^2.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@dnd-kit/core": "^6.3.0",
|
|
||||||
"react": ">=16.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@dnd-kit/utilities": {
|
|
||||||
"version": "3.2.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
|
||||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=16.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@esbuild/aix-ppc64": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.25.4",
|
"version": "0.25.4",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz",
|
||||||
@@ -1969,32 +1910,6 @@
|
|||||||
"win32"
|
"win32"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@tanstack/query-core": {
|
|
||||||
"version": "5.90.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.2.tgz",
|
|
||||||
"integrity": "sha512-k/TcR3YalnzibscALLwxeiLUub6jN5EDLwKDiO7q5f4ICEoptJ+n9+7vcEFy5/x/i6Q+Lb/tXrsKCggf5uQJXQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/tannerlinsley"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tanstack/react-query": {
|
|
||||||
"version": "5.90.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.2.tgz",
|
|
||||||
"integrity": "sha512-CLABiR+h5PYfOWr/z+vWFt5VsOA2ekQeRQBFSKlcoW6Ndx/f8rfyVmq4LbgOM4GG2qtxAxjLYLOpCNTYm4uKzw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@tanstack/query-core": "5.90.2"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/tannerlinsley"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": "^18 || ^19"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/axios": {
|
"node_modules/@types/axios": {
|
||||||
"version": "0.14.4",
|
"version": "0.14.4",
|
||||||
"resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.4.tgz",
|
"resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.4.tgz",
|
||||||
@@ -5581,16 +5496,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/path-to-regexp": {
|
|
||||||
"version": "8.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
|
|
||||||
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "opencollective",
|
|
||||||
"url": "https://opencollective.com/express"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/picocolors": {
|
"node_modules/picocolors": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||||
@@ -6030,9 +5935,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-router": {
|
"node_modules/react-router": {
|
||||||
"version": "6.30.1",
|
"version": "6.30.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
|
||||||
"integrity": "sha512-X1m21aEmxGXqENEPG3T6u0Th7g0aS4ZmoNynhbs+Cn+q+QGTLt+d5IQ2bHAXKzKcxGJjxACpVbnYQSCRcfxHlQ==",
|
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remix-run/router": "1.23.0"
|
"@remix-run/router": "1.23.0"
|
||||||
@@ -6045,13 +5950,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-router-dom": {
|
"node_modules/react-router-dom": {
|
||||||
"version": "6.30.1",
|
"version": "6.30.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
|
||||||
"integrity": "sha512-llKsgOkZdbPU1Eg3zK8lCn+sjD9wMRZZPuzmdWWX5SUs8OFkN5HnFVC0u5KMeMaC9aoancFI/KoLuKPqN+hxHw==",
|
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remix-run/router": "1.23.0",
|
"@remix-run/router": "1.23.0",
|
||||||
"react-router": "6.30.1"
|
"react-router": "6.30.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
@@ -7325,35 +7230,6 @@
|
|||||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/zustand": {
|
|
||||||
"version": "5.0.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
|
|
||||||
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=12.20.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@types/react": ">=18.0.0",
|
|
||||||
"immer": ">=9.0.6",
|
|
||||||
"react": ">=18.0.0",
|
|
||||||
"use-sync-external-store": ">=1.2.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@types/react": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"immer": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"react": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"use-sync-external-store": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/zwitch": {
|
"node_modules/zwitch": {
|
||||||
"version": "2.0.4",
|
"version": "2.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
|
||||||
|
|||||||
+1
-7
@@ -11,14 +11,10 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
|
||||||
"@dnd-kit/modifiers": "^9.0.0",
|
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
|
||||||
"@fontsource-variable/noto-sans-jp": "^5.2.9",
|
"@fontsource-variable/noto-sans-jp": "^5.2.9",
|
||||||
"@radix-ui/react-dialog": "^1.1.14",
|
"@radix-ui/react-dialog": "^1.1.14",
|
||||||
"@radix-ui/react-switch": "^1.2.5",
|
"@radix-ui/react-switch": "^1.2.5",
|
||||||
"@radix-ui/react-toast": "^1.2.14",
|
"@radix-ui/react-toast": "^1.2.14",
|
||||||
"@tanstack/react-query": "^5.90.2",
|
|
||||||
"axios": "^1.10.0",
|
"axios": "^1.10.0",
|
||||||
"camelcase-keys": "^9.1.3",
|
"camelcase-keys": "^9.1.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@@ -27,17 +23,15 @@
|
|||||||
"humps": "^2.0.1",
|
"humps": "^2.0.1",
|
||||||
"lucide-react": "^0.511.0",
|
"lucide-react": "^0.511.0",
|
||||||
"markdown-it": "^14.1.0",
|
"markdown-it": "^14.1.0",
|
||||||
"path-to-regexp": "^8.3.0",
|
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"react-dom": "^19.1.0",
|
"react-dom": "^19.1.0",
|
||||||
"react-helmet-async": "^2.0.5",
|
"react-helmet-async": "^2.0.5",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-markdown-editor-lite": "^1.3.4",
|
"react-markdown-editor-lite": "^1.3.4",
|
||||||
"react-router-dom": "^6.30.1",
|
"react-router-dom": "^6.30.0",
|
||||||
"react-youtube": "^10.1.0",
|
"react-youtube": "^10.1.0",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.3.0",
|
"tailwind-merge": "^3.3.0",
|
||||||
"zustand": "^5.0.8",
|
|
||||||
"unist-util-visit-parents": "^6.0.1"
|
"unist-util-visit-parents": "^6.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const fetchPosts = async tagName => (await axios.get (`${ API_BASE_URL }/posts`,
|
|||||||
match: 'all',
|
match: 'all',
|
||||||
limit: '20' }) } })).data.posts
|
limit: '20' }) } })).data.posts
|
||||||
|
|
||||||
const fetchTags = async () => (await axios.get (`${ API_BASE_URL }/tags`)).data.tags
|
const fetchTags = async () => (await axios.get (`${ API_BASE_URL }/tags`)).data
|
||||||
const fetchTagNames = async () => (await fetchTags ()).map (tag => tag.name)
|
const fetchTagNames = async () => (await fetchTags ()).map (tag => tag.name)
|
||||||
|
|
||||||
const fetchWikiPages = async () => (await axios.get (`${ API_BASE_URL }/wiki`)).data
|
const fetchWikiPages = async () => (await axios.get (`${ API_BASE_URL }/wiki`)).data
|
||||||
|
|||||||
+31
-63
@@ -1,26 +1,19 @@
|
|||||||
import { AnimatePresence, LayoutGroup } from 'framer-motion'
|
import axios from 'axios'
|
||||||
|
import toCamel from 'camelcase-keys'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { BrowserRouter,
|
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
|
||||||
Navigate,
|
|
||||||
Route,
|
|
||||||
Routes,
|
|
||||||
useLocation } from 'react-router-dom'
|
|
||||||
|
|
||||||
import RouteBlockerOverlay from '@/components/RouteBlockerOverlay'
|
|
||||||
import TopNav from '@/components/TopNav'
|
import TopNav from '@/components/TopNav'
|
||||||
import { Toaster } from '@/components/ui/toaster'
|
import { Toaster } from '@/components/ui/toaster'
|
||||||
import { apiPost, isApiError } from '@/lib/api'
|
import { API_BASE_URL } from '@/config'
|
||||||
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
||||||
import NotFound from '@/pages/NotFound'
|
import NotFound from '@/pages/NotFound'
|
||||||
import PostDetailPage from '@/pages/posts/PostDetailPage'
|
import PostDetailPage from '@/pages/posts/PostDetailPage'
|
||||||
import PostHistoryPage from '@/pages/posts/PostHistoryPage'
|
import PostHistoryPage from '@/pages/posts/PostHistoryPage'
|
||||||
import PostListPage from '@/pages/posts/PostListPage'
|
import PostListPage from '@/pages/posts/PostListPage'
|
||||||
import PostNewPage from '@/pages/posts/PostNewPage'
|
import PostNewPage from '@/pages/posts/PostNewPage'
|
||||||
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 TagListPage from '@/pages/tags/TagListPage'
|
|
||||||
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'
|
||||||
@@ -28,62 +21,23 @@ import WikiHistoryPage from '@/pages/wiki/WikiHistoryPage'
|
|||||||
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
||||||
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
|
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
|
||||||
|
|
||||||
import type { Dispatch, FC, SetStateAction } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { User } from '@/types'
|
import type { User } from '@/types'
|
||||||
|
|
||||||
|
|
||||||
const RouteTransitionWrapper = ({ user, setUser }: {
|
|
||||||
user: User | null
|
|
||||||
setUser: Dispatch<SetStateAction<User | null>> }) => {
|
|
||||||
const location = useLocation ()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<LayoutGroup id="gallery-shared">
|
|
||||||
<AnimatePresence mode="wait">
|
|
||||||
<Routes location={location} key={location.pathname}>
|
|
||||||
<Route path="/" element={<Navigate to="/posts" replace/>}/>
|
|
||||||
<Route path="/posts" element={<PostListPage/>}/>
|
|
||||||
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
|
|
||||||
<Route path="/posts/search" element={<PostSearchPage/>}/>
|
|
||||||
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
|
|
||||||
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
|
|
||||||
<Route path="/tags" element={<TagListPage/>}/>
|
|
||||||
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
|
|
||||||
<Route path="/theatres/:id" element={<TheatreDetailPage/>}/>
|
|
||||||
<Route path="/wiki" element={<WikiSearchPage/>}/>
|
|
||||||
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
|
|
||||||
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
|
|
||||||
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
|
|
||||||
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
|
|
||||||
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
|
|
||||||
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
|
|
||||||
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
|
|
||||||
<Route path="*" element={<NotFound/>}/>
|
|
||||||
</Routes>
|
|
||||||
</AnimatePresence>
|
|
||||||
</LayoutGroup>)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const PostDetailRoute = ({ user }: { user: User | null }) => {
|
|
||||||
const location = useLocation ()
|
|
||||||
const key = location.pathname
|
|
||||||
return <PostDetailPage key={key} user={user}/>
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export default (() => {
|
export default (() => {
|
||||||
const [user, setUser] = useState<User | null> (null)
|
const [user, setUser] = useState<User | null> (null)
|
||||||
const [status, setStatus] = useState (200)
|
const [status, setStatus] = useState (200)
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
const createUser = async () => {
|
const createUser = async () => {
|
||||||
const data = await apiPost<{ code: string; user: User }> ('/users')
|
const res = await axios.post (`${ API_BASE_URL }/users`)
|
||||||
|
const data = res.data as { code: string; user: any }
|
||||||
if (data.code)
|
if (data.code)
|
||||||
{
|
{
|
||||||
localStorage.setItem ('user_code', data.code)
|
localStorage.setItem ('user_code', data.code)
|
||||||
setUser (data.user)
|
setUser (toCamel (data.user, { deep: true }) as User)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,16 +47,17 @@ export default (() => {
|
|||||||
void (async () => {
|
void (async () => {
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await apiPost<{ valid: boolean; user: User }> ('/users/verify', { code })
|
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code })
|
||||||
|
const data = res.data as { valid: boolean, user: any }
|
||||||
if (data.valid)
|
if (data.valid)
|
||||||
setUser (data.user)
|
setUser (toCamel (data.user, { deep: true }))
|
||||||
else
|
else
|
||||||
await createUser ()
|
await createUser ()
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err)
|
||||||
{
|
{
|
||||||
if (isApiError (err))
|
if (axios.isAxiosError (err))
|
||||||
setStatus (err.response?.status ?? 200)
|
setStatus (err.status ?? 200)
|
||||||
}
|
}
|
||||||
}) ()
|
}) ()
|
||||||
}
|
}
|
||||||
@@ -117,14 +72,27 @@ export default (() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<RouteBlockerOverlay/>
|
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<div className="flex flex-col h-screen w-screen">
|
<div className="flex flex-col h-screen w-screen">
|
||||||
<TopNav user={user}/>
|
<TopNav user={user}/>
|
||||||
<RouteTransitionWrapper user={user} setUser={setUser}/>
|
<Routes>
|
||||||
|
<Route path="/" element={<Navigate to="/posts" replace/>}/>
|
||||||
|
<Route path="/posts" element={<PostListPage/>}/>
|
||||||
|
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
|
||||||
|
<Route path="/posts/:id" element={<PostDetailPage user={user}/>}/>
|
||||||
|
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
|
||||||
|
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
|
||||||
|
<Route path="/wiki" element={<WikiSearchPage/>}/>
|
||||||
|
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
|
||||||
|
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
|
||||||
|
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
|
||||||
|
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
|
||||||
|
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
|
||||||
|
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
|
||||||
|
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
|
||||||
|
<Route path="*" element={<NotFound/>}/>
|
||||||
|
</Routes>
|
||||||
</div>
|
</div>
|
||||||
<Toaster/>
|
<Toaster/>
|
||||||
</BrowserRouter>
|
</BrowserRouter>)
|
||||||
</>)
|
|
||||||
}) satisfies FC
|
}) satisfies FC
|
||||||
|
|||||||
@@ -1,97 +0,0 @@
|
|||||||
import { useDraggable, useDroppable } from '@dnd-kit/core'
|
|
||||||
import { CSS } from '@dnd-kit/utilities'
|
|
||||||
import { motion } from 'framer-motion'
|
|
||||||
import { useRef } from 'react'
|
|
||||||
|
|
||||||
import TagLink from '@/components/TagLink'
|
|
||||||
import { cn } from '@/lib/utils'
|
|
||||||
|
|
||||||
import type { CSSProperties, FC, MutableRefObject } from 'react'
|
|
||||||
|
|
||||||
import type { Tag } from '@/types'
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
tag: Tag
|
|
||||||
nestLevel: number
|
|
||||||
pathKey: string
|
|
||||||
parentTagId?: number
|
|
||||||
suppressClickRef: MutableRefObject<boolean>
|
|
||||||
sp?: boolean }
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ tag, nestLevel, pathKey, parentTagId, suppressClickRef, sp }: Props) => {
|
|
||||||
const dndId = `tag-node:${ pathKey }`
|
|
||||||
|
|
||||||
const downPosRef = useRef<{ x: number; y: number } | null> (null)
|
|
||||||
const armedRef = useRef (false)
|
|
||||||
|
|
||||||
const armEatNextClick = () => {
|
|
||||||
if (armedRef.current)
|
|
||||||
return
|
|
||||||
|
|
||||||
armedRef.current = true
|
|
||||||
suppressClickRef.current = true
|
|
||||||
|
|
||||||
const handler = (ev: MouseEvent) => {
|
|
||||||
ev.preventDefault ()
|
|
||||||
ev.stopPropagation ()
|
|
||||||
armedRef.current = false
|
|
||||||
suppressClickRef.current = false
|
|
||||||
}
|
|
||||||
|
|
||||||
addEventListener ('click', handler, { capture: true, once: true })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { attributes,
|
|
||||||
listeners,
|
|
||||||
setNodeRef: setDragRef,
|
|
||||||
transform,
|
|
||||||
isDragging: dragging } = useDraggable ({ id: dndId,
|
|
||||||
data: { kind: 'tag',
|
|
||||||
tagId: tag.id,
|
|
||||||
parentTagId } })
|
|
||||||
|
|
||||||
const { setNodeRef: setDropRef, isOver: over } = useDroppable ({
|
|
||||||
id: dndId,
|
|
||||||
data: { kind: 'tag', tagId: tag.id } })
|
|
||||||
|
|
||||||
const style: CSSProperties = { transform: CSS.Translate.toString (transform),
|
|
||||||
visibility: dragging ? 'hidden' : 'visible' }
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
onPointerDownCapture={e => {
|
|
||||||
downPosRef.current = { x: e.clientX, y: e.clientY }
|
|
||||||
}}
|
|
||||||
onPointerMoveCapture={e => {
|
|
||||||
const p = downPosRef.current
|
|
||||||
if (!(p))
|
|
||||||
return
|
|
||||||
const dx = e.clientX - p.x
|
|
||||||
const dy = e.clientY - p.y
|
|
||||||
if (dx * dx + dy * dy >= 9)
|
|
||||||
armEatNextClick ()
|
|
||||||
}}
|
|
||||||
onPointerUpCapture={() => {
|
|
||||||
downPosRef.current = null
|
|
||||||
}}
|
|
||||||
onClickCapture={e => {
|
|
||||||
if (suppressClickRef.current)
|
|
||||||
{
|
|
||||||
e.preventDefault ()
|
|
||||||
e.stopPropagation ()
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
ref={node => {
|
|
||||||
setDragRef (node)
|
|
||||||
setDropRef (node)
|
|
||||||
}}
|
|
||||||
style={style}
|
|
||||||
className={cn ('rounded select-none', over && 'ring-2 ring-offset-2')}
|
|
||||||
{...attributes}
|
|
||||||
{...listeners}>
|
|
||||||
<motion.div layoutId={`tag-${ sp ? 'sp-' : '' }${ tag.id }`}>
|
|
||||||
<TagLink tag={tag} nestLevel={nestLevel}/>
|
|
||||||
</motion.div>
|
|
||||||
</div>)
|
|
||||||
}) satisfies FC<Props>
|
|
||||||
@@ -1,185 +1,59 @@
|
|||||||
import { forwardRef,
|
import { useRef, useLayoutEffect, useEffect, useState } from 'react'
|
||||||
useCallback,
|
type Props = { id: string,
|
||||||
useEffect,
|
width: number,
|
||||||
useImperativeHandle,
|
height: number,
|
||||||
useLayoutEffect,
|
style?: CSSProperties }
|
||||||
useMemo,
|
|
||||||
useRef,
|
|
||||||
useState } from 'react'
|
|
||||||
|
|
||||||
import type { CSSProperties, ForwardedRef } from 'react'
|
import type { CSSProperties, FC } 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>) => {
|
export default ((props: Props) => {
|
||||||
const { id, width, height, style = { }, onLoadComplete, onMetadataChange } = props
|
const { id, width, height, style = { } } = 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 =
|
const src = `https://embed.nicovideo.jp/watch/${id}?persistence=1&oldScript=1&referer=&from=0&allowProgrammaticFullScreen=1`;
|
||||||
`${ EMBED_ORIGIN }/watch/${ id }`
|
|
||||||
+ '?jsapi=1'
|
|
||||||
+ `&playerId=${ encodeURIComponent (playerId) }`
|
|
||||||
+ '&persistence=1'
|
|
||||||
+ '&oldScript=1'
|
|
||||||
+ '&referer='
|
|
||||||
+ '&from=0'
|
|
||||||
+ '&allowProgrammaticFullScreen=1'
|
|
||||||
|
|
||||||
const styleFullScreen: CSSProperties =
|
const styleFullScreen: CSSProperties = fullScreen ? {
|
||||||
fullScreen
|
top: 0,
|
||||||
? { top: 0,
|
|
||||||
left: landscape ? 0 : '100%',
|
left: landscape ? 0 : '100%',
|
||||||
position: 'fixed',
|
position: 'fixed',
|
||||||
width: screenWidth,
|
width: screenWidth,
|
||||||
height: screenHeight,
|
height: screenHeight,
|
||||||
zIndex: 2_147_483_647,
|
zIndex: 2147483647,
|
||||||
maxWidth: 'none',
|
maxWidth: 'none',
|
||||||
transformOrigin: '0% 0%',
|
transformOrigin: '0% 0%',
|
||||||
transform: landscape ? 'none' : 'rotate(90deg)',
|
transform: landscape ? 'none' : 'rotate(90deg)',
|
||||||
WebkitTransformOrigin: '0% 0%',
|
WebkitTransformOrigin: '0% 0%',
|
||||||
WebkitTransform: landscape ? 'none' : 'rotate(90deg)' }
|
WebkitTransform: landscape ? 'none' : 'rotate(90deg)' } : {};
|
||||||
: { }
|
|
||||||
|
|
||||||
const margedStyle: CSSProperties =
|
const margedStyle = {
|
||||||
{ border: 'none', maxWidth: '100%', ...style, ...styleFullScreen }
|
border: 'none',
|
||||||
|
maxWidth: '100%',
|
||||||
const postToPlayer = useCallback ((message: NiconicoCommand) => {
|
...style,
|
||||||
const win = iframeRef.current?.contentWindow
|
...styleFullScreen }
|
||||||
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<NiconicoPlayerMessage>) => {
|
const onMessage = (event: MessageEvent<any>) => {
|
||||||
if (!(iframeRef.current)
|
if (!(iframeRef.current)
|
||||||
|| (event.source !== iframeRef.current.contentWindow)
|
|| (event.source !== iframeRef.current.contentWindow))
|
||||||
|| (event.origin !== EMBED_ORIGIN))
|
|
||||||
return
|
return
|
||||||
|
|
||||||
const data = event.data
|
if (event.data.eventName === 'enterProgrammaticFullScreen')
|
||||||
|
|
||||||
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)
|
setFullScreen (true)
|
||||||
return
|
else if (event.data.eventName === 'exitProgrammaticFullScreen')
|
||||||
}
|
|
||||||
|
|
||||||
if (data.eventName === 'exitProgrammaticFullScreen')
|
|
||||||
{
|
|
||||||
setFullScreen (false)
|
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))
|
||||||
@@ -187,18 +61,18 @@ export default forwardRef ((props: Props, ref: ForwardedRef<NiconicoViewerHandle
|
|||||||
|
|
||||||
const initialScrollX = scrollX
|
const initialScrollX = scrollX
|
||||||
const initialScrollY = scrollY
|
const initialScrollY = scrollY
|
||||||
let timer: ReturnType<typeof setTimeout>
|
let timer: NodeJS.Timeout
|
||||||
let ended = false
|
let ended = false
|
||||||
|
|
||||||
const pollingResize = () => {
|
const pollingResize = () => {
|
||||||
if (ended)
|
if (ended)
|
||||||
return
|
return
|
||||||
|
|
||||||
const isLandscape = innerWidth >= innerHeight
|
const landscape = innerWidth >= innerHeight
|
||||||
const windowWidth = `${ isLandscape ? innerWidth : innerHeight }px`
|
const windowWidth = `${landscape ? innerWidth : innerHeight}px`
|
||||||
const windowHeight = `${ isLandscape ? innerHeight : innerWidth }px`
|
const windowHeight = `${landscape ? innerHeight : innerWidth}px`
|
||||||
|
|
||||||
setLandscape (isLandscape)
|
setLandscape (landscape)
|
||||||
setScreenWidth (windowWidth)
|
setScreenWidth (windowWidth)
|
||||||
setScreenHeight (windowHeight)
|
setScreenHeight (windowHeight)
|
||||||
timer = setTimeout (startPollingResize, 200)
|
timer = setTimeout (startPollingResize, 200)
|
||||||
@@ -223,17 +97,15 @@ export default forwardRef ((props: Props, ref: ForwardedRef<NiconicoViewerHandle
|
|||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (!(fullScreen))
|
if (!(fullScreen))
|
||||||
return
|
return
|
||||||
|
|
||||||
scrollTo (0, 0)
|
scrollTo (0, 0)
|
||||||
}, [screenWidth, screenHeight, fullScreen])
|
}, [screenWidth, screenHeight, fullScreen])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<iframe
|
<iframe ref={iframeRef}
|
||||||
ref={iframeRef}
|
|
||||||
src={src}
|
src={src}
|
||||||
width={width}
|
width={width}
|
||||||
height={height}
|
height={height}
|
||||||
style={margedStyle}
|
style={margedStyle}
|
||||||
allowFullScreen
|
allowFullScreen
|
||||||
allow="autoplay"/>)
|
allow="autoplay"/>)
|
||||||
})
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import toCamel from 'camelcase-keys'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
||||||
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { apiPut } from '@/lib/api'
|
import { API_BASE_URL } from '@/config'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
@@ -39,11 +41,14 @@ export default (({ post, onSave }: Props) => {
|
|||||||
const [tags, setTags] = useState<string> ('')
|
const [tags, setTags] = useState<string> ('')
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const data = await apiPut<Post> (
|
const res = await axios.put (
|
||||||
`/posts/${ post.id }`,
|
`${ API_BASE_URL }/posts/${ post.id }`,
|
||||||
{ title, tags, original_created_from: originalCreatedFrom,
|
{ title, tags,
|
||||||
|
original_created_from: originalCreatedFrom,
|
||||||
original_created_before: originalCreatedBefore },
|
original_created_before: originalCreatedBefore },
|
||||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
{ headers: { 'Content-Type': 'multipart/form-data',
|
||||||
|
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||||
|
const data = toCamel (res.data as any, { deep: true }) as Post
|
||||||
onSave ({ ...post,
|
onSave ({ ...post,
|
||||||
title: data.title,
|
title: data.title,
|
||||||
tags: data.tags,
|
tags: data.tags,
|
||||||
|
|||||||
@@ -4,60 +4,31 @@ 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, RefObject } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { NiconicoMetadata, NiconicoVideoInfo, NiconicoViewerHandle, Post } from '@/types'
|
import type { Post } from '@/types'
|
||||||
|
|
||||||
type Props = {
|
type Props = { post: Post }
|
||||||
ref?: RefObject<NiconicoViewerHandle | null>
|
|
||||||
post: Post
|
|
||||||
onLoadComplete?: (info: NiconicoVideoInfo) => void
|
|
||||||
onMetadataChange?: (meta: NiconicoMetadata) => void }
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ ref, post, onLoadComplete, onMetadataChange }: Props) => {
|
export default (({ post }: 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 ('.'))
|
||||||
{
|
{
|
||||||
case 'nicovideo.jp':
|
case 'nicovideo.jp':
|
||||||
{
|
{
|
||||||
const mVideoId = url.pathname.match (/(?<=\/watch\/)[a-zA-Z0-9]+?(?=\/|$)/)
|
const [videoId] = url.pathname.match (/(?<=\/watch\/)[a-zA-Z0-9]+?(?=\/|$)/)!
|
||||||
if (!(mVideoId))
|
return <NicoViewer id={videoId} width={640} height={360}/>
|
||||||
break
|
|
||||||
|
|
||||||
const [videoId] = mVideoId
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NicoViewer
|
|
||||||
ref={ref}
|
|
||||||
id={videoId}
|
|
||||||
width={640}
|
|
||||||
height={360}
|
|
||||||
onLoadComplete={onLoadComplete}
|
|
||||||
onMetadataChange={onMetadataChange}/>)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'twitter.com':
|
case 'twitter.com':
|
||||||
case 'x.com':
|
case 'x.com':
|
||||||
{
|
const [userId] = url.pathname.match (/(?<=\/)[^\/]+?(?=\/|$|\?)/)!
|
||||||
const mUserId = url.pathname.match (/(?<=\/)[^\/]+?(?=\/|$|\?)/)
|
const [statusId] = url.pathname.match (/(?<=\/status\/)\d+?(?=\/|$|\?)/)!
|
||||||
const mStatusId = url.pathname.match (/(?<=\/status\/)\d+?(?=\/|$|\?)/)
|
|
||||||
if (!(mUserId) || !(mStatusId))
|
|
||||||
break
|
|
||||||
|
|
||||||
const [userId] = mUserId
|
|
||||||
const [statusId] = mStatusId
|
|
||||||
|
|
||||||
return <TwitterEmbed userId={userId} statusId={statusId}/>
|
return <TwitterEmbed userId={userId} statusId={statusId}/>
|
||||||
}
|
|
||||||
|
|
||||||
case 'youtube.com':
|
case 'youtube.com':
|
||||||
{
|
{
|
||||||
const videoId = url.searchParams.get ('v')
|
const videoId = url.searchParams.get ('v')!
|
||||||
if (!(videoId))
|
|
||||||
break
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<YoutubeEmbed videoId={videoId} opts={{ playerVars: {
|
<YoutubeEmbed videoId={videoId} opts={{ playerVars: {
|
||||||
playsinline: 1,
|
playsinline: 1,
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
// TODO: TagSearch と共通化する.
|
import axios from 'axios'
|
||||||
|
import toCamel from 'camelcase-keys'
|
||||||
import { useRef, useState } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
|
|
||||||
import TagSearchBox from '@/components/TagSearchBox'
|
import TagSearchBox from '@/components/TagSearchBox'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import TextArea from '@/components/common/TextArea'
|
import TextArea from '@/components/common/TextArea'
|
||||||
import { apiGet } from '@/lib/api'
|
import { API_BASE_URL } from '@/config'
|
||||||
|
|
||||||
import type { FC, SyntheticEvent } from 'react'
|
import type { FC, SyntheticEvent } from 'react'
|
||||||
|
|
||||||
@@ -27,8 +27,8 @@ const getTokenAt = (value: string, pos: number) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const replaceToken = (value: string, start: number, end: number, text: string) =>
|
const replaceToken = (value: string, start: number, end: number, text: string) => (
|
||||||
`${ value.slice (0, start) }${ text }${ value.slice (end) }`
|
`${ value.slice (0, start) }${ text }${ value.slice (end) }`)
|
||||||
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -40,17 +40,16 @@ export default (({ tags, setTags }: Props) => {
|
|||||||
const ref = useRef<HTMLTextAreaElement> (null)
|
const ref = useRef<HTMLTextAreaElement> (null)
|
||||||
|
|
||||||
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
|
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
|
||||||
const [focused, setFocused] = useState (false)
|
|
||||||
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
||||||
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
||||||
|
|
||||||
const handleTagSelect = (tag: Tag) => {
|
const handleTagSelect = (tag: Tag) => {
|
||||||
setSuggestionsVsbl (false)
|
setSuggestionsVsbl (false)
|
||||||
const textarea = ref.current!
|
const textarea = ref.current!
|
||||||
const newValue = replaceToken (tags, bounds.start, bounds.end, tag.name + ' ')
|
const newValue = replaceToken (tags, bounds.start, bounds.end, tag.name)
|
||||||
setTags (newValue)
|
setTags (newValue)
|
||||||
requestAnimationFrame (async () => {
|
requestAnimationFrame (async () => {
|
||||||
const p = bounds.start + tag.name.length + 1
|
const p = bounds.start + tag.name.length
|
||||||
textarea.selectionStart = textarea.selectionEnd = p
|
textarea.selectionStart = textarea.selectionEnd = p
|
||||||
textarea.focus ()
|
textarea.focus ()
|
||||||
await recompute (p, newValue)
|
await recompute (p, newValue)
|
||||||
@@ -59,21 +58,14 @@ export default (({ tags, setTags }: Props) => {
|
|||||||
|
|
||||||
const recompute = async (pos: number, v: string = tags) => {
|
const recompute = async (pos: number, v: string = tags) => {
|
||||||
const { start, end, token } = getTokenAt (v, pos)
|
const { start, end, token } = getTokenAt (v, pos)
|
||||||
if (!(token.trim ()))
|
|
||||||
{
|
|
||||||
setSuggestionsVsbl (false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setBounds ({ start, end })
|
setBounds ({ start, end })
|
||||||
|
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q: token } })
|
||||||
const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q: token, nico: '0' } })
|
setSuggestions (toCamel (res.data as any, { deep: true }) as Tag[])
|
||||||
setSuggestions (data.filter (t => t.postCount > 0))
|
|
||||||
setSuggestionsVsbl (suggestions.length > 0)
|
setSuggestionsVsbl (suggestions.length > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative w-full">
|
<div>
|
||||||
<Label>タグ</Label>
|
<Label>タグ</Label>
|
||||||
<TextArea
|
<TextArea
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -82,18 +74,11 @@ export default (({ tags, setTags }: Props) => {
|
|||||||
onSelect={async (ev: SyntheticEvent<HTMLTextAreaElement>) => {
|
onSelect={async (ev: SyntheticEvent<HTMLTextAreaElement>) => {
|
||||||
const pos = (ev.target as HTMLTextAreaElement).selectionStart
|
const pos = (ev.target as HTMLTextAreaElement).selectionStart
|
||||||
await recompute (pos)
|
await recompute (pos)
|
||||||
}}
|
|
||||||
onFocus={() => setFocused (true)}
|
|
||||||
onBlur={() => {
|
|
||||||
setFocused (false)
|
|
||||||
setSuggestionsVsbl (false)
|
|
||||||
}}/>
|
}}/>
|
||||||
{focused && (
|
<TagSearchBox suggestions={suggestionsVsbl && suggestions.length
|
||||||
<TagSearchBox
|
|
||||||
suggestions={suggestionsVsbl && suggestions.length > 0
|
|
||||||
? suggestions
|
? suggestions
|
||||||
: [] as Tag[]}
|
: [] as Tag[]}
|
||||||
activeIndex={-1}
|
activeIndex={-1}
|
||||||
onSelect={handleTagSelect}/>)}
|
onSelect={handleTagSelect}/>
|
||||||
</div>)
|
</div>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,9 +1,4 @@
|
|||||||
import { motion } from 'framer-motion'
|
import { Link } from 'react-router-dom'
|
||||||
import { useRef } from 'react'
|
|
||||||
import { useLocation } from 'react-router-dom'
|
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import { useSharedTransitionStore } from '@/stores/sharedTransitionStore'
|
|
||||||
|
|
||||||
import type { FC, MouseEvent } from 'react'
|
import type { FC, MouseEvent } from 'react'
|
||||||
|
|
||||||
@@ -13,58 +8,18 @@ type Props = { posts: Post[]
|
|||||||
onClick?: (event: MouseEvent<HTMLElement>) => void }
|
onClick?: (event: MouseEvent<HTMLElement>) => void }
|
||||||
|
|
||||||
|
|
||||||
export default (({ posts, onClick }: Props) => {
|
export default (({ posts, onClick }: Props) => (
|
||||||
const location = useLocation ()
|
|
||||||
|
|
||||||
const setForLocationKey = useSharedTransitionStore (s => s.setForLocationKey)
|
|
||||||
|
|
||||||
const cardRef = useRef<HTMLDivElement> (null)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex flex-wrap gap-6 p-4">
|
<div className="flex flex-wrap gap-6 p-4">
|
||||||
{posts.map ((post, i) => {
|
{posts.map ((post, i) => (
|
||||||
const sharedId = `page-${ post.id }`
|
<Link to={`/posts/${ post.id }`}
|
||||||
const layoutId = sharedId
|
|
||||||
|
|
||||||
return (
|
|
||||||
<PrefetchLink
|
|
||||||
to={`/posts/${ post.id }`}
|
|
||||||
key={post.id}
|
key={post.id}
|
||||||
className="w-40 h-40"
|
className="w-40 h-40 overflow-hidden rounded-lg shadow-md hover:shadow-lg"
|
||||||
state={{ sharedId }}
|
onClick={onClick}>
|
||||||
onClick={e => {
|
|
||||||
setForLocationKey (location.key, sharedId)
|
|
||||||
onClick?.(e)
|
|
||||||
}}>
|
|
||||||
<motion.div
|
|
||||||
ref={cardRef}
|
|
||||||
layoutId={layoutId}
|
|
||||||
className="w-full h-full overflow-hidden rounded-xl shadow
|
|
||||||
transform-gpu will-change-transform"
|
|
||||||
whileHover={{ scale: 1.02 }}
|
|
||||||
onLayoutAnimationStart={() => {
|
|
||||||
if (!(cardRef.current))
|
|
||||||
return
|
|
||||||
|
|
||||||
cardRef.current.style.position = 'relative'
|
|
||||||
cardRef.current.style.zIndex = '9999'
|
|
||||||
}}
|
|
||||||
onLayoutAnimationComplete={() => {
|
|
||||||
if (!(cardRef.current))
|
|
||||||
return
|
|
||||||
|
|
||||||
cardRef.current.style.zIndex = ''
|
|
||||||
cardRef.current.style.position = ''
|
|
||||||
}}
|
|
||||||
transition={{ type: 'spring', stiffness: 500, damping: 40, mass: .5 }}>
|
|
||||||
<img src={post.thumbnail || post.thumbnailBase || undefined}
|
<img src={post.thumbnail || post.thumbnailBase || undefined}
|
||||||
alt={post.title || post.url}
|
alt={post.title || post.url}
|
||||||
title={post.title || post.url || undefined}
|
title={post.title || post.url || undefined}
|
||||||
loading={i < 12 ? 'eager' : 'lazy'}
|
loading={i < 12 ? 'eager' : 'lazy'}
|
||||||
decoding="async"
|
decoding="async"
|
||||||
className="object-cover w-full h-full"/>
|
className="object-cover w-full h-full"/>
|
||||||
</motion.div>
|
</Link>))}
|
||||||
</PrefetchLink>)
|
</div>)) satisfies FC<Props>
|
||||||
})}
|
|
||||||
</div>)
|
|
||||||
}) satisfies FC<Props>
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import DateTimeField from '@/components/common/DateTimeField'
|
import DateTimeField from '@/components/common/DateTimeField'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import { Button } from '@/components/ui/button'
|
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
@@ -17,8 +16,7 @@ export default (({ originalCreatedFrom,
|
|||||||
setOriginalCreatedBefore }: Props) => (
|
setOriginalCreatedBefore }: Props) => (
|
||||||
<div>
|
<div>
|
||||||
<Label>オリジナルの作成日時</Label>
|
<Label>オリジナルの作成日時</Label>
|
||||||
<div className="my-1 flex">
|
<div className="my-1">
|
||||||
<div className="w-80">
|
|
||||||
<DateTimeField
|
<DateTimeField
|
||||||
className="mr-2"
|
className="mr-2"
|
||||||
value={originalCreatedFrom ?? undefined}
|
value={originalCreatedFrom ?? undefined}
|
||||||
@@ -27,42 +25,25 @@ export default (({ originalCreatedFrom,
|
|||||||
const v = ev.target.value
|
const v = ev.target.value
|
||||||
if (!(v))
|
if (!(v))
|
||||||
return
|
return
|
||||||
|
|
||||||
const d = new Date (v)
|
const d = new Date (v)
|
||||||
|
if (d.getSeconds () === 0)
|
||||||
|
{
|
||||||
if (d.getMinutes () === 0 && d.getHours () === 0)
|
if (d.getMinutes () === 0 && d.getHours () === 0)
|
||||||
d.setDate (d.getDate () + 1)
|
d.setDate (d.getDate () + 1)
|
||||||
else
|
else
|
||||||
d.setMinutes (d.getMinutes () + 1)
|
d.setMinutes (d.getMinutes () + 1)
|
||||||
|
}
|
||||||
|
else
|
||||||
|
d.setSeconds (d.getSeconds () + 1)
|
||||||
setOriginalCreatedBefore (d.toISOString ())
|
setOriginalCreatedBefore (d.toISOString ())
|
||||||
}}/>
|
}}/>
|
||||||
以降
|
以降
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="my-1">
|
||||||
<Button
|
|
||||||
className="bg-gray-600 text-white rounded"
|
|
||||||
onClick={() => {
|
|
||||||
setOriginalCreatedFrom (null)
|
|
||||||
}}>
|
|
||||||
リセット
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="my-1 flex">
|
|
||||||
<div className="w-80">
|
|
||||||
<DateTimeField
|
<DateTimeField
|
||||||
className="mr-2"
|
className="mr-2"
|
||||||
value={originalCreatedBefore ?? undefined}
|
value={originalCreatedBefore ?? undefined}
|
||||||
onChange={setOriginalCreatedBefore}/>
|
onChange={setOriginalCreatedBefore}/>
|
||||||
より前
|
より前
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<Button
|
|
||||||
className="bg-gray-600 text-white rounded"
|
|
||||||
onClick={() => {
|
|
||||||
setOriginalCreatedBefore (null)
|
|
||||||
}}>
|
|
||||||
リセット
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>)) satisfies FC<Props>
|
</div>)) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,108 +0,0 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { forwardRef, useMemo } from 'react'
|
|
||||||
import { flushSync } from 'react-dom'
|
|
||||||
import { createPath, useNavigate } from 'react-router-dom'
|
|
||||||
|
|
||||||
import { useOverlayStore } from '@/components/RouteBlockerOverlay'
|
|
||||||
import { prefetchForURL } from '@/lib/prefetchers'
|
|
||||||
import { cn } from '@/lib/utils'
|
|
||||||
|
|
||||||
import type { AnchorHTMLAttributes, MouseEvent, TouchEvent } from 'react'
|
|
||||||
import type { To } from 'react-router-dom'
|
|
||||||
|
|
||||||
type Props = AnchorHTMLAttributes<HTMLAnchorElement> & {
|
|
||||||
to: To
|
|
||||||
state?: Record<string, string>
|
|
||||||
replace?: boolean
|
|
||||||
className?: string
|
|
||||||
cancelOnError?: boolean }
|
|
||||||
|
|
||||||
|
|
||||||
export default forwardRef<HTMLAnchorElement, Props> (({
|
|
||||||
to,
|
|
||||||
replace,
|
|
||||||
className,
|
|
||||||
state,
|
|
||||||
onMouseEnter,
|
|
||||||
onTouchStart,
|
|
||||||
onClick,
|
|
||||||
cancelOnError = false,
|
|
||||||
...rest }, ref) => {
|
|
||||||
if ('onClick' in rest)
|
|
||||||
delete rest['onClick']
|
|
||||||
|
|
||||||
const navigate = useNavigate ()
|
|
||||||
const qc = useQueryClient ()
|
|
||||||
const url = useMemo (() => {
|
|
||||||
const path = (typeof to === 'string') ? to : createPath (to)
|
|
||||||
return (new URL (path, location.origin)).toString ()
|
|
||||||
}, [to])
|
|
||||||
const setOverlay = useOverlayStore (s => s.setActive)
|
|
||||||
|
|
||||||
const doPrefetch = async () => {
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await prefetchForURL (qc, url)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
catch (e)
|
|
||||||
{
|
|
||||||
console.error ('データ取得エラー', e)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleMouseEnter = async (ev: MouseEvent<HTMLAnchorElement>) => {
|
|
||||||
onMouseEnter?.(ev)
|
|
||||||
await doPrefetch ()
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleTouchStart = async (ev: TouchEvent<HTMLAnchorElement>) => {
|
|
||||||
onTouchStart?.(ev)
|
|
||||||
await doPrefetch ()
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleClick = async (ev: MouseEvent<HTMLAnchorElement>) => {
|
|
||||||
try
|
|
||||||
{
|
|
||||||
onClick?.(ev)
|
|
||||||
|
|
||||||
if (ev.defaultPrevented
|
|
||||||
|| ev.metaKey
|
|
||||||
|| ev.ctrlKey
|
|
||||||
|| ev.shiftKey
|
|
||||||
|| ev.altKey
|
|
||||||
|| (rest.target && rest.target !== '_self'))
|
|
||||||
return
|
|
||||||
|
|
||||||
ev.preventDefault ()
|
|
||||||
|
|
||||||
flushSync (() => {
|
|
||||||
setOverlay (true)
|
|
||||||
})
|
|
||||||
const ok = await doPrefetch ()
|
|
||||||
flushSync (() => {
|
|
||||||
setOverlay (false)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!(ok) && cancelOnError)
|
|
||||||
return
|
|
||||||
|
|
||||||
navigate (to, { replace, ...(state && { state }) })
|
|
||||||
}
|
|
||||||
catch (ex)
|
|
||||||
{
|
|
||||||
console.log (ex)
|
|
||||||
ev.preventDefault ()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<a ref={ref}
|
|
||||||
href={typeof to === 'string' ? to : createPath (to)}
|
|
||||||
onMouseEnter={handleMouseEnter}
|
|
||||||
onTouchStart={handleTouchStart}
|
|
||||||
onClick={handleClick}
|
|
||||||
className={cn ('cursor-pointer', className)}
|
|
||||||
{...rest}/>)
|
|
||||||
})
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { useEffect } from 'react'
|
|
||||||
import { create } from 'zustand'
|
|
||||||
|
|
||||||
import type { FC } from 'react'
|
|
||||||
|
|
||||||
type OverlayStore = {
|
|
||||||
active: boolean
|
|
||||||
setActive: (v: boolean) => void }
|
|
||||||
|
|
||||||
|
|
||||||
export const useOverlayStore = create<OverlayStore> (set => ({
|
|
||||||
active: false,
|
|
||||||
setActive: v => set ({ active: v }) }))
|
|
||||||
|
|
||||||
|
|
||||||
export default (() => {
|
|
||||||
const active = useOverlayStore (s => s.active)
|
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (active)
|
|
||||||
{
|
|
||||||
document.body.style.overflow = 'hidden'
|
|
||||||
document.body.setAttribute ('aria-busy', 'true')
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
document.body.style.overflow = ''
|
|
||||||
document.body.removeAttribute ('aria-busy')
|
|
||||||
}
|
|
||||||
}, [active])
|
|
||||||
|
|
||||||
if (!(active))
|
|
||||||
return null
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
role="progressbar"
|
|
||||||
aria-label="Loading"
|
|
||||||
className="fixed inset-0 z-[9999] bg-black/50 backdrop-blur-sm pointer-events-auto">
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center">
|
|
||||||
<div className="rounded-2xl bg-black/60 text-white px-6 py-3 text-sm">
|
|
||||||
Loading...
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>)
|
|
||||||
}) satisfies FC
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { useLocation } from 'react-router-dom'
|
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
|
|
||||||
|
|
||||||
export default <T extends string,>({ by, label, currentOrder, defaultDirection }: {
|
|
||||||
by: T
|
|
||||||
label: string
|
|
||||||
currentOrder: `${ T }:${ 'asc' | 'desc' }`
|
|
||||||
defaultDirection: Record<T, 'asc' | 'desc'> }) => {
|
|
||||||
const [fld, dir] = currentOrder.split (':')
|
|
||||||
|
|
||||||
const location = useLocation ()
|
|
||||||
const qs = new URLSearchParams (location.search)
|
|
||||||
const nextDir =
|
|
||||||
(by === fld)
|
|
||||||
? (dir === 'asc' ? 'desc' : 'asc')
|
|
||||||
: (defaultDirection[by] || 'desc')
|
|
||||||
qs.set ('order', `${ by }:${ nextDir }`)
|
|
||||||
qs.set ('page', '1')
|
|
||||||
|
|
||||||
return (
|
|
||||||
<PrefetchLink
|
|
||||||
className="text-inherit visited:text-inherit hover:text-inherit"
|
|
||||||
to={`${ location.pathname }?${ qs.toString () }`}>
|
|
||||||
<span className="font-bold">
|
|
||||||
{label}
|
|
||||||
{by === fld && (dir === 'asc' ? ' ▲' : ' ▼')}
|
|
||||||
</span>
|
|
||||||
</PrefetchLink>)
|
|
||||||
}
|
|
||||||
@@ -1,30 +1,15 @@
|
|||||||
import { DndContext,
|
import { AnimatePresence, motion } from 'framer-motion'
|
||||||
DragOverlay,
|
import { useEffect, useState } from 'react'
|
||||||
MouseSensor,
|
import { Link } from 'react-router-dom'
|
||||||
TouchSensor,
|
|
||||||
useDroppable,
|
|
||||||
useSensor,
|
|
||||||
useSensors } from '@dnd-kit/core'
|
|
||||||
import { restrictToWindowEdges } from '@dnd-kit/modifiers'
|
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { motion } from 'framer-motion'
|
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
|
||||||
|
|
||||||
import DraggableDroppableTagRow from '@/components/DraggableDroppableTagRow'
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
import TagSearch from '@/components/TagSearch'
|
import TagSearch from '@/components/TagSearch'
|
||||||
import SectionTitle from '@/components/common/SectionTitle'
|
import SectionTitle from '@/components/common/SectionTitle'
|
||||||
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { CATEGORIES } from '@/consts'
|
||||||
import { CATEGORIES, CATEGORY_NAMES } from '@/consts'
|
|
||||||
import { apiDelete, apiGet, apiPatch, apiPost } from '@/lib/api'
|
|
||||||
import { postsKeys, tagsKeys } from '@/lib/queryKeys'
|
|
||||||
import { dateString, originalCreatedAtString } from '@/lib/utils'
|
|
||||||
|
|
||||||
import type { DragEndEvent } from '@dnd-kit/core'
|
import type { FC, ReactNode } from 'react'
|
||||||
import type { FC, MutableRefObject, ReactNode } from 'react'
|
|
||||||
|
|
||||||
import type { Category, Post, Tag } from '@/types'
|
import type { Category, Post, Tag } from '@/types'
|
||||||
|
|
||||||
@@ -35,128 +20,45 @@ const renderTagTree = (
|
|||||||
tag: Tag,
|
tag: Tag,
|
||||||
nestLevel: number,
|
nestLevel: number,
|
||||||
path: string,
|
path: string,
|
||||||
suppressClickRef: MutableRefObject<boolean>,
|
|
||||||
parentTagId?: number,
|
|
||||||
sp?: boolean,
|
|
||||||
): ReactNode[] => {
|
): ReactNode[] => {
|
||||||
const key = `${ path }-${ tag.id }`
|
const key = `${ path }-${ tag.id }`
|
||||||
|
|
||||||
const self = (
|
const self = (
|
||||||
<li key={key} className="mb-1">
|
<motion.li
|
||||||
<DraggableDroppableTagRow
|
key={key}
|
||||||
tag={tag}
|
layout
|
||||||
nestLevel={nestLevel}
|
transition={{ duration: .2, ease: 'easeOut' }}
|
||||||
pathKey={key}
|
className="mb-1">
|
||||||
parentTagId={parentTagId}
|
<TagLink tag={tag} nestLevel={nestLevel}/>
|
||||||
suppressClickRef={suppressClickRef}
|
</motion.li>)
|
||||||
sp={sp}/>
|
|
||||||
</li>)
|
|
||||||
|
|
||||||
return [
|
return [self,
|
||||||
self,
|
|
||||||
...((tag.children
|
...((tag.children
|
||||||
?.sort ((a, b) => a.name < b.name ? -1 : 1)
|
?.sort ((a, b) => a.name < b.name ? -1 : 1)
|
||||||
.flatMap (child =>
|
.flatMap (child => renderTagTree (child, nestLevel + 1, key)))
|
||||||
renderTagTree (child, nestLevel + 1, key, suppressClickRef, tag.id, sp)))
|
|
||||||
?? [])]
|
?? [])]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const isDescendant = (
|
type Props = { post: Post | null }
|
||||||
root: Tag,
|
|
||||||
targetId: number,
|
|
||||||
): boolean => {
|
|
||||||
if (!(root.children))
|
|
||||||
return false
|
|
||||||
|
|
||||||
for (const c of root.children)
|
|
||||||
{
|
|
||||||
if (c.id === targetId)
|
|
||||||
return true
|
|
||||||
if (isDescendant (c, targetId))
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const findTag = (
|
export default (({ post }: Props) => {
|
||||||
byCat: TagByCategory,
|
const [tags, setTags] = useState ({ } as TagByCategory)
|
||||||
id: number,
|
|
||||||
): Tag | undefined => {
|
|
||||||
const walk = (nodes: Tag[]): Tag | undefined => {
|
|
||||||
for (const t of nodes)
|
|
||||||
{
|
|
||||||
if (t.id === id)
|
|
||||||
return t
|
|
||||||
|
|
||||||
const found = t.children ? walk (t.children) : undefined
|
const categoryNames: Record<Category, string> = {
|
||||||
if (found)
|
deerjikist: 'ニジラー',
|
||||||
return found
|
meme: '原作・ネタ元・ミーム等',
|
||||||
}
|
character: 'キャラクター',
|
||||||
|
general: '一般',
|
||||||
|
material: '素材',
|
||||||
|
meta: 'メタタグ',
|
||||||
|
nico: 'ニコニコタグ' }
|
||||||
|
|
||||||
return undefined
|
useEffect (() => {
|
||||||
}
|
if (!(post))
|
||||||
|
return
|
||||||
|
|
||||||
for (const cat of Object.keys (byCat) as (keyof typeof byCat)[])
|
|
||||||
{
|
|
||||||
const found = walk (byCat[cat] ?? [])
|
|
||||||
if (found)
|
|
||||||
return found
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const buildTagByCategory = (post: Post): TagByCategory => {
|
|
||||||
const tagsTmp = { } as TagByCategory
|
|
||||||
|
|
||||||
for (const tag of post.tags)
|
|
||||||
{
|
|
||||||
if (!(tag.category in tagsTmp))
|
|
||||||
tagsTmp[tag.category] = []
|
|
||||||
|
|
||||||
tagsTmp[tag.category].push (tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const cat of Object.keys (tagsTmp) as (keyof typeof tagsTmp)[])
|
|
||||||
tagsTmp[cat].sort ((a, b) => a.name < b.name ? -1 : 1)
|
|
||||||
|
|
||||||
return tagsTmp
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const changeCategory = async (
|
|
||||||
tagId: number,
|
|
||||||
category: Category,
|
|
||||||
): Promise<void> => {
|
|
||||||
await apiPatch (`/tags/${ tagId }`, { category })
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const DropSlot = ({ cat }: { cat: Category }) => {
|
|
||||||
const { setNodeRef, isOver: over } = useDroppable ({
|
|
||||||
id: `slot:${ cat }`,
|
|
||||||
data: { kind: 'slot', cat } })
|
|
||||||
|
|
||||||
return (
|
|
||||||
<li ref={setNodeRef} className="h-1">
|
|
||||||
{over && <div className="h-0.5 w-full rounded bg-sky-400"/>}
|
|
||||||
</li>)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
type Props = { post: Post; sp?: boolean }
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ post, sp }: Props) => {
|
|
||||||
sp = Boolean (sp)
|
|
||||||
|
|
||||||
const qc = useQueryClient ()
|
|
||||||
|
|
||||||
const baseTags = useMemo<TagByCategory> (() => {
|
|
||||||
const tagsTmp = { } as TagByCategory
|
const tagsTmp = { } as TagByCategory
|
||||||
|
|
||||||
for (const tag of post.tags)
|
for (const tag of post.tags)
|
||||||
@@ -169,176 +71,41 @@ export default (({ post, sp }: Props) => {
|
|||||||
for (const cat of Object.keys (tagsTmp) as (keyof typeof tagsTmp)[])
|
for (const cat of Object.keys (tagsTmp) as (keyof typeof tagsTmp)[])
|
||||||
tagsTmp[cat].sort ((tagA: Tag, tagB: Tag) => tagA.name < tagB.name ? -1 : 1)
|
tagsTmp[cat].sort ((tagA: Tag, tagB: Tag) => tagA.name < tagB.name ? -1 : 1)
|
||||||
|
|
||||||
return tagsTmp
|
setTags (tagsTmp)
|
||||||
}, [post])
|
}, [post])
|
||||||
|
|
||||||
const [activeTagId, setActiveTagId] = useState<number | null> (null)
|
|
||||||
const [dragging, setDragging] = useState (false)
|
|
||||||
const [saving, setSaving] = useState (false)
|
|
||||||
const [tags, setTags] = useState (baseTags)
|
|
||||||
|
|
||||||
const suppressClickRef = useRef (false)
|
|
||||||
|
|
||||||
const sensors = useSensors (
|
|
||||||
useSensor (MouseSensor, { activationConstraint: { distance: 6 } }),
|
|
||||||
useSensor (TouchSensor, { activationConstraint: { delay: 250, tolerance: 8 } }))
|
|
||||||
|
|
||||||
const reloadTags = async (): Promise<void> => {
|
|
||||||
setTags (buildTagByCategory (await apiGet<Post> (`/posts/${ post.id }`)))
|
|
||||||
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
|
||||||
qc.invalidateQueries ({ queryKey: tagsKeys.root })
|
|
||||||
}
|
|
||||||
|
|
||||||
const onDragEnd = async (e: DragEndEvent) => {
|
|
||||||
if (saving)
|
|
||||||
return
|
|
||||||
|
|
||||||
const activeKind = e.active.data.current?.kind
|
|
||||||
if (activeKind !== 'tag')
|
|
||||||
return
|
|
||||||
|
|
||||||
const childId: number | undefined = e.active.data.current?.tagId
|
|
||||||
const fromParentId: number | undefined = e.active.data.current?.parentTagId
|
|
||||||
|
|
||||||
const overKind = e.over?.data.current?.kind
|
|
||||||
|
|
||||||
if (childId == null || !(overKind))
|
|
||||||
return
|
|
||||||
|
|
||||||
const child = findTag (tags, childId)
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
setSaving (true)
|
|
||||||
|
|
||||||
switch (overKind)
|
|
||||||
{
|
|
||||||
case 'tag':
|
|
||||||
{
|
|
||||||
const parentId: number | undefined = e.over?.data.current?.tagId
|
|
||||||
if (parentId == null || childId === parentId)
|
|
||||||
return
|
|
||||||
|
|
||||||
const parent = findTag (tags, parentId)
|
|
||||||
|
|
||||||
if (!(child)
|
|
||||||
|| !(parent)
|
|
||||||
|| isDescendant (child, parentId))
|
|
||||||
return
|
|
||||||
|
|
||||||
if (fromParentId != null)
|
|
||||||
await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
|
|
||||||
|
|
||||||
await apiPost (`/tags/${ parentId }/children/${ childId }`, { })
|
|
||||||
|
|
||||||
await reloadTags ()
|
|
||||||
toast ({
|
|
||||||
title: '上位タグ対応追加',
|
|
||||||
description: `《${ child?.name }》を《${ parent?.name }》の子タグに設定しました.` })
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'slot':
|
|
||||||
{
|
|
||||||
const cat: Category | undefined = e.over?.data.current?.cat
|
|
||||||
if (!(cat) || !(child))
|
|
||||||
return
|
|
||||||
|
|
||||||
if (child.category !== cat)
|
|
||||||
await changeCategory (childId, cat)
|
|
||||||
|
|
||||||
if (fromParentId != null)
|
|
||||||
await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
|
|
||||||
|
|
||||||
const fromParent = fromParentId == null ? null : findTag (tags, fromParentId)
|
|
||||||
|
|
||||||
await reloadTags ()
|
|
||||||
toast ({
|
|
||||||
title: '上位タグ対応解除',
|
|
||||||
description: (
|
|
||||||
fromParent
|
|
||||||
? `《${ child.name }》を《${ fromParent.name }》の子タグから外しました.`
|
|
||||||
: `《${ child.name }》のカテゴリを変更しました.`) })
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
toast ({ title: '上位タグ対応失敗', description: '独裁者である必要があります.' })
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
setSaving (false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
setTags (baseTags)
|
|
||||||
}, [baseTags])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarComponent>
|
<SidebarComponent>
|
||||||
<TagSearch/>
|
<TagSearch/>
|
||||||
<DndContext
|
<motion.div key={post?.id ?? 0} layout>
|
||||||
sensors={sensors}
|
{CATEGORIES.map ((cat: Category) => cat in tags && (
|
||||||
onDragStart={e => {
|
<motion.div layout className="my-3" key={cat}>
|
||||||
if (e.active.data.current?.kind === 'tag')
|
<SubsectionTitle>{categoryNames[cat]}</SubsectionTitle>
|
||||||
setActiveTagId (e.active.data.current?.tagId ?? null)
|
|
||||||
setDragging (true)
|
|
||||||
suppressClickRef.current = true
|
|
||||||
document.body.style.userSelect = 'none'
|
|
||||||
getSelection?.()?.removeAllRanges?.()
|
|
||||||
addEventListener ('click', e => {
|
|
||||||
e.preventDefault ()
|
|
||||||
e.stopPropagation ()
|
|
||||||
suppressClickRef.current = false
|
|
||||||
}, { capture: true, once: true })
|
|
||||||
}}
|
|
||||||
onDragCancel={() => {
|
|
||||||
setActiveTagId (null)
|
|
||||||
setDragging (false)
|
|
||||||
document.body.style.userSelect = ''
|
|
||||||
suppressClickRef.current = false
|
|
||||||
}}
|
|
||||||
onDragEnd={async e => {
|
|
||||||
setActiveTagId (null)
|
|
||||||
setDragging (false)
|
|
||||||
await onDragEnd (e)
|
|
||||||
document.body.style.userSelect = ''
|
|
||||||
}}
|
|
||||||
modifiers={[restrictToWindowEdges]}>
|
|
||||||
{CATEGORIES.map ((cat: Category) => ((tags[cat] ?? []).length > 0 || dragging) && (
|
|
||||||
<div className="my-3" key={cat}>
|
|
||||||
<SubsectionTitle>
|
|
||||||
<motion.div layoutId={`tag-${ sp ? 'sp-' : '' }${ cat }`}>
|
|
||||||
{CATEGORY_NAMES[cat]}
|
|
||||||
</motion.div>
|
|
||||||
</SubsectionTitle>
|
|
||||||
|
|
||||||
<ul>
|
<motion.ul layout>
|
||||||
{(tags[cat] ?? []).flatMap (tag => (
|
<AnimatePresence initial={false}>
|
||||||
renderTagTree (tag, 0, `cat-${ cat }`, suppressClickRef, undefined, sp)))}
|
{tags[cat].map (tag => renderTagTree (tag, 0, `cat-${ cat }`))}
|
||||||
<DropSlot cat={cat}/>
|
</AnimatePresence>
|
||||||
</ul>
|
</motion.ul>
|
||||||
</div>))}
|
</motion.div>))}
|
||||||
{post && (
|
{post && (
|
||||||
<motion.div layoutId={`post-info-${ sp }`}>
|
<div>
|
||||||
<SectionTitle>情報</SectionTitle>
|
<SectionTitle>情報</SectionTitle>
|
||||||
<ul>
|
<ul>
|
||||||
<li>Id.: {post.id}</li>
|
<li>Id.: {post.id}</li>
|
||||||
|
{/* TODO: uploadedUser の取得を対応したらコメント外す */}
|
||||||
|
{/*
|
||||||
<li>
|
<li>
|
||||||
<>耕作者: </>
|
<>耕作者: </>
|
||||||
{post.uploadedUser
|
{post.uploadedUser
|
||||||
? (
|
? (
|
||||||
<PrefetchLink to={`/users/${ post.uploadedUser.id }`}>
|
<Link to={`/users/${ post.uploadedUser.id }`}>
|
||||||
{post.uploadedUser.name || '名もなきニジラー'}
|
{post.uploadedUser.name || '名もなきニジラー'}
|
||||||
</PrefetchLink>)
|
</Link>)
|
||||||
: 'bot操作'}
|
: 'bot操作'}
|
||||||
</li>
|
</li>
|
||||||
<li>耕作日時: {dateString (post.createdAt)}</li>
|
*/}
|
||||||
|
<li>耕作日時: {(new Date (post.createdAt)).toLocaleString ()}</li>
|
||||||
<li>
|
<li>
|
||||||
<>リンク: </>
|
<>リンク: </>
|
||||||
<a
|
<a
|
||||||
@@ -350,26 +117,23 @@ export default (({ post, sp }: Props) => {
|
|||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
|
{/* TODO: 表示形式きしょすぎるので何とかする */}
|
||||||
<>オリジナルの投稿日時: </>
|
<>オリジナルの投稿日時: </>
|
||||||
{originalCreatedAtString (post.originalCreatedFrom,
|
{!(post.originalCreatedFrom) && !(post.originalCreatedBefore)
|
||||||
post.originalCreatedBefore)}
|
? '不明'
|
||||||
|
: (
|
||||||
|
<>
|
||||||
|
{post.originalCreatedFrom
|
||||||
|
&& `${ (new Date (post.originalCreatedFrom)).toLocaleString () } 以降 `}
|
||||||
|
{post.originalCreatedBefore
|
||||||
|
&& `${ (new Date (post.originalCreatedBefore)).toLocaleString () } より前`}
|
||||||
|
</>)}
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<PrefetchLink to={`/posts/changes?id=${ post.id }`}>
|
<Link to={`/posts/changes?id=${ post.id }`}>履歴</Link>
|
||||||
履歴
|
|
||||||
</PrefetchLink>
|
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</motion.div>)}
|
</div>)}
|
||||||
|
</motion.div>
|
||||||
<DragOverlay adjustScale={false}>
|
|
||||||
<div className="pointer-events-none">
|
|
||||||
{activeTagId != null && (() => {
|
|
||||||
const tag = findTag (tags, activeTagId)
|
|
||||||
return tag && <TagLink tag={tag}/>
|
|
||||||
}) ()}
|
|
||||||
</div>
|
|
||||||
</DragOverlay>
|
|
||||||
</DndContext>
|
|
||||||
</SidebarComponent>)
|
</SidebarComponent>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,34 +1,27 @@
|
|||||||
|
import axios from 'axios'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
import { API_BASE_URL } from '@/config'
|
||||||
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
|
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
|
||||||
import { apiGet } from '@/lib/api'
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { ComponentProps, FC, HTMLAttributes } from 'react'
|
import type { ComponentProps, FC, HTMLAttributes } from 'react'
|
||||||
|
|
||||||
import type { Tag } from '@/types'
|
import type { Tag } from '@/types'
|
||||||
|
|
||||||
type CommonProps = {
|
type CommonProps = { tag: Tag
|
||||||
tag: Tag
|
|
||||||
nestLevel?: number
|
nestLevel?: number
|
||||||
withWiki?: boolean
|
withWiki?: boolean
|
||||||
withCount?: boolean
|
withCount?: boolean }
|
||||||
prefetch?: boolean }
|
|
||||||
|
|
||||||
type PropsWithLink =
|
type PropsWithLink =
|
||||||
& CommonProps
|
CommonProps & { linkFlg?: true } & Partial<ComponentProps<typeof Link>>
|
||||||
& { linkFlg?: true }
|
|
||||||
& Partial<ComponentProps<typeof PrefetchLink>>
|
|
||||||
|
|
||||||
type PropsWithoutLink =
|
type PropsWithoutLink =
|
||||||
& CommonProps
|
CommonProps & { linkFlg: false } & Partial<HTMLAttributes<HTMLSpanElement>>
|
||||||
& { linkFlg: false }
|
|
||||||
& Partial<HTMLAttributes<HTMLSpanElement>>
|
|
||||||
|
|
||||||
type Props =
|
type Props = PropsWithLink | PropsWithoutLink
|
||||||
| PropsWithLink
|
|
||||||
| PropsWithoutLink
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ tag,
|
export default (({ tag,
|
||||||
@@ -36,22 +29,13 @@ export default (({ tag,
|
|||||||
linkFlg = true,
|
linkFlg = true,
|
||||||
withWiki = true,
|
withWiki = true,
|
||||||
withCount = true,
|
withCount = true,
|
||||||
prefetch = false,
|
|
||||||
...props }: Props) => {
|
...props }: Props) => {
|
||||||
const [havingWiki, setHavingWiki] = useState (true)
|
const [havingWiki, setHavingWiki] = useState (true)
|
||||||
|
|
||||||
const wikiExists = async (tag: Tag) => {
|
const wikiExists = async (tagName: string) => {
|
||||||
if ('hasWiki' in tag)
|
|
||||||
{
|
|
||||||
setHavingWiki (tag.hasWiki)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const tagName = (tag as Tag).name
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await apiGet (`/wiki/title/${ encodeURIComponent (tagName) }/exists`)
|
await axios.get (`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (tagName) }/exists`)
|
||||||
setHavingWiki (true)
|
setHavingWiki (true)
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
@@ -64,7 +48,7 @@ export default (({ tag,
|
|||||||
if (!(linkFlg) || !(withWiki))
|
if (!(linkFlg) || !(withWiki))
|
||||||
return
|
return
|
||||||
|
|
||||||
wikiExists (tag)
|
wikiExists (tag.name)
|
||||||
}, [tag.name, linkFlg, withWiki])
|
}, [tag.name, linkFlg, withWiki])
|
||||||
|
|
||||||
const spanClass = cn (
|
const spanClass = cn (
|
||||||
@@ -81,17 +65,17 @@ export default (({ tag,
|
|||||||
<span className="mr-1">
|
<span className="mr-1">
|
||||||
{havingWiki
|
{havingWiki
|
||||||
? (
|
? (
|
||||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||||
className={linkClass}>
|
className={linkClass}>
|
||||||
?
|
?
|
||||||
</PrefetchLink>)
|
</Link>)
|
||||||
: (
|
: (
|
||||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||||
className="animate-[wiki-blink_.25s_steps(2,end)_infinite]
|
className="animate-[wiki-blink_.25s_steps(2,end)_infinite]
|
||||||
dark:animate-[wiki-blink-dark_.25s_steps(2,end)_infinite]"
|
dark:animate-[wiki-blink-dark_.25s_steps(2,end)_infinite]"
|
||||||
title={`${ tag.name } Wiki が存在しません.`}>
|
title={`${ tag.name } Wiki が存在しません.`}>
|
||||||
!
|
!
|
||||||
</PrefetchLink>)}
|
</Link>)}
|
||||||
</span>)}
|
</span>)}
|
||||||
{nestLevel > 0 && (
|
{nestLevel > 0 && (
|
||||||
<span
|
<span
|
||||||
@@ -99,28 +83,13 @@ export default (({ tag,
|
|||||||
style={{ paddingLeft: `${ (nestLevel - 1) }rem` }}>
|
style={{ paddingLeft: `${ (nestLevel - 1) }rem` }}>
|
||||||
↳
|
↳
|
||||||
</span>)}
|
</span>)}
|
||||||
{tag.matchedAlias != null && (
|
|
||||||
<>
|
|
||||||
<span className={spanClass} {...props}>
|
|
||||||
{tag.matchedAlias}
|
|
||||||
</span>
|
|
||||||
<> → </>
|
|
||||||
</>)}
|
|
||||||
{linkFlg
|
{linkFlg
|
||||||
? (
|
? (
|
||||||
prefetch
|
<Link to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||||
? <PrefetchLink
|
|
||||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
|
||||||
className={linkClass}
|
className={linkClass}
|
||||||
{...props}>
|
{...props}>
|
||||||
{tag.name}
|
{tag.name}
|
||||||
</PrefetchLink>
|
</Link>)
|
||||||
: <PrefetchLink
|
|
||||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
|
||||||
className={linkClass}
|
|
||||||
{...props}>
|
|
||||||
{tag.name}
|
|
||||||
</PrefetchLink>)
|
|
||||||
: (
|
: (
|
||||||
<span className={spanClass}
|
<span className={spanClass}
|
||||||
{...props}>
|
{...props}>
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
// TODO: タグ入力系すべてに同様の処理あるため共通化する.
|
import axios from 'axios'
|
||||||
|
import React, { useEffect, useState } from 'react'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { useNavigate, useLocation } from 'react-router-dom'
|
import { useNavigate, useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
import { apiGet } from '@/lib/api'
|
import { API_BASE_URL } from '@/config'
|
||||||
|
|
||||||
import TagSearchBox from './TagSearchBox'
|
import TagSearchBox from './TagSearchBox'
|
||||||
|
|
||||||
import type { ChangeEvent, FC, KeyboardEvent } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { Tag } from '@/types'
|
import type { Tag } from '@/types'
|
||||||
|
|
||||||
@@ -21,7 +20,7 @@ export default (() => {
|
|||||||
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
||||||
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
||||||
|
|
||||||
const whenChanged = async (ev: ChangeEvent<HTMLInputElement>) => {
|
const whenChanged = async (ev: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setSearch (ev.target.value)
|
setSearch (ev.target.value)
|
||||||
|
|
||||||
const q = ev.target.value.trim ().split (' ').at (-1)
|
const q = ev.target.value.trim ().split (' ').at (-1)
|
||||||
@@ -31,13 +30,14 @@ export default (() => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q } })
|
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q } })
|
||||||
setSuggestions (data.filter (t => t.postCount > 0))
|
const data = res.data as Tag[]
|
||||||
|
setSuggestions (data)
|
||||||
if (suggestions.length > 0)
|
if (suggestions.length > 0)
|
||||||
setSuggestionsVsbl (true)
|
setSuggestionsVsbl (true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleKeyDown = (ev: KeyboardEvent<HTMLInputElement>) => {
|
const handleKeyDown = (ev: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
switch (ev.key)
|
switch (ev.key)
|
||||||
{
|
{
|
||||||
case 'ArrowDown':
|
case 'ArrowDown':
|
||||||
@@ -56,11 +56,8 @@ export default (() => {
|
|||||||
if (activeIndex < 0)
|
if (activeIndex < 0)
|
||||||
break
|
break
|
||||||
ev.preventDefault ()
|
ev.preventDefault ()
|
||||||
{
|
|
||||||
const selected = suggestions[activeIndex]
|
const selected = suggestions[activeIndex]
|
||||||
if (selected)
|
selected && handleTagSelect (selected)
|
||||||
handleTagSelect (selected)
|
|
||||||
}
|
|
||||||
break
|
break
|
||||||
|
|
||||||
case 'Escape':
|
case 'Escape':
|
||||||
@@ -70,25 +67,14 @@ export default (() => {
|
|||||||
}
|
}
|
||||||
if (ev.key === 'Enter' && (!(suggestionsVsbl) || activeIndex < 0))
|
if (ev.key === 'Enter' && (!(suggestionsVsbl) || activeIndex < 0))
|
||||||
{
|
{
|
||||||
const parts = search.split (' ')
|
navigate (`/posts?${ (new URLSearchParams ({ tags: search })).toString () }`)
|
||||||
const match = parts.map (t => t.toLowerCase ()).includes ('type:or') ? 'any' : 'all'
|
|
||||||
navigate (`/posts?${
|
|
||||||
(new URLSearchParams ({
|
|
||||||
tags: parts.map (t => t.toLowerCase ())
|
|
||||||
.filter (t => t !== 'type:or')
|
|
||||||
.join (' '),
|
|
||||||
match }))
|
|
||||||
.toString () }`)
|
|
||||||
setSuggestionsVsbl (false)
|
setSuggestionsVsbl (false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleTagSelect = (tag: Tag) => {
|
const handleTagSelect = (tag: Tag) => {
|
||||||
const parts = search.split (' ')
|
const parts = search.split (' ')
|
||||||
parts[parts.length - 1] = (
|
parts[parts.length - 1] = tag.name
|
||||||
(parts[parts.length - 1].slice(0, 4).toLowerCase () === 'not:')
|
|
||||||
? ('not:' + tag.name)
|
|
||||||
: tag.name)
|
|
||||||
setSearch (parts.join (' ') + ' ')
|
setSearch (parts.join (' ') + ' ')
|
||||||
setSuggestions ([])
|
setSuggestions ([])
|
||||||
setActiveIndex (-1)
|
setActiveIndex (-1)
|
||||||
@@ -96,8 +82,7 @@ export default (() => {
|
|||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
const query = new URLSearchParams (location.search)
|
const query = new URLSearchParams (location.search)
|
||||||
const anyFlg = query.get ('match') === 'any'
|
const tagsQuery = query.get ('tags') ?? ''
|
||||||
const tagsQuery = `${ query.get ('tags') ?? '' }${ anyFlg ? ' type:or' : '' }`
|
|
||||||
setSearch (tagsQuery)
|
setSearch (tagsQuery)
|
||||||
}, [location.search])
|
}, [location.search])
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import TagLink from '@/components/TagLink'
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
@@ -23,7 +22,8 @@ export default (({ suggestions, activeIndex, onSelect }: Props) => {
|
|||||||
className={cn ('px-3 py-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700',
|
className={cn ('px-3 py-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700',
|
||||||
i === activeIndex && 'bg-gray-300 dark:bg-gray-700')}
|
i === activeIndex && 'bg-gray-300 dark:bg-gray-700')}
|
||||||
onMouseDown={() => onSelect (tag)}>
|
onMouseDown={() => onSelect (tag)}>
|
||||||
<TagLink tag={tag} linkFlg={false} withWiki={false}/>
|
{tag.name}
|
||||||
|
{<span className="ml-2 text-sm text-gray-400">{tag.postCount}</span>}
|
||||||
</li>))}
|
</li>))}
|
||||||
</ul>)
|
</ul>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import axios from 'axios'
|
||||||
import { AnimatePresence, motion } from 'framer-motion'
|
import { AnimatePresence, motion } from 'framer-motion'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useLocation, useNavigate } from 'react-router-dom'
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
@@ -6,20 +7,19 @@ import TagLink from '@/components/TagLink'
|
|||||||
import TagSearch from '@/components/TagSearch'
|
import TagSearch from '@/components/TagSearch'
|
||||||
import SectionTitle from '@/components/common/SectionTitle'
|
import SectionTitle from '@/components/common/SectionTitle'
|
||||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||||
|
import { API_BASE_URL } from '@/config'
|
||||||
import { CATEGORIES } from '@/consts'
|
import { CATEGORIES } from '@/consts'
|
||||||
import { apiGet } from '@/lib/api'
|
|
||||||
|
|
||||||
import type { FC, MouseEvent } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { Post, Tag } from '@/types'
|
import type { Post, Tag } from '@/types'
|
||||||
|
|
||||||
type TagByCategory = Record<string, Tag[]>
|
type TagByCategory = Record<string, Tag[]>
|
||||||
|
|
||||||
type Props = { posts: Post[]
|
type Props = { posts: Post[] }
|
||||||
onClick?: (event: MouseEvent<HTMLElement>) => void }
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ posts, onClick }: Props) => {
|
export default (({ posts }: Props) => {
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
const [tagsVsbl, setTagsVsbl] = useState (false)
|
const [tagsVsbl, setTagsVsbl] = useState (false)
|
||||||
@@ -65,22 +65,21 @@ export default (({ posts, onClick }: Props) => {
|
|||||||
{CATEGORIES.flatMap (cat => cat in tags ? (
|
{CATEGORIES.flatMap (cat => cat in tags ? (
|
||||||
tags[cat].map (tag => (
|
tags[cat].map (tag => (
|
||||||
<li key={tag.id} className="mb-1">
|
<li key={tag.id} className="mb-1">
|
||||||
<motion.div layoutId={`tag-${ tag.id }`}>
|
<TagLink tag={tag}/>
|
||||||
<TagLink tag={tag} prefetch onClick={onClick}/>
|
|
||||||
</motion.div>
|
|
||||||
</li>))) : [])}
|
</li>))) : [])}
|
||||||
</ul>
|
</ul>
|
||||||
<SectionTitle>関聯</SectionTitle>
|
<SectionTitle>関聯</SectionTitle>
|
||||||
|
{posts.length > 0 && (
|
||||||
<a href="#"
|
<a href="#"
|
||||||
onClick={ev => {
|
onClick={ev => {
|
||||||
ev.preventDefault ()
|
ev.preventDefault ()
|
||||||
void ((async () => {
|
void ((async () => {
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await apiGet<Post> ('/posts/random',
|
const { data } = await axios.get (`${ API_BASE_URL }/posts/random`,
|
||||||
{ params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '),
|
{ params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '),
|
||||||
match: (anyFlg ? 'any' : 'all') } })
|
match: (anyFlg ? 'any' : 'all') } })
|
||||||
navigate (`/posts/${ data.id }`)
|
navigate (`/posts/${ (data as Post).id }`)
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -89,7 +88,7 @@ export default (({ posts, onClick }: Props) => {
|
|||||||
}) ())
|
}) ())
|
||||||
}}>
|
}}>
|
||||||
ランダム
|
ランダム
|
||||||
</a>
|
</a>)}
|
||||||
</>)
|
</>)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -97,19 +96,23 @@ export default (({ posts, onClick }: Props) => {
|
|||||||
<TagSearch/>
|
<TagSearch/>
|
||||||
|
|
||||||
<div className="hidden md:block mt-4">
|
<div className="hidden md:block mt-4">
|
||||||
{posts.length > 0 && TagBlock}
|
{TagBlock}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<AnimatePresence initial={false}>
|
<AnimatePresence initial={false}>
|
||||||
{tagsVsbl && (
|
{tagsVsbl && (
|
||||||
<motion.div
|
<motion.div
|
||||||
key="sptags"
|
key="sptags"
|
||||||
className="md:hidden overflow-hidden"
|
className="md:hidden mt-4"
|
||||||
initial={{ height: 0 }}
|
variants={{ hidden: { clipPath: 'inset(0 0 100% 0)',
|
||||||
animate={{ height: 'auto' }}
|
height: 0 },
|
||||||
exit={{ height: 0 }}
|
visible: { clipPath: 'inset(0 0 0% 0)',
|
||||||
|
height: 'auto'} }}
|
||||||
|
initial="hidden"
|
||||||
|
animate="visible"
|
||||||
|
exit="hidden"
|
||||||
transition={{ duration: .2, ease: 'easeOut' }}>
|
transition={{ duration: .2, ease: 'easeOut' }}>
|
||||||
{posts.length > 0 && TagBlock}
|
{TagBlock}
|
||||||
</motion.div>)}
|
</motion.div>)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,18 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import axios from 'axios'
|
||||||
|
import toCamel from 'camelcase-keys'
|
||||||
import { AnimatePresence, motion } from 'framer-motion'
|
import { AnimatePresence, motion } from 'framer-motion'
|
||||||
import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { Link, useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
import Separator from '@/components/MenuSeparator'
|
import Separator from '@/components/MenuSeparator'
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import TopNavUser from '@/components/TopNavUser'
|
import TopNavUser from '@/components/TopNavUser'
|
||||||
|
import { API_BASE_URL } from '@/config'
|
||||||
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
||||||
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
|
||||||
import { fetchTagByName } from '@/lib/tags'
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { fetchWikiPage } from '@/lib/wiki'
|
|
||||||
|
|
||||||
import type { FC, MouseEvent } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { Menu, User } from '@/types'
|
import type { Menu, Tag, User, WikiPage } from '@/types'
|
||||||
|
|
||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
@@ -46,44 +44,23 @@ export default (({ user }: Props) => {
|
|||||||
visible: false })
|
visible: false })
|
||||||
const [menuOpen, setMenuOpen] = useState (false)
|
const [menuOpen, setMenuOpen] = useState (false)
|
||||||
const [openItemIdx, setOpenItemIdx] = useState (-1)
|
const [openItemIdx, setOpenItemIdx] = useState (-1)
|
||||||
|
const [postCount, setPostCount] = useState<number | null> (null)
|
||||||
const [wikiId, setWikiId] = useState<number | null> (WikiIdBus.get ())
|
const [wikiId, setWikiId] = useState<number | null> (WikiIdBus.get ())
|
||||||
|
|
||||||
const wikiIdStr = String (wikiId ?? '')
|
|
||||||
|
|
||||||
const { data: wikiPage } = useQuery ({
|
|
||||||
enabled: Boolean (wikiIdStr),
|
|
||||||
queryKey: wikiKeys.show (wikiIdStr, { }),
|
|
||||||
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
|
|
||||||
|
|
||||||
const effectiveTitle = wikiPage?.title ?? ''
|
|
||||||
|
|
||||||
const { data: tag } = useQuery ({
|
|
||||||
enabled: Boolean (effectiveTitle),
|
|
||||||
queryKey: tagsKeys.show (effectiveTitle),
|
|
||||||
queryFn: () => fetchTagByName (effectiveTitle) })
|
|
||||||
|
|
||||||
const postCount = tag?.postCount ?? 0
|
|
||||||
|
|
||||||
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^\/]+/.test (location.pathname) && wikiId)
|
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^\/]+/.test (location.pathname) && wikiId)
|
||||||
const wikiTitle = location.pathname.split ('/')[2] ?? ''
|
const wikiTitle = location.pathname.split ('/')[2]
|
||||||
const menu: Menu = [
|
const menu: Menu = [
|
||||||
{ name: '広場', to: '/posts', subMenu: [
|
{ name: '広場', to: '/posts', subMenu: [
|
||||||
{ name: '一覧', to: '/posts' },
|
{ name: '一覧', to: '/posts' },
|
||||||
{ name: '検索', to: '/posts/search' },
|
|
||||||
{ name: '投稿追加', to: '/posts/new' },
|
{ name: '投稿追加', to: '/posts/new' },
|
||||||
{ name: '履歴', to: '/posts/changes' },
|
{ name: '耕作履歴', to: '/posts/changes' },
|
||||||
{ name: 'ヘルプ', to: '/wiki/ヘルプ:広場' }] },
|
{ name: 'ヘルプ', to: '/wiki/ヘルプ:広場' }] },
|
||||||
{ name: 'タグ', to: '/tags', subMenu: [
|
{ name: 'タグ', to: '/tags', subMenu: [
|
||||||
{ name: 'タグ一覧', to: '/tags', visible: true },
|
{ name: 'タグ一覧', to: '/tags', visible: false },
|
||||||
{ name: '別名タグ', to: '/tags/aliases', visible: false },
|
{ name: '別名タグ', to: '/tags/aliases', visible: false },
|
||||||
{ 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/ヘルプ:タグ' }] },
|
||||||
{ name: '上映会', to: '/theatres/1', base: '/theatres', subMenu: [
|
|
||||||
{ name: <>第 1 会場</>, to: '/theatres/1' },
|
|
||||||
{ name: 'CyTube', to: '//cytube.mm428.net/r/deernijika' },
|
|
||||||
{ name: <>ニジカ放送局第 1 チャンネル</>,
|
|
||||||
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' },
|
||||||
@@ -94,7 +71,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/settings', subMenu: [
|
{ name: 'ユーザ', to: '/users', 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) }] }]
|
||||||
@@ -136,20 +113,39 @@ export default (({ user }: Props) => {
|
|||||||
location.pathname.startsWith (item.base || item.to))))
|
location.pathname.startsWith (item.base || item.to))))
|
||||||
}, [location])
|
}, [location])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (!(wikiId))
|
||||||
|
return
|
||||||
|
|
||||||
|
const fetchPostCount = async () => {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const pageRes = await axios.get (`${ API_BASE_URL }/wiki/${ wikiId }`)
|
||||||
|
const wikiPage = toCamel (pageRes.data as any, { deep: true }) as WikiPage
|
||||||
|
|
||||||
|
const tagRes = await axios.get (`${ API_BASE_URL }/tags/name/${ wikiPage.title }`)
|
||||||
|
const tag = toCamel (tagRes.data as any, { deep: true }) as Tag
|
||||||
|
|
||||||
|
setPostCount (tag.postCount)
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
setPostCount (0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fetchPostCount ()
|
||||||
|
}, [wikiId])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<nav className="px-3 flex justify-between items-center w-full min-h-[48px]
|
<nav className="px-3 flex justify-between items-center w-full min-h-[48px]
|
||||||
bg-yellow-200 dark:bg-red-975 md:bg-yellow-50">
|
bg-yellow-200 dark:bg-red-975 md:bg-yellow-50">
|
||||||
<div className="flex items-center gap-2 h-full">
|
<div className="flex items-center gap-2 h-full">
|
||||||
<PrefetchLink
|
<Link to="/"
|
||||||
to="/posts"
|
|
||||||
className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400
|
className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400
|
||||||
dark:text-pink-300 dark:hover:text-pink-100"
|
dark:text-pink-300 dark:hover:text-pink-100">
|
||||||
onClick={() => {
|
|
||||||
scroll (0, 0)
|
|
||||||
}}>
|
|
||||||
ぼざクリ タグ広場
|
ぼざクリ タグ広場
|
||||||
</PrefetchLink>
|
</Link>
|
||||||
|
|
||||||
<div ref={navRef} className="relative hidden md:flex h-full items-center">
|
<div ref={navRef} className="relative hidden md:flex h-full items-center">
|
||||||
<div aria-hidden
|
<div aria-hidden
|
||||||
@@ -161,16 +157,15 @@ export default (({ user }: Props) => {
|
|||||||
opacity: hl.visible ? 1 : 0 }}/>
|
opacity: hl.visible ? 1 : 0 }}/>
|
||||||
|
|
||||||
{menu.map ((item, i) => (
|
{menu.map ((item, i) => (
|
||||||
<PrefetchLink
|
<Link key={i}
|
||||||
key={i}
|
|
||||||
to={item.to}
|
to={item.to}
|
||||||
ref={(el: (HTMLAnchorElement | null)) => {
|
ref={el => {
|
||||||
itemsRef.current[i] = el
|
itemsRef.current[i] = el
|
||||||
}}
|
}}
|
||||||
className={cn ('relative z-10 flex h-full items-center px-5',
|
className={cn ('relative z-10 flex h-full items-center px-5',
|
||||||
(i === openItemIdx) && 'font-bold')}>
|
(i === openItemIdx) && 'font-bold')}>
|
||||||
{item.name}
|
{item.name}
|
||||||
</PrefetchLink>))}
|
</Link>))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -208,13 +203,11 @@ export default (({ user }: Props) => {
|
|||||||
'component' in item
|
'component' in item
|
||||||
? <Fragment key={`c-${ i }`}>{item.component}</Fragment>
|
? <Fragment key={`c-${ i }`}>{item.component}</Fragment>
|
||||||
: (
|
: (
|
||||||
<PrefetchLink
|
<Link key={`l-${ i }`}
|
||||||
key={`l-${ i }`}
|
|
||||||
to={item.to}
|
to={item.to}
|
||||||
target={item.to.slice (0, 2) === '//' ? '_blank' : undefined}
|
|
||||||
className="h-full flex items-center px-3">
|
className="h-full flex items-center px-3">
|
||||||
{item.name}
|
{item.name}
|
||||||
</PrefetchLink>)))}
|
</Link>)))}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
</div>
|
</div>
|
||||||
@@ -236,12 +229,11 @@ export default (({ user }: Props) => {
|
|||||||
<Separator/>
|
<Separator/>
|
||||||
{menu.map ((item, i) => (
|
{menu.map ((item, i) => (
|
||||||
<Fragment key={i}>
|
<Fragment key={i}>
|
||||||
<PrefetchLink
|
<Link to={i === openItemIdx ? item.to : '#'}
|
||||||
to={i === openItemIdx ? item.to : '#'}
|
|
||||||
className={cn ('w-full min-h-[40px] flex items-center pl-8',
|
className={cn ('w-full min-h-[40px] flex items-center pl-8',
|
||||||
((i === openItemIdx)
|
((i === openItemIdx)
|
||||||
&& 'font-bold bg-yellow-50 dark:bg-red-950'))}
|
&& 'font-bold bg-yellow-50 dark:bg-red-950'))}
|
||||||
onClick={(ev: MouseEvent<HTMLAnchorElement>) => {
|
onClick={ev => {
|
||||||
if (i !== openItemIdx)
|
if (i !== openItemIdx)
|
||||||
{
|
{
|
||||||
ev.preventDefault ()
|
ev.preventDefault ()
|
||||||
@@ -249,7 +241,7 @@ export default (({ user }: Props) => {
|
|||||||
}
|
}
|
||||||
}}>
|
}}>
|
||||||
{item.name}
|
{item.name}
|
||||||
</PrefetchLink>
|
</Link>
|
||||||
|
|
||||||
<AnimatePresence initial={false}>
|
<AnimatePresence initial={false}>
|
||||||
{i === openItemIdx && (
|
{i === openItemIdx && (
|
||||||
@@ -275,15 +267,11 @@ export default (({ user }: Props) => {
|
|||||||
{subItem.component}
|
{subItem.component}
|
||||||
</Fragment>)
|
</Fragment>)
|
||||||
: (
|
: (
|
||||||
<PrefetchLink
|
<Link key={`sp-l-${ i }-${ j }`}
|
||||||
key={`sp-l-${ i }-${ j }`}
|
|
||||||
to={subItem.to}
|
to={subItem.to}
|
||||||
target={subItem.to.slice (0, 2) === '//'
|
|
||||||
? '_blank'
|
|
||||||
: undefined}
|
|
||||||
className="w-full min-h-[36px] flex items-center pl-12">
|
className="w-full min-h-[36px] flex items-center pl-12">
|
||||||
{subItem.name}
|
{subItem.name}
|
||||||
</PrefetchLink>)))}
|
</Link>)))}
|
||||||
</motion.div>)}
|
</motion.div>)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
</Fragment>))}
|
</Fragment>))}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
|
||||||
import Separator from '@/components/MenuSeparator'
|
import Separator from '@/components/MenuSeparator'
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
@@ -23,9 +24,9 @@ export default (({ user, sp }: Props) => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{sp && <Separator/>}
|
{sp && <Separator/>}
|
||||||
<PrefetchLink to="/users/settings"
|
<Link to="/users/settings"
|
||||||
className={className}>
|
className={className}>
|
||||||
{user.name || '名もなきニジラー'}
|
{user.name || '名もなきニジラー'}
|
||||||
</PrefetchLink>
|
</Link>
|
||||||
</>)
|
</>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import axios from 'axios'
|
||||||
import { useMemo } from 'react'
|
import toCamel from 'camelcase-keys'
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import ReactMarkdown from 'react-markdown'
|
import ReactMarkdown from 'react-markdown'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
import remarkGFM from 'remark-gfm'
|
import remarkGFM from 'remark-gfm'
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import SectionTitle from '@/components/common/SectionTitle'
|
import SectionTitle from '@/components/common/SectionTitle'
|
||||||
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||||
import { wikiKeys } from '@/lib/queryKeys'
|
import { API_BASE_URL } from '@/config'
|
||||||
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
||||||
import { fetchWikiPages } from '@/lib/wiki'
|
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
import type { Components } from 'react-markdown'
|
import type { Components } from 'react-markdown'
|
||||||
|
|
||||||
|
import type { WikiPage } from '@/types'
|
||||||
|
|
||||||
type Props = { title: string
|
type Props = { title: string
|
||||||
body?: string }
|
body?: string }
|
||||||
|
|
||||||
@@ -22,7 +24,7 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
|
|||||||
ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>,
|
ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>,
|
||||||
a: (({ href, children }) => (
|
a: (({ href, children }) => (
|
||||||
['/', '.'].some (e => href?.startsWith (e))
|
['/', '.'].some (e => href?.startsWith (e))
|
||||||
? <PrefetchLink to={href!}>{children}</PrefetchLink>
|
? <Link to={href!}>{children}</Link>
|
||||||
: (
|
: (
|
||||||
<a href={href}
|
<a href={href}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
@@ -32,15 +34,26 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
|
|||||||
|
|
||||||
|
|
||||||
export default (({ title, body }: Props) => {
|
export default (({ title, body }: Props) => {
|
||||||
const { data } = useQuery ({
|
const [pageNames, setPageNames] = useState<string[]> ([])
|
||||||
enabled: Boolean (body),
|
|
||||||
queryKey: wikiKeys.index ({ }),
|
|
||||||
queryFn: () => fetchWikiPages ({ }) })
|
|
||||||
const pageNames = (data ?? []).map (page => page.title).sort ((a, b) => b.length - a.length)
|
|
||||||
|
|
||||||
const remarkPlugins = useMemo (
|
const remarkPlugins = useMemo (
|
||||||
() => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])
|
() => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
void (async () => {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const res = await axios.get (`${ API_BASE_URL }/wiki`)
|
||||||
|
const data: WikiPage[] = toCamel (res.data as any, { deep: true })
|
||||||
|
setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length))
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
setPageNames ([])
|
||||||
|
}
|
||||||
|
}) ()
|
||||||
|
}, [])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
|
<ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
|
||||||
{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { cn } from '@/lib/utils'
|
|||||||
import type { FC, FocusEvent } from 'react'
|
import type { FC, FocusEvent } from 'react'
|
||||||
|
|
||||||
|
|
||||||
const pad = (n: number): string => n.toString ().padStart (2, '0')
|
const pad = (n: number) => n.toString ().padStart (2, '0')
|
||||||
|
|
||||||
|
|
||||||
const toDateTimeLocalValue = (d: Date) => {
|
const toDateTimeLocalValue = (d: Date) => {
|
||||||
@@ -14,7 +14,8 @@ const toDateTimeLocalValue = (d: Date) => {
|
|||||||
const day = pad (d.getDate ())
|
const day = pad (d.getDate ())
|
||||||
const h = pad (d.getHours ())
|
const h = pad (d.getHours ())
|
||||||
const min = pad (d.getMinutes ())
|
const min = pad (d.getMinutes ())
|
||||||
return `${ y }-${ m }-${ day }T${ h }:${ min }:00`
|
const s = pad (d.getSeconds ())
|
||||||
|
return `${ y }-${ m }-${ day }T${ h }:${ min }:${ s }`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -36,6 +37,7 @@ export default (({ value, onChange, className, onBlur }: Props) => {
|
|||||||
<input
|
<input
|
||||||
className={cn ('border rounded p-2', className)}
|
className={cn ('border rounded p-2', className)}
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
|
step={1}
|
||||||
value={local}
|
value={local}
|
||||||
onChange={ev => {
|
onChange={ev => {
|
||||||
const v = ev.target.value
|
const v = ev.target.value
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import { useLocation } from 'react-router-dom'
|
import { Link, useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
@@ -48,7 +46,7 @@ const getPages = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default (({ page, totalPages, siblingCount = 3 }) => {
|
export default (({ page, totalPages, siblingCount = 4 }) => {
|
||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
|
|
||||||
const buildTo = (p: number) => {
|
const buildTo = (p: number) => {
|
||||||
@@ -63,65 +61,19 @@ export default (({ page, totalPages, siblingCount = 3 }) => {
|
|||||||
<nav className="mt-4 flex justify-center" aria-label="Pagination">
|
<nav className="mt-4 flex justify-center" aria-label="Pagination">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{(page > 1)
|
{(page > 1)
|
||||||
? (
|
? <Link to={buildTo (page - 1)} aria-label="前のページ"><</Link>
|
||||||
<>
|
: <span aria-hidden><</span>}
|
||||||
<PrefetchLink
|
|
||||||
className="md:hidden p-2"
|
|
||||||
to={buildTo (1)}
|
|
||||||
aria-label="最初のページ">
|
|
||||||
|<
|
|
||||||
</PrefetchLink>
|
|
||||||
<PrefetchLink
|
|
||||||
className="p-2"
|
|
||||||
to={buildTo (page - 1)}
|
|
||||||
aria-label="前のページ">
|
|
||||||
<
|
|
||||||
</PrefetchLink>
|
|
||||||
</>)
|
|
||||||
: (
|
|
||||||
<>
|
|
||||||
<span className="md:hidden p-2" aria-hidden>
|
|
||||||
|<
|
|
||||||
</span>
|
|
||||||
<span className="p-2" aria-hidden>
|
|
||||||
<
|
|
||||||
</span>
|
|
||||||
</>)}
|
|
||||||
|
|
||||||
{pages.map ((p, idx) => (
|
{pages.map ((p, idx) => (
|
||||||
(p === '…')
|
(p === '…')
|
||||||
? <span key={`dots-${ idx }`} className="hidden md:block p-2">…</span>
|
? <span key={`dots-${ idx }`}>…</span>
|
||||||
: ((p === page)
|
: ((p === page)
|
||||||
? <span key={p} className="font-bold p-2" aria-current="page">{p}</span>
|
? <span key={p} className="font-bold" aria-current="page">{p}</span>
|
||||||
: (
|
: <Link key={p} to={buildTo (p)}>{p}</Link>)))}
|
||||||
<PrefetchLink
|
|
||||||
key={p}
|
|
||||||
className="hidden md:block p-2"
|
|
||||||
to={buildTo (p)}>
|
|
||||||
{p}
|
|
||||||
</PrefetchLink>))))}
|
|
||||||
|
|
||||||
{(page < totalPages)
|
{(page < totalPages)
|
||||||
? (
|
? <Link to={buildTo (page + 1)} aria-label="次のページ">></Link>
|
||||||
<>
|
: <span aria-hidden>></span>}
|
||||||
<PrefetchLink
|
|
||||||
className="p-2"
|
|
||||||
to={buildTo (page + 1)}
|
|
||||||
aria-label="次のページ">
|
|
||||||
>
|
|
||||||
</PrefetchLink>
|
|
||||||
<PrefetchLink
|
|
||||||
className="md:hidden p-2"
|
|
||||||
to={buildTo (totalPages)}
|
|
||||||
aria-label="最後のページ">
|
|
||||||
>|
|
|
||||||
</PrefetchLink>
|
|
||||||
</>)
|
|
||||||
: (
|
|
||||||
<>
|
|
||||||
<span className="p-2" aria-hidden>></span>
|
|
||||||
<span className="md:hidden p-2" aria-hidden>>|</span>
|
|
||||||
</>)}
|
|
||||||
</div>
|
</div>
|
||||||
</nav>)
|
</nav>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
import { cn } from '@/lib/utils'
|
import React from 'react'
|
||||||
|
|
||||||
import type { FC, ReactNode } from 'react'
|
type Props = { children: React.ReactNode }
|
||||||
|
|
||||||
type Props = {
|
|
||||||
children: ReactNode
|
|
||||||
className?: string }
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ children, className }: Props) => (
|
export default ({ children }: Props) => (
|
||||||
<main className={cn ('flex-1 overflow-y-auto p-4', className)}>
|
<main className="flex-1 overflow-y-auto p-4">
|
||||||
{children}
|
{children}
|
||||||
</main>)) satisfies FC<Props>
|
</main>)
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import toCamel from 'camelcase-keys'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
@@ -6,7 +8,7 @@ import { Dialog,
|
|||||||
DialogTitle } from '@/components/ui/dialog'
|
DialogTitle } from '@/components/ui/dialog'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { apiPost } from '@/lib/api'
|
import { API_BASE_URL } from '@/config'
|
||||||
|
|
||||||
import type { User } from '@/types'
|
import type { User } from '@/types'
|
||||||
|
|
||||||
@@ -24,12 +26,12 @@ export default ({ visible, onVisibleChange, setUser }: Props) => {
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await apiPost<{ valid: boolean; user: User }> (
|
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code: inputCode })
|
||||||
'/users/verify', { code: inputCode })
|
const data = res.data as { valid: boolean; user: any }
|
||||||
if (data.valid)
|
if (data.valid)
|
||||||
{
|
{
|
||||||
localStorage.setItem ('user_code', inputCode)
|
localStorage.setItem ('user_code', inputCode)
|
||||||
setUser (data.user)
|
setUser (toCamel (data.user, { deep: true }))
|
||||||
toast ({ title: '引継ぎ成功!' })
|
toast ({ title: '引継ぎ成功!' })
|
||||||
onVisibleChange (false)
|
onVisibleChange (false)
|
||||||
}
|
}
|
||||||
|
|||||||
変更されたファイルが多すぎるため,一部のファイルは表示されません さらに表示
新しい課題から参照
ユーザをブロックする