Merge remote-tracking branch 'origin/main' into feature/111
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
--require spec_helper
|
||||||
@@ -46,6 +46,8 @@ group :development, :test do
|
|||||||
|
|
||||||
# Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/]
|
# Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/]
|
||||||
gem "rubocop-rails-omakase", require: false
|
gem "rubocop-rails-omakase", require: false
|
||||||
|
|
||||||
|
gem 'factory_bot_rails'
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
@@ -65,3 +67,5 @@ gem 'dotenv-rails'
|
|||||||
gem 'whenever', require: false
|
gem 'whenever', require: false
|
||||||
|
|
||||||
gem 'discard'
|
gem 'discard'
|
||||||
|
|
||||||
|
gem "rspec-rails", "~> 8.0", :groups => [:development, :test]
|
||||||
|
|||||||
@@ -99,6 +99,11 @@ GEM
|
|||||||
drb (2.2.1)
|
drb (2.2.1)
|
||||||
ed25519 (1.4.0)
|
ed25519 (1.4.0)
|
||||||
erubi (1.13.1)
|
erubi (1.13.1)
|
||||||
|
factory_bot (6.5.6)
|
||||||
|
activesupport (>= 6.1.0)
|
||||||
|
factory_bot_rails (6.5.1)
|
||||||
|
factory_bot (~> 6.5)
|
||||||
|
railties (>= 6.1.0)
|
||||||
ffi (1.17.2-aarch64-linux-gnu)
|
ffi (1.17.2-aarch64-linux-gnu)
|
||||||
ffi (1.17.2-aarch64-linux-musl)
|
ffi (1.17.2-aarch64-linux-musl)
|
||||||
ffi (1.17.2-arm-linux-gnu)
|
ffi (1.17.2-arm-linux-gnu)
|
||||||
@@ -298,6 +303,23 @@ GEM
|
|||||||
io-console (~> 0.5)
|
io-console (~> 0.5)
|
||||||
rexml (3.4.1)
|
rexml (3.4.1)
|
||||||
rouge (3.30.0)
|
rouge (3.30.0)
|
||||||
|
rspec-core (3.13.6)
|
||||||
|
rspec-support (~> 3.13.0)
|
||||||
|
rspec-expectations (3.13.5)
|
||||||
|
diff-lcs (>= 1.2.0, < 2.0)
|
||||||
|
rspec-support (~> 3.13.0)
|
||||||
|
rspec-mocks (3.13.7)
|
||||||
|
diff-lcs (>= 1.2.0, < 2.0)
|
||||||
|
rspec-support (~> 3.13.0)
|
||||||
|
rspec-rails (8.0.2)
|
||||||
|
actionpack (>= 7.2)
|
||||||
|
activesupport (>= 7.2)
|
||||||
|
railties (>= 7.2)
|
||||||
|
rspec-core (~> 3.13)
|
||||||
|
rspec-expectations (~> 3.13)
|
||||||
|
rspec-mocks (~> 3.13)
|
||||||
|
rspec-support (~> 3.13)
|
||||||
|
rspec-support (3.13.6)
|
||||||
rss (0.3.1)
|
rss (0.3.1)
|
||||||
rexml
|
rexml
|
||||||
rubocop (1.75.6)
|
rubocop (1.75.6)
|
||||||
@@ -424,6 +446,7 @@ DEPENDENCIES
|
|||||||
diff-lcs
|
diff-lcs
|
||||||
discard
|
discard
|
||||||
dotenv-rails
|
dotenv-rails
|
||||||
|
factory_bot_rails
|
||||||
gollum
|
gollum
|
||||||
image_processing (~> 1.14)
|
image_processing (~> 1.14)
|
||||||
jwt
|
jwt
|
||||||
@@ -433,6 +456,7 @@ DEPENDENCIES
|
|||||||
puma (>= 5.0)
|
puma (>= 5.0)
|
||||||
rack-cors
|
rack-cors
|
||||||
rails (~> 8.0.2)
|
rails (~> 8.0.2)
|
||||||
|
rspec-rails (~> 8.0)
|
||||||
rubocop-rails-omakase
|
rubocop-rails-omakase
|
||||||
sprockets-rails
|
sprockets-rails
|
||||||
sqlite3 (>= 2.1)
|
sqlite3 (>= 2.1)
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
class IpAddressesController < ApplicationController
|
|
||||||
def index
|
|
||||||
@ip_addresses = IpAddress.all
|
|
||||||
|
|
||||||
render json: @ip_addresses
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
render json: @ip_address
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
class NicoTagRelationController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
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.includes(:linked_tags).order(updated_at: :desc)
|
q = Tag.nico_tags
|
||||||
|
.includes(:tag_name, linked_tags: :tag_name)
|
||||||
|
.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)
|
tags = q.limit(limit + 1)
|
||||||
@@ -15,7 +19,9 @@ class NicoTagsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
render json: { tags: tags.map { |tag|
|
render json: { tags: tags.map { |tag|
|
||||||
tag.as_json(include: :linked_tags)
|
tag.as_json(TAG_JSON).merge(linked_tags: tag.linked_tags.map { |lt|
|
||||||
|
lt.as_json(TAG_JSON)
|
||||||
|
})
|
||||||
}, next_cursor: }
|
}, next_cursor: }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -30,12 +36,11 @@ class NicoTagsController < ApplicationController
|
|||||||
|
|
||||||
linked_tag_names = params[:tags].to_s.split(' ')
|
linked_tag_names = params[:tags].to_s.split(' ')
|
||||||
linked_tags = Tag.normalise_tags(linked_tag_names, with_tagme: false)
|
linked_tags = Tag.normalise_tags(linked_tag_names, with_tagme: false)
|
||||||
return head :bad_request if linked_tags.filter { |t| t.category == 'nico' }.present?
|
return head :bad_request if linked_tags.any? { |t| t.category == 'nico' }
|
||||||
|
|
||||||
tag.linked_tags = linked_tags
|
tag.linked_tags = linked_tags
|
||||||
tag.updated_at = Time.now
|
|
||||||
tag.save!
|
tag.save!
|
||||||
|
|
||||||
render json: tag.linked_tags, status: :ok
|
render json: tag.linked_tags.map { |t| t.as_json(TAG_JSON) }, status: :ok
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
class PostTagsController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
class PostsController < ApplicationController
|
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)
|
||||||
|
|
||||||
# GET /posts
|
|
||||||
def index
|
def index
|
||||||
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
|
||||||
@@ -18,7 +17,7 @@ class PostsController < ApplicationController
|
|||||||
'posts.created_at)'
|
'posts.created_at)'
|
||||||
q =
|
q =
|
||||||
filtered_posts
|
filtered_posts
|
||||||
.preload(:tags)
|
.preload(tags: :tag_name)
|
||||||
.with_attached_thumbnail
|
.with_attached_thumbnail
|
||||||
.select("posts.*, #{ sort_sql } AS sort_ts")
|
.select("posts.*, #{ sort_sql } AS sort_ts")
|
||||||
.order(Arel.sql("#{ sort_sql } DESC"))
|
.order(Arel.sql("#{ sort_sql } DESC"))
|
||||||
@@ -36,7 +35,8 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
render json: { posts: posts.map { |post|
|
render json: { posts: posts.map { |post|
|
||||||
post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }).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)
|
||||||
@@ -44,23 +44,27 @@ class PostsController < ApplicationController
|
|||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
}, count: filtered_posts.count(:id), next_cursor: }
|
}, 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.order('RAND()').first
|
post = filtered_posts.preload(tags: :tag_name).order('RAND()').first
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
|
|
||||||
viewed = current_user&.viewed?(post) || false
|
viewed = current_user&.viewed?(post) || false
|
||||||
|
|
||||||
render json: (post
|
render json: (post
|
||||||
.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } })
|
.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||||
|
methods: [:name] } })
|
||||||
.merge(viewed:))
|
.merge(viewed:))
|
||||||
end
|
end
|
||||||
|
|
||||||
# GET /posts/1
|
|
||||||
def show
|
def show
|
||||||
post = Post.includes(:tags).find(params[:id])
|
post = Post.includes(tags: :tag_name).find(params[:id])
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
|
|
||||||
viewed = current_user&.viewed?(post) || false
|
viewed = current_user&.viewed?(post) || false
|
||||||
@@ -73,7 +77,6 @@ class PostsController < ApplicationController
|
|||||||
render json:
|
render json:
|
||||||
end
|
end
|
||||||
|
|
||||||
# POST /posts
|
|
||||||
def create
|
def create
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.member?
|
return head :forbidden unless current_user.member?
|
||||||
@@ -81,7 +84,7 @@ class PostsController < ApplicationController
|
|||||||
# TODO: URL が正規のものがチェック,不正ならエラー
|
# TODO: URL が正規のものがチェック,不正ならエラー
|
||||||
# TODO: URL は必須にする(タイトルは省略可).
|
# TODO: URL は必須にする(タイトルは省略可).
|
||||||
# TODO: サイトに応じて thumbnail_base 設定
|
# TODO: サイトに応じて thumbnail_base 設定
|
||||||
title = params[:title]
|
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(' ')
|
||||||
@@ -96,7 +99,8 @@ 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, :name, :category, :post_count] } }),
|
render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||||
|
methods: [:name] } }),
|
||||||
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
|
||||||
@@ -117,12 +121,11 @@ class PostsController < ApplicationController
|
|||||||
head :no_content
|
head :no_content
|
||||||
end
|
end
|
||||||
|
|
||||||
# PATCH/PUT /posts/1
|
|
||||||
def update
|
def update
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.member?
|
return head :forbidden unless current_user.member?
|
||||||
|
|
||||||
title = params[:title]
|
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]
|
||||||
@@ -141,10 +144,6 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# DELETE /posts/1
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
|
|
||||||
def changes
|
def changes
|
||||||
id = params[:id]
|
id = params[:id]
|
||||||
page = (params[:page].presence || 1).to_i
|
page = (params[:page].presence || 1).to_i
|
||||||
@@ -157,13 +156,13 @@ 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.includes(:post, :tag, :created_user, :deleted_user)
|
pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
|
||||||
|
|
||||||
events = []
|
events = []
|
||||||
pts.each do |pt|
|
pts.each do |pt|
|
||||||
events << Event.new(
|
events << Event.new(
|
||||||
post: pt.post,
|
post: pt.post,
|
||||||
tag: pt.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)
|
||||||
@@ -171,7 +170,7 @@ class PostsController < ApplicationController
|
|||||||
if pt.discarded_at
|
if pt.discarded_at
|
||||||
events << Event.new(
|
events << Event.new(
|
||||||
post: pt.post,
|
post: pt.post,
|
||||||
tag: pt.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)
|
||||||
@@ -186,7 +185,7 @@ class PostsController < ApplicationController
|
|||||||
private
|
private
|
||||||
|
|
||||||
def filtered_posts
|
def filtered_posts
|
||||||
tag_names = params[:tags]&.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)
|
||||||
@@ -196,15 +195,15 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def filter_posts_by_tags tag_names, match_type
|
def filter_posts_by_tags tag_names, match_type
|
||||||
posts = Post.joins(:tags)
|
posts = Post.joins(tags: :tag_name)
|
||||||
|
|
||||||
if match_type == 'any'
|
if match_type == 'any'
|
||||||
posts = posts.where(tags: { name: tag_names }).distinct
|
posts.where(tag_names: { name: tag_names }).distinct
|
||||||
else
|
else
|
||||||
tag_names.each do |tag|
|
posts.where(tag_names: { name: tag_names })
|
||||||
posts = posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
|
.group('posts.id')
|
||||||
end
|
.having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
|
||||||
end
|
end
|
||||||
posts.distinct
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def sync_post_tags! post, desired_tags
|
def sync_post_tags! post, desired_tags
|
||||||
@@ -255,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 tag.as_json(only: [:id, :name, :category, :post_count]).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)
|
||||||
@@ -267,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] = tag.as_json(only: [:id, :name, :category, :post_count]).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,16 +0,0 @@
|
|||||||
class SettingsController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
class TagAliasesController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,46 +1,47 @@
|
|||||||
class TagsController < ApplicationController
|
class TagsController < ApplicationController
|
||||||
def index
|
def index
|
||||||
post_id = params[:post]
|
post_id = params[:post]
|
||||||
tags = if post_id.present?
|
|
||||||
Tag.joins(:posts).where(posts: { id: post_id })
|
tags =
|
||||||
else
|
if post_id.present?
|
||||||
Tag.all
|
Tag.joins(:posts).where(posts: { id: post_id })
|
||||||
end
|
else
|
||||||
render json: tags
|
Tag.all
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: tags.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
end
|
end
|
||||||
|
|
||||||
def autocomplete
|
def autocomplete
|
||||||
q = params[:q].to_s.strip
|
q = params[:q].to_s.strip
|
||||||
return render json: [] if q.blank?
|
return render json: [] if q.blank?
|
||||||
|
|
||||||
tags = (Tag
|
tags = (Tag.joins(:tag_name).includes(:tag_name)
|
||||||
.where('(category = ? AND name LIKE ?) OR name LIKE ?',
|
.where('(tags.category = ? AND tag_names.name LIKE ?) OR tag_names.name LIKE ?',
|
||||||
'nico', "nico:#{ q }%", "#{ q }%")
|
'nico', "nico:#{ q }%", "#{ q }%")
|
||||||
.order('post_count DESC, name ASC')
|
.order(Arel.sql('post_count DESC, tag_names.name ASC'))
|
||||||
.limit(20))
|
.limit(20))
|
||||||
render json: tags
|
render json: tags.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
tag = Tag.find(params[:id])
|
tag = Tag.find_by(id: params[:id])
|
||||||
render json: tag
|
|
||||||
end
|
|
||||||
|
|
||||||
def show_by_name
|
|
||||||
tag = Tag.find_by(name: params[:name])
|
|
||||||
if tag
|
if tag
|
||||||
render json: 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 create
|
def show_by_name
|
||||||
end
|
name = params[:name].to_s.strip
|
||||||
|
return head :bad_request if name.blank?
|
||||||
|
|
||||||
def update
|
tag = Tag.joins(:tag_name).includes(:tag_name).find_by(tag_names: { name: })
|
||||||
end
|
if tag
|
||||||
|
render json: tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||||
def destroy
|
else
|
||||||
|
head :not_found
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
class UserIpsController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
class UserPostViewsController < ApplicationController
|
|
||||||
def index
|
|
||||||
end
|
|
||||||
|
|
||||||
def show
|
|
||||||
end
|
|
||||||
|
|
||||||
def create
|
|
||||||
end
|
|
||||||
|
|
||||||
def update
|
|
||||||
end
|
|
||||||
|
|
||||||
def destroy
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -18,6 +18,8 @@ class UsersController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def renew
|
def renew
|
||||||
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
user = current_user
|
user = current_user
|
||||||
user.inheritance_code = SecureRandom.uuid
|
user.inheritance_code = SecureRandom.uuid
|
||||||
user.save!
|
user.save!
|
||||||
|
|||||||
@@ -2,19 +2,25 @@ 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
|
||||||
render json: WikiPage.all
|
pages = WikiPage.all
|
||||||
|
render json: pages.as_json(methods: [:title])
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
render_wiki_page_or_404 WikiPage.find(params[:id])
|
page = WikiPage.find_by(id: params[:id])
|
||||||
|
render_wiki_page_or_404 page
|
||||||
end
|
end
|
||||||
|
|
||||||
def show_by_title
|
def show_by_title
|
||||||
render_wiki_page_or_404 WikiPage.find_by(title: params[:title])
|
title = params[:title].to_s.strip
|
||||||
|
page = WikiPage.joins(:tag_name)
|
||||||
|
.includes(:tag_name)
|
||||||
|
.find_by(tag_names: { name: title })
|
||||||
|
render_wiki_page_or_404 page
|
||||||
end
|
end
|
||||||
|
|
||||||
def exists
|
def exists
|
||||||
if WikiPage.exists?(params[:id])
|
if WikiPage.exists?(id: params[:id])
|
||||||
head :no_content
|
head :no_content
|
||||||
else
|
else
|
||||||
head :not_found
|
head :not_found
|
||||||
@@ -22,7 +28,8 @@ class WikiPagesController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def exists_by_title
|
def exists_by_title
|
||||||
if WikiPage.exists?(title: params[:title])
|
title = params[:title].to_s.strip
|
||||||
|
if WikiPage.joins(:tag_name).exists?(tag_names: { name: title })
|
||||||
head :no_content
|
head :no_content
|
||||||
else
|
else
|
||||||
head :not_found
|
head :not_found
|
||||||
@@ -81,7 +88,7 @@ class WikiPagesController < ApplicationController
|
|||||||
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: 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
|
||||||
@@ -115,14 +122,14 @@ class WikiPagesController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def search
|
def search
|
||||||
title = params[:title]&.strip
|
title = params[:title].to_s.strip
|
||||||
|
|
||||||
q = WikiPage.all
|
q = WikiPage.joins(:tag_name).includes(:tag_name)
|
||||||
if title.present?
|
if title.present?
|
||||||
q = q.where('title LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
|
q = q.where('tag_names.name LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
|
||||||
end
|
end
|
||||||
|
|
||||||
render json: q.limit(20)
|
render json: q.limit(20).as_json(methods: [:title])
|
||||||
end
|
end
|
||||||
|
|
||||||
def changes
|
def changes
|
||||||
@@ -163,12 +170,14 @@ 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
|
||||||
|
|
||||||
return render json: page.as_json.merge(body:, revision_id:, pred:, succ:, updated_at:)
|
return render json: page.as_json(methods: [:title])
|
||||||
|
.merge(body:, revision_id:, pred:, succ:, updated_at:)
|
||||||
end
|
end
|
||||||
|
|
||||||
rev = page.current_revision
|
rev = page.current_revision
|
||||||
unless rev
|
unless rev
|
||||||
return render json: page.as_json.merge(body: nil, revision_id: nil, pred: nil, succ: nil)
|
return render json: page.as_json(methods: [:title])
|
||||||
|
.merge(body: nil, revision_id: nil, pred: nil, succ: nil)
|
||||||
end
|
end
|
||||||
|
|
||||||
if rev.redirect?
|
if rev.redirect?
|
||||||
@@ -183,7 +192,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: page.as_json.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 render_wiki_conflict err
|
def render_wiki_conflict err
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
class PostTag < ApplicationRecord
|
class PostTag < ApplicationRecord
|
||||||
include Discard::Model
|
include Discard::Model
|
||||||
|
|
||||||
|
before_destroy do
|
||||||
|
raise ActiveRecord::ReadOnlyRecord, '消さないでください.'
|
||||||
|
end
|
||||||
|
|
||||||
belongs_to :post
|
belongs_to :post
|
||||||
belongs_to :tag, counter_cache: :post_count
|
belongs_to :tag, counter_cache: :post_count
|
||||||
belongs_to :created_user, class_name: 'User', optional: true
|
belongs_to :created_user, class_name: 'User', optional: true
|
||||||
|
|||||||
+28
-13
@@ -21,6 +21,10 @@ class Tag < ApplicationRecord
|
|||||||
dependent: :destroy
|
dependent: :destroy
|
||||||
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
||||||
|
|
||||||
|
belongs_to :tag_name
|
||||||
|
delegate :name, to: :tag_name, allow_nil: true
|
||||||
|
validates :tag_name, presence: true
|
||||||
|
|
||||||
enum :category, { deerjikist: 'deerjikist',
|
enum :category, { deerjikist: 'deerjikist',
|
||||||
meme: 'meme',
|
meme: 'meme',
|
||||||
character: 'character',
|
character: 'character',
|
||||||
@@ -29,7 +33,6 @@ class Tag < ApplicationRecord
|
|||||||
nico: 'nico',
|
nico: 'nico',
|
||||||
meta: 'meta' }
|
meta: 'meta' }
|
||||||
|
|
||||||
validates :name, presence: true, length: { maximum: 255 }
|
|
||||||
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
|
||||||
@@ -44,31 +47,35 @@ class Tag < ApplicationRecord
|
|||||||
'mtr:' => 'material',
|
'mtr:' => 'material',
|
||||||
'meta:' => 'meta' }.freeze
|
'meta:' => 'meta' }.freeze
|
||||||
|
|
||||||
|
def name= val
|
||||||
|
(self.tag_name ||= build_tag_name).name = val
|
||||||
|
end
|
||||||
|
|
||||||
|
def has_wiki
|
||||||
|
tag_name&.wiki_page.present?
|
||||||
|
end
|
||||||
|
|
||||||
def self.tagme
|
def self.tagme
|
||||||
@tagme ||= Tag.find_or_create_by!(name: 'タグ希望') do |tag|
|
@tagme ||= find_or_create_by_tag_name!('タグ希望', category: 'meta')
|
||||||
tag.category = 'meta'
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.bot
|
def self.bot
|
||||||
@bot ||= Tag.find_or_create_by!(name: 'bot操作') do |tag|
|
@bot ||= find_or_create_by_tag_name!('bot操作', category: 'meta')
|
||||||
tag.category = 'meta'
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.normalise_tags tag_names, with_tagme: true
|
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.start_with?(p) } || ['', nil]
|
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.start_with?(p) } || ['', nil]
|
||||||
name.delete_prefix!(pf)
|
name.delete_prefix!(pf)
|
||||||
Tag.find_or_initialize_by(name:).tap do |tag|
|
find_or_create_by_tag_name!(name, category: (cat || 'general')).tap do |tag|
|
||||||
if cat && tag.category != cat
|
if cat && tag.category != cat
|
||||||
tag.category = cat
|
tag.update!(category: cat)
|
||||||
tag.save!
|
|
||||||
end
|
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.uniq
|
tags.uniq(&:id)
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.expand_parent_tags tags
|
def self.expand_parent_tags tags
|
||||||
@@ -94,11 +101,19 @@ 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:)
|
||||||
|
tn = TagName.find_or_create_by!(name: name.to_s.strip)
|
||||||
|
Tag.find_or_create_by!(tag_name_id: tn.id) do |t|
|
||||||
|
t.category = category
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def nico_tag_name_must_start_with_nico
|
def nico_tag_name_must_start_with_nico
|
||||||
if ((category == 'nico' && !(name.start_with?('nico:'))) ||
|
n = name.to_s
|
||||||
(category != 'nico' && name.start_with?('nico:')))
|
if ((category == 'nico' && !(n.start_with?('nico:'))) ||
|
||||||
|
(category != 'nico' && n.start_with?('nico:')))
|
||||||
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
|
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class TagName < ApplicationRecord
|
||||||
|
has_one :tag
|
||||||
|
has_one :wiki_page
|
||||||
|
|
||||||
|
belongs_to :canonical, class_name: 'TagName', optional: true
|
||||||
|
has_many :aliases, class_name: 'TagName', foreign_key: :canonical_id
|
||||||
|
|
||||||
|
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
|
||||||
|
end
|
||||||
@@ -11,7 +11,16 @@ class WikiPage < ApplicationRecord
|
|||||||
foreign_key: :redirect_page_id,
|
foreign_key: :redirect_page_id,
|
||||||
dependent: :nullify
|
dependent: :nullify
|
||||||
|
|
||||||
validates :title, presence: true, length: { maximum: 255 }, uniqueness: true
|
belongs_to :tag_name
|
||||||
|
validates :tag_name, presence: true
|
||||||
|
|
||||||
|
def title
|
||||||
|
tag_name.name
|
||||||
|
end
|
||||||
|
|
||||||
|
def title= val
|
||||||
|
(self.tag_name ||= build_tag_name).name = val
|
||||||
|
end
|
||||||
|
|
||||||
def current_revision
|
def current_revision
|
||||||
wiki_revisions.order(id: :desc).first
|
wiki_revisions.order(id: :desc).first
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ module Backend
|
|||||||
# Initialize configuration defaults for originally generated Rails version.
|
# Initialize configuration defaults for originally generated Rails version.
|
||||||
config.load_defaults 8.0
|
config.load_defaults 8.0
|
||||||
|
|
||||||
|
config.i18n.available_locales = [:ja, :en]
|
||||||
|
config.i18n.default_locale = :ja
|
||||||
|
|
||||||
# Please, add to the `ignore` list any other `lib` subdirectories that do
|
# Please, add to the `ignore` list any other `lib` subdirectories that do
|
||||||
# not contain `.rb` files, or that should not be reloaded or eager loaded.
|
# not contain `.rb` files, or that should not be reloaded or eager loaded.
|
||||||
# Common ones are `templates`, `generators`, or `middleware`, for example.
|
# Common ones are `templates`, `generators`, or `middleware`, for example.
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ja:
|
||||||
|
hello: 'ぬ゛〜゛ん゛'
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
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]
|
||||||
|
|
||||||
resources :tags do
|
resources :tags, only: [:index, :show] do
|
||||||
collection do
|
collection do
|
||||||
get :autocomplete
|
get :autocomplete
|
||||||
get 'name/:name', action: :show_by_name
|
get 'name/:name', action: :show_by_name
|
||||||
@@ -30,7 +30,7 @@ Rails.application.routes.draw do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
resources :posts do
|
resources :posts, only: [:index, :show, :create, :update] do
|
||||||
collection do
|
collection do
|
||||||
get :random
|
get :random
|
||||||
get :changes
|
get :changes
|
||||||
@@ -49,12 +49,4 @@ Rails.application.routes.draw do
|
|||||||
post 'code/renew', action: :renew
|
post 'code/renew', action: :renew
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
resources :ip_addresses
|
|
||||||
resources :nico_tag_relations
|
|
||||||
resources :post_tags
|
|
||||||
resources :settings
|
|
||||||
resources :tag_aliases
|
|
||||||
resources :user_ips
|
|
||||||
resources :user_post_views
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
class MakeTitleNullableInPosts < ActiveRecord::Migration[7.0]
|
||||||
|
def up
|
||||||
|
change_column_null :posts, :title, true
|
||||||
|
|
||||||
|
execute <<~SQL
|
||||||
|
UPDATE
|
||||||
|
posts
|
||||||
|
SET
|
||||||
|
title = NULL
|
||||||
|
WHERE
|
||||||
|
title = ''
|
||||||
|
SQL
|
||||||
|
end
|
||||||
|
|
||||||
|
def down
|
||||||
|
execute <<~SQL
|
||||||
|
UPDATE
|
||||||
|
posts
|
||||||
|
SET
|
||||||
|
title = ''
|
||||||
|
WHERE
|
||||||
|
title IS NULL
|
||||||
|
SQL
|
||||||
|
|
||||||
|
change_column_null :posts, :title, false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
class CreateTagNames < ActiveRecord::Migration[7.0]
|
||||||
|
def change
|
||||||
|
create_table :tag_names do |t|
|
||||||
|
t.string :name, limit: 255, null: false
|
||||||
|
t.references :canonical, null: true, foreign_key: { to_table: :tag_names }, index: true
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
add_index :tag_names, :name, unique: true
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
class AddTagNameToTags < ActiveRecord::Migration[7.0]
|
||||||
|
class Tag < ApplicationRecord
|
||||||
|
self.table_name = 'tags'
|
||||||
|
end
|
||||||
|
|
||||||
|
class TagName < ApplicationRecord
|
||||||
|
self.table_name = 'tag_names'
|
||||||
|
end
|
||||||
|
|
||||||
|
def up
|
||||||
|
add_reference :tags, :tag_name, null: true, foreign_key: true, index: false, after: :id
|
||||||
|
add_index :tags, :tag_name_id, unique: true
|
||||||
|
|
||||||
|
Tag.find_each do |tag|
|
||||||
|
name = tag.read_attribute(:name)
|
||||||
|
tn = TagName.find_or_create_by!(name:) do |r|
|
||||||
|
r.canonical_id = nil
|
||||||
|
end
|
||||||
|
tag.update_columns(tag_name_id: tn.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
change_column_null :tags, :tag_name_id, false
|
||||||
|
|
||||||
|
remove_column :tags, :name
|
||||||
|
end
|
||||||
|
|
||||||
|
def down
|
||||||
|
add_column :tags, :name, :string, limit: 255, null: true, after: :id
|
||||||
|
|
||||||
|
Tag.find_each do |tag|
|
||||||
|
tag_name_id = tag.read_attribute(:tag_name_id)
|
||||||
|
name = TagName.find(tag_name_id).read_attribute(:name)
|
||||||
|
tag.update_columns(name:)
|
||||||
|
end
|
||||||
|
|
||||||
|
change_column_null :tags, :name, false
|
||||||
|
|
||||||
|
remove_foreign_key :tags, column: :tag_name_id
|
||||||
|
remove_index :tags, :tag_name_id
|
||||||
|
remove_column :tags, :tag_name_id
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
class AddTagNameToWikiPages < ActiveRecord::Migration[7.0]
|
||||||
|
class WikiPage < ApplicationRecord
|
||||||
|
self.table_name = 'wiki_pages'
|
||||||
|
end
|
||||||
|
|
||||||
|
class TagName < ApplicationRecord
|
||||||
|
self.table_name = 'tag_names'
|
||||||
|
end
|
||||||
|
|
||||||
|
def up
|
||||||
|
add_reference :wiki_pages, :tag_name, null: true, foreign_key: true, index: false, after: :id
|
||||||
|
add_index :wiki_pages, :tag_name_id, unique: true
|
||||||
|
|
||||||
|
WikiPage.find_each do |page|
|
||||||
|
name = page.read_attribute(:title)
|
||||||
|
tn = TagName.find_or_create_by!(name:) do |r|
|
||||||
|
r.canonical_id = nil
|
||||||
|
end
|
||||||
|
page.update_columns(tag_name_id: tn.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
change_column_null :wiki_pages, :tag_name_id, false
|
||||||
|
|
||||||
|
remove_column :wiki_pages, :title
|
||||||
|
end
|
||||||
|
|
||||||
|
def down
|
||||||
|
add_column :wiki_pages, :title, :string, limit: 255, null: true, after: :id
|
||||||
|
|
||||||
|
WikiPage.find_each do |page|
|
||||||
|
tag_name_id = page.read_attribute(:tag_name_id)
|
||||||
|
title = TagName.find(tag_name_id).read_attribute(:name)
|
||||||
|
page.update_columns(title:)
|
||||||
|
end
|
||||||
|
|
||||||
|
change_column_null :wiki_pages, :title, false
|
||||||
|
|
||||||
|
remove_foreign_key :wiki_pages, column: :tag_name_id
|
||||||
|
remove_index :wiki_pages, :tag_name_id
|
||||||
|
remove_column :wiki_pages, :tag_name_id
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class DropTagAliases < ActiveRecord::Migration[7.0]
|
||||||
|
def up
|
||||||
|
drop_table :tag_aliases
|
||||||
|
end
|
||||||
|
|
||||||
|
def down
|
||||||
|
raise ActiveRecord::IrreversibleMigration, '戻せません.'
|
||||||
|
end
|
||||||
|
end
|
||||||
Generated
+18
-13
@@ -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: 2025_12_30_143400) 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
|
||||||
@@ -84,7 +84,7 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) do
|
|||||||
end
|
end
|
||||||
|
|
||||||
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", null: false
|
t.string "title"
|
||||||
t.string "url", limit: 2000, 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"
|
||||||
@@ -106,14 +106,6 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) do
|
|||||||
t.index ["user_id"], name: "index_settings_on_user_id"
|
t.index ["user_id"], name: "index_settings_on_user_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "tag_aliases", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
|
||||||
t.bigint "tag_id", null: false
|
|
||||||
t.string "name", null: false
|
|
||||||
t.datetime "created_at", null: false
|
|
||||||
t.datetime "updated_at", null: false
|
|
||||||
t.index ["tag_id"], name: "index_tag_aliases_on_tag_id"
|
|
||||||
end
|
|
||||||
|
|
||||||
create_table "tag_implications", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "tag_implications", 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 "parent_tag_id", null: false
|
t.bigint "parent_tag_id", null: false
|
||||||
@@ -124,6 +116,15 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) 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_names", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.string "name", null: false
|
||||||
|
t.bigint "canonical_id"
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["canonical_id"], name: "index_tag_names_on_canonical_id"
|
||||||
|
t.index ["name"], name: "index_tag_names_on_name", unique: true
|
||||||
|
end
|
||||||
|
|
||||||
create_table "tag_similarities", 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
|
||||||
@@ -133,11 +134,12 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) do
|
|||||||
end
|
end
|
||||||
|
|
||||||
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.bigint "tag_name_id", null: false
|
||||||
t.string "category", default: "general", null: false
|
t.string "category", default: "general", 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.integer "post_count", default: 0, null: false
|
t.integer "post_count", default: 0, null: false
|
||||||
|
t.index ["tag_name_id"], name: "index_tags_on_tag_name_id", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "user_ips", 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|
|
||||||
@@ -176,12 +178,13 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) do
|
|||||||
end
|
end
|
||||||
|
|
||||||
create_table "wiki_pages", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "wiki_pages", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "title", null: false
|
t.bigint "tag_name_id", null: false
|
||||||
t.bigint "created_user_id", null: false
|
t.bigint "created_user_id", null: false
|
||||||
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.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 ["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
|
||||||
|
|
||||||
@@ -228,15 +231,17 @@ ActiveRecord::Schema[8.0].define(version: 2025_12_30_143400) do
|
|||||||
add_foreign_key "posts", "posts", column: "parent_id"
|
add_foreign_key "posts", "posts", column: "parent_id"
|
||||||
add_foreign_key "posts", "users", column: "uploaded_user_id"
|
add_foreign_key "posts", "users", column: "uploaded_user_id"
|
||||||
add_foreign_key "settings", "users"
|
add_foreign_key "settings", "users"
|
||||||
add_foreign_key "tag_aliases", "tags"
|
|
||||||
add_foreign_key "tag_implications", "tags"
|
add_foreign_key "tag_implications", "tags"
|
||||||
add_foreign_key "tag_implications", "tags", column: "parent_tag_id"
|
add_foreign_key "tag_implications", "tags", column: "parent_tag_id"
|
||||||
|
add_foreign_key "tag_names", "tag_names", column: "canonical_id"
|
||||||
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 "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"
|
||||||
add_foreign_key "user_post_views", "users"
|
add_foreign_key "user_post_views", "users"
|
||||||
|
add_foreign_key "wiki_pages", "tag_names"
|
||||||
add_foreign_key "wiki_pages", "users", column: "created_user_id"
|
add_foreign_key "wiki_pages", "users", column: "created_user_id"
|
||||||
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
|
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
|
||||||
add_foreign_key "wiki_revision_lines", "wiki_lines"
|
add_foreign_key "wiki_revision_lines", "wiki_lines"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace :nico do
|
|||||||
require 'open3'
|
require 'open3'
|
||||||
require 'open-uri'
|
require 'open-uri'
|
||||||
require 'nokogiri'
|
require 'nokogiri'
|
||||||
|
require 'set'
|
||||||
|
|
||||||
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
|
||||||
@@ -12,9 +13,9 @@ 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
|
def sync_post_tags! post, desired_tag_ids, current_ids: nil
|
||||||
|
current_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||||
desired_ids = desired_tag_ids.compact.to_set
|
desired_ids = desired_tag_ids.compact.to_set
|
||||||
current_ids = post.tags.pluck(:id).to_set
|
|
||||||
|
|
||||||
to_add = desired_ids - current_ids
|
to_add = desired_ids - current_ids
|
||||||
to_remove = current_ids - desired_ids
|
to_remove = current_ids - desired_ids
|
||||||
@@ -43,12 +44,12 @@ namespace :nico do
|
|||||||
|
|
||||||
data = JSON.parse(stdout)
|
data = JSON.parse(stdout)
|
||||||
data.each do |datum|
|
data.each do |datum|
|
||||||
post = Post.where('url LIKE ?', '%nicovideo.jp%').find { |post|
|
code = datum['code']
|
||||||
post.url =~ %r{#{ Regexp.escape(datum['code']) }(?!\d)}
|
post = Post.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
||||||
}
|
.first
|
||||||
unless post
|
unless post
|
||||||
title = datum['title']
|
title = datum['title']
|
||||||
url = "https://www.nicovideo.jp/watch/#{ datum['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)
|
||||||
if thumbnail_base.present?
|
if thumbnail_base.present?
|
||||||
@@ -62,21 +63,19 @@ namespace :nico do
|
|||||||
sync_post_tags!(post, [Tag.tagme.id])
|
sync_post_tags!(post, [Tag.tagme.id])
|
||||||
end
|
end
|
||||||
|
|
||||||
kept_tags = post.tags.reload
|
kept_ids = PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||||
kept_non_nico_ids = kept_tags.where.not(category: 'nico').pluck(:id).to_set
|
kept_non_nico_ids = post.tags.where.not(category: 'nico').pluck(:id).to_set
|
||||||
|
|
||||||
desired_nico_ids = []
|
desired_nico_ids = []
|
||||||
desired_non_nico_ids = []
|
desired_non_nico_ids = []
|
||||||
datum['tags'].each do |raw|
|
datum['tags'].each do |raw|
|
||||||
name = "nico:#{ raw }"
|
name = "nico:#{ raw }"
|
||||||
tag = Tag.find_or_initialize_by(name:) do |t|
|
tag = Tag.find_or_create_by_tag_name!(name, category: 'nico')
|
||||||
t.category = 'nico'
|
|
||||||
end
|
|
||||||
tag.save! if tag.new_record?
|
|
||||||
desired_nico_ids << tag.id
|
desired_nico_ids << tag.id
|
||||||
unless tag.in?(kept_tags)
|
unless tag.id.in?(kept_ids)
|
||||||
desired_non_nico_ids.concat(tag.linked_tags.pluck(:id))
|
linked_ids = tag.linked_tags.pluck(:id)
|
||||||
desired_nico_ids.concat(tag.linked_tags.pluck(:id))
|
desired_non_nico_ids.concat(linked_ids)
|
||||||
|
desired_nico_ids.concat(linked_ids)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
desired_nico_ids.uniq!
|
desired_nico_ids.uniq!
|
||||||
@@ -89,7 +88,7 @@ namespace :nico do
|
|||||||
end
|
end
|
||||||
desired_all_ids.uniq!
|
desired_all_ids.uniq!
|
||||||
|
|
||||||
sync_post_tags!(post, desired_all_ids)
|
sync_post_tags!(post, desired_all_ids, current_ids: kept_ids)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :tag_name do
|
||||||
|
name { "tag-#{SecureRandom.hex(4)}" }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :tag do
|
||||||
|
category { 'general' }
|
||||||
|
post_count { 0 }
|
||||||
|
association :tag_name
|
||||||
|
|
||||||
|
trait :nico do
|
||||||
|
category { 'nico' }
|
||||||
|
tag_name { association(:tag_name, name: "nico:#{ SecureRandom.hex(4) }") }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :user do
|
||||||
|
name { "test-user" }
|
||||||
|
inheritance_code { SecureRandom.uuid }
|
||||||
|
role { "guest" }
|
||||||
|
|
||||||
|
trait :member do
|
||||||
|
role { "member" }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :wiki_page do
|
||||||
|
title { "TestPage" }
|
||||||
|
association :created_user, factory: :user
|
||||||
|
association :updated_user, factory: :user
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# This file is copied to spec/ when you run 'rails generate rspec:install'
|
||||||
|
require 'spec_helper'
|
||||||
|
ENV['RAILS_ENV'] ||= 'test'
|
||||||
|
require_relative '../config/environment'
|
||||||
|
# Prevent database truncation if the environment is production
|
||||||
|
abort("The Rails environment is running in production mode!") if Rails.env.production?
|
||||||
|
# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file
|
||||||
|
# that will avoid rails generators crashing because migrations haven't been run yet
|
||||||
|
# return unless Rails.env.test?
|
||||||
|
require 'rspec/rails'
|
||||||
|
Dir[Rails.root.join('spec/support/**/*.rb')].each do |f|
|
||||||
|
require f
|
||||||
|
end
|
||||||
|
|
||||||
|
# Add additional requires below this line. Rails is not loaded until this point!
|
||||||
|
|
||||||
|
# Requires supporting ruby files with custom matchers and macros, etc, in
|
||||||
|
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
|
||||||
|
# run as spec files by default. This means that files in spec/support that end
|
||||||
|
# in _spec.rb will both be required and run as specs, causing the specs to be
|
||||||
|
# run twice. It is recommended that you do not name files matching this glob to
|
||||||
|
# end with _spec.rb. You can configure this pattern with the --pattern
|
||||||
|
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
|
||||||
|
#
|
||||||
|
# The following line is provided for convenience purposes. It has the downside
|
||||||
|
# of increasing the boot-up time by auto-requiring all files in the support
|
||||||
|
# directory. Alternatively, in the individual `*_spec.rb` files, manually
|
||||||
|
# require only the support files necessary.
|
||||||
|
#
|
||||||
|
# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }
|
||||||
|
|
||||||
|
# Ensures that the test database schema matches the current schema file.
|
||||||
|
# If there are pending migrations it will invoke `db:test:prepare` to
|
||||||
|
# recreate the test database by loading the schema.
|
||||||
|
# If you are not using ActiveRecord, you can remove these lines.
|
||||||
|
begin
|
||||||
|
ActiveRecord::Migration.maintain_test_schema!
|
||||||
|
rescue ActiveRecord::PendingMigrationError => e
|
||||||
|
abort e.to_s.strip
|
||||||
|
end
|
||||||
|
RSpec.configure do |config|
|
||||||
|
config.before do
|
||||||
|
I18n.locale = :en
|
||||||
|
end
|
||||||
|
|
||||||
|
config.include TestRecords
|
||||||
|
config.include RakeTaskHelper
|
||||||
|
|
||||||
|
# FactoryBot の create / create_list を使へるやぅにする
|
||||||
|
config.include FactoryBot::Syntax::Methods
|
||||||
|
|
||||||
|
# request spec で helper 使へるやぅにする
|
||||||
|
config.include AuthHelper, type: :request
|
||||||
|
config.include JsonHelper, type: :request
|
||||||
|
|
||||||
|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
|
||||||
|
config.fixture_paths = [
|
||||||
|
Rails.root.join('spec/fixtures')
|
||||||
|
]
|
||||||
|
|
||||||
|
# If you're not using ActiveRecord, or you'd prefer not to run each of your
|
||||||
|
# examples within a transaction, remove the following line or assign false
|
||||||
|
# instead of true.
|
||||||
|
config.use_transactional_fixtures = true
|
||||||
|
|
||||||
|
# You can uncomment this line to turn off ActiveRecord support entirely.
|
||||||
|
# config.use_active_record = false
|
||||||
|
|
||||||
|
# RSpec Rails uses metadata to mix in different behaviours to your tests,
|
||||||
|
# for example enabling you to call `get` and `post` in request specs. e.g.:
|
||||||
|
#
|
||||||
|
# RSpec.describe UsersController, type: :request do
|
||||||
|
# # ...
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# The different available types are documented in the features, such as in
|
||||||
|
# https://rspec.info/features/8-0/rspec-rails
|
||||||
|
#
|
||||||
|
# You can also this infer these behaviours automatically by location, e.g.
|
||||||
|
# /spec/models would pull in the same behaviour as `type: :model` but this
|
||||||
|
# behaviour is considered legacy and will be removed in a future version.
|
||||||
|
#
|
||||||
|
# To enable this behaviour uncomment the line below.
|
||||||
|
# config.infer_spec_type_from_file_location!
|
||||||
|
|
||||||
|
# Filter lines from Rails gems in backtraces.
|
||||||
|
config.filter_rails_from_backtrace!
|
||||||
|
# arbitrary gems may also be filtered via:
|
||||||
|
# config.filter_gems_from_backtrace("gem name")
|
||||||
|
end
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe 'NicoTags', type: :request do
|
||||||
|
describe 'GET /tags/nico' do
|
||||||
|
it 'returns tags and next_cursor when overflowing limit' do
|
||||||
|
create_list(:tag, 21, :nico)
|
||||||
|
get '/tags/nico', params: { limit: 20 }
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['tags'].size).to eq(20)
|
||||||
|
expect(json['next_cursor']).to be_present
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'PATCH /tags/nico/:id' do
|
||||||
|
let(:member) { create(:user, :member) }
|
||||||
|
let(:nico_tag) { create(:tag, :nico) }
|
||||||
|
|
||||||
|
it '401 when not logged in' do
|
||||||
|
sign_out
|
||||||
|
patch "/tags/nico/#{nico_tag.id}", params: { tags: 'a b' }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '403 when not member' do
|
||||||
|
sign_in_as(create(:user, role: 'guest'))
|
||||||
|
patch "/tags/nico/#{nico_tag.id}", params: { tags: 'a b' }
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '400 when target is not nico category' do
|
||||||
|
sign_in_as(member)
|
||||||
|
non_nico = create(:tag, :general)
|
||||||
|
patch "/tags/nico/#{non_nico.id}", params: { tags: 'a b' }
|
||||||
|
expect(response).to have_http_status(:bad_request)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
require 'set'
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe 'Posts API', type: :request do
|
||||||
|
# create / update で thumbnail.attach は走るが、
|
||||||
|
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
||||||
|
before do
|
||||||
|
allow_any_instance_of(Post).to receive(:resized_thumbnail!).and_return(true)
|
||||||
|
end
|
||||||
|
|
||||||
|
def dummy_upload
|
||||||
|
# 中身は何でもいい(加工処理はスタブしてる)
|
||||||
|
Rack::Test::UploadedFile.new(StringIO.new('dummy'), 'image/jpeg', original_filename: 'dummy.jpg')
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:tag_name) { TagName.create!(name: 'spec_tag') }
|
||||||
|
let!(:tag) { Tag.create!(tag_name: tag_name, category: 'general') }
|
||||||
|
|
||||||
|
let!(:post_record) do
|
||||||
|
Post.create!(title: 'spec post', url: 'https://example.com/spec').tap do |p|
|
||||||
|
PostTag.create!(post: p, tag: tag)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "GET /posts" do
|
||||||
|
let!(:user) { create_member_user! }
|
||||||
|
|
||||||
|
let!(:tag_name) { TagName.create!(name: "spec_tag") }
|
||||||
|
let!(:tag) { Tag.create!(tag_name:, category: "general") }
|
||||||
|
let!(:tag_name2) { TagName.create!(name: 'unko') }
|
||||||
|
let!(:tag2) { Tag.create!(tag_name: tag_name2, category: 'deerjikist') }
|
||||||
|
|
||||||
|
let!(:hit_post) do
|
||||||
|
Post.create!(uploaded_user: user, title: "hello spec world",
|
||||||
|
url: 'https://example.com/spec').tap do |p|
|
||||||
|
PostTag.create!(post: p, tag:)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:miss_post) do
|
||||||
|
Post.create!(uploaded_user: user, title: "unrelated title",
|
||||||
|
url: 'https://example.com/spec2').tap do |p|
|
||||||
|
PostTag.create!(post: p, tag: tag2)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns posts with tag name in JSON" do
|
||||||
|
get "/posts"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
posts = json.fetch("posts")
|
||||||
|
|
||||||
|
# 全postの全tagが name を含むこと
|
||||||
|
expect(posts).not_to be_empty
|
||||||
|
posts.each do |p|
|
||||||
|
expect(p["tags"]).to be_an(Array)
|
||||||
|
p["tags"].each do |t|
|
||||||
|
expect(t).to include("name", "category")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
expect(json['count']).to be_an(Integer)
|
||||||
|
|
||||||
|
# spec_tag を含む投稿が存在すること
|
||||||
|
all_tag_names = posts.flat_map { |p| p["tags"].map { |t| t["name"] } }
|
||||||
|
expect(all_tag_names).to include("spec_tag")
|
||||||
|
end
|
||||||
|
|
||||||
|
context "when q is provided" do
|
||||||
|
it "filters posts by q (hit case)" do
|
||||||
|
get "/posts", params: { tags: "spec_tag" }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
ids = json.fetch("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)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns empty posts when nothing matches" do
|
||||||
|
get "/posts", params: { tags: "no_such_keyword_12345" }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json.fetch("posts")).to eq([])
|
||||||
|
expect(json.fetch('count')).to eq(0)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /posts/:id' do
|
||||||
|
subject(:request) { get "/posts/#{post_id}" }
|
||||||
|
|
||||||
|
context 'when post exists' do
|
||||||
|
let(:post_id) { post_record.id }
|
||||||
|
|
||||||
|
it 'returns post with tag tree + related + viewed' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to include('id' => post_record.id)
|
||||||
|
expect(json).to have_key('tags')
|
||||||
|
expect(json['tags']).to be_an(Array)
|
||||||
|
|
||||||
|
# show は build_tag_tree_for を使うので、tags はツリー形式(children 付き)
|
||||||
|
node = json['tags'][0]
|
||||||
|
expect(node).to include('id', 'name', 'category', 'post_count', 'children')
|
||||||
|
expect(node['name']).to eq('spec_tag')
|
||||||
|
|
||||||
|
expect(json).to have_key('related')
|
||||||
|
expect(json['related']).to be_an(Array)
|
||||||
|
|
||||||
|
expect(json).to have_key('viewed')
|
||||||
|
expect([true, false]).to include(json['viewed'])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when post does not exist' do
|
||||||
|
let(:post_id) { 999_999_999 }
|
||||||
|
|
||||||
|
it 'returns 404' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /posts' do
|
||||||
|
let(:member) { create(:user, :member) }
|
||||||
|
|
||||||
|
it '401 when not logged in' do
|
||||||
|
sign_out
|
||||||
|
post '/posts', params: { title: 't', url: 'https://example.com/x', tags: 'a', thumbnail: dummy_upload }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '403 when not member' do
|
||||||
|
sign_in_as(create(:user, role: 'guest'))
|
||||||
|
post '/posts', params: { title: 't', url: 'https://example.com/x', tags: 'a', thumbnail: dummy_upload }
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '201 and creates post + tags when member' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: {
|
||||||
|
title: 'new post',
|
||||||
|
url: 'https://example.com/new',
|
||||||
|
tags: 'spec_tag', # 既存タグ名を投げる
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(json).to include('id', 'title', 'url')
|
||||||
|
|
||||||
|
# tags が name を含むこと(API 側の serialization が正しいこと)
|
||||||
|
expect(json).to have_key('tags')
|
||||||
|
expect(json['tags']).to be_an(Array)
|
||||||
|
expect(json['tags'][0]).to have_key('name')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'PUT /posts/:id' do
|
||||||
|
let(:member) { create(:user, :member) }
|
||||||
|
|
||||||
|
it '401 when not logged in' do
|
||||||
|
sign_out
|
||||||
|
put "/posts/#{post_record.id}", params: { title: 'updated', tags: 'spec_tag' }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '403 when not member' do
|
||||||
|
sign_in_as(create(:user, role: 'guest'))
|
||||||
|
put "/posts/#{post_record.id}", params: { title: 'updated', tags: 'spec_tag' }
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '200 and updates title + resync tags when member' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
# 追加で別タグも作って、更新時に入れ替わることを見る
|
||||||
|
tn2 = TagName.create!(name: 'spec_tag_2')
|
||||||
|
Tag.create!(tag_name: tn2, category: 'general')
|
||||||
|
|
||||||
|
put "/posts/#{post_record.id}", params: {
|
||||||
|
title: 'updated title',
|
||||||
|
tags: 'spec_tag_2'
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to have_key('tags')
|
||||||
|
expect(json['tags']).to be_an(Array)
|
||||||
|
|
||||||
|
# show と同様、update 後レスポンスもツリー形式
|
||||||
|
names = json['tags'].map { |n| n['name'] }
|
||||||
|
expect(names).to include('spec_tag_2')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /posts/random' do
|
||||||
|
it '404 when no posts' do
|
||||||
|
PostTag.delete_all
|
||||||
|
Post.delete_all
|
||||||
|
get '/posts/random'
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '200 and returns viewed boolean' do
|
||||||
|
get '/posts/random'
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to have_key('viewed')
|
||||||
|
expect([true, false]).to include(json['viewed'])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /posts/changes' do
|
||||||
|
let(:member) { create(:user, :member) }
|
||||||
|
|
||||||
|
it 'returns add/remove events (history) for a post' do
|
||||||
|
# add
|
||||||
|
tn2 = TagName.create!(name: 'spec_tag2')
|
||||||
|
tag2 = Tag.create!(tag_name: tn2, category: 'general')
|
||||||
|
pt = PostTag.create!(post: post_record, tag: tag2, created_user: member)
|
||||||
|
|
||||||
|
# remove (discard)
|
||||||
|
pt.discard_by!(member)
|
||||||
|
|
||||||
|
get '/posts/changes', params: { id: post_record.id }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to include('changes', 'count')
|
||||||
|
expect(json['changes']).to be_an(Array)
|
||||||
|
expect(json['count']).to be >= 2
|
||||||
|
|
||||||
|
types = json['changes'].map { |e| e['change_type'] }.uniq
|
||||||
|
expect(types).to include('add')
|
||||||
|
expect(types).to include('remove')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /posts/:id/viewed' do
|
||||||
|
let(:user) { create(:user) }
|
||||||
|
|
||||||
|
it '401 when not logged in' do
|
||||||
|
sign_out
|
||||||
|
post "/posts/#{ post_record.id }/viewed"
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '204 and marks viewed when logged in' do
|
||||||
|
sign_in_as(user)
|
||||||
|
post "/posts/#{ post_record.id }/viewed"
|
||||||
|
expect(response).to have_http_status(:no_content)
|
||||||
|
|
||||||
|
expect(user.reload.viewed?(post_record)).to be(true)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'DELETE /posts/:id/viewed' do
|
||||||
|
let(:user) { create(:user) }
|
||||||
|
|
||||||
|
it '401 when not logged in' do
|
||||||
|
sign_out
|
||||||
|
delete "/posts/#{ post_record.id }/viewed"
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '204 and unmarks viewed when logged in' do
|
||||||
|
sign_in_as(user)
|
||||||
|
|
||||||
|
# 先に viewed 付けてから外す
|
||||||
|
user.viewed_posts << post_record
|
||||||
|
|
||||||
|
delete "/posts/#{ post_record.id }/viewed"
|
||||||
|
expect(response).to have_http_status(:no_content)
|
||||||
|
|
||||||
|
expect(user.reload.viewed?(post_record)).to be(false)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
require "rails_helper"
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe "Preview", type: :request do
|
||||||
|
describe "GET /preview/title" do
|
||||||
|
it "401 unless logged in" do
|
||||||
|
sign_out
|
||||||
|
get "/preview/title", params: { url: "example.com" }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "400 when url blank" do
|
||||||
|
sign_in_as(create(:user))
|
||||||
|
get "/preview/title", params: { url: "" }
|
||||||
|
expect(response).to have_http_status(:bad_request)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns parsed title (stubbing URI.open)" do
|
||||||
|
sign_in_as(create(:user))
|
||||||
|
fake_html = "<html><head><title> Hello </title></head></html>"
|
||||||
|
allow(URI).to receive(:open).and_return(StringIO.new(fake_html))
|
||||||
|
|
||||||
|
get "/preview/title", params: { url: "example.com" }
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["title"]).to eq("Hello")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
require 'cgi'
|
||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe 'Tags API', type: :request do
|
||||||
|
let!(:tn) { TagName.create!(name: 'spec_tag') }
|
||||||
|
let!(:tag) { Tag.create!(tag_name: tn, category: 'general') }
|
||||||
|
|
||||||
|
describe 'GET /tags' do
|
||||||
|
it 'returns tags with name' do
|
||||||
|
get '/tags'
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json).not_to be_empty
|
||||||
|
expect(json[0]).to have_key('name')
|
||||||
|
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /tags/:id' do
|
||||||
|
subject(:request) do
|
||||||
|
get "/tags/#{ tag_id }"
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:tag_id) { tag.id }
|
||||||
|
|
||||||
|
context 'when tag exists' do
|
||||||
|
it 'returns tag with name' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'id' => tag.id,
|
||||||
|
'name' => 'spec_tag',
|
||||||
|
'category' => 'general')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when tag does not exist' do
|
||||||
|
let(:tag_id) { 9_999_999 }
|
||||||
|
|
||||||
|
it 'returns 404' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /tags/autocomplete' do
|
||||||
|
it 'returns matching tags by q' do
|
||||||
|
get '/tags/autocomplete', params: { q: 'spec' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json.map { |t| t['name'] }).to include('spec_tag')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /tags/name/:name' do
|
||||||
|
it 'returns tag by name' do
|
||||||
|
get "/tags/name/#{ CGI.escape('spec_tag') }"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to have_key('id')
|
||||||
|
expect(json).to have_key('name')
|
||||||
|
expect(json['id']).to eq(tag.id)
|
||||||
|
expect(json['name']).to eq('spec_tag')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 404 when not found' do
|
||||||
|
get "/tags/name/#{ CGI.escape('nope') }"
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
require "rails_helper"
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe "Users", type: :request do
|
||||||
|
describe "POST /users" do
|
||||||
|
it "creates guest user and returns code" do
|
||||||
|
post "/users"
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["code"]).to be_present
|
||||||
|
expect(json["user"]["role"]).to eq("guest")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "POST /users/code/renew" do
|
||||||
|
it "returns 401 when not logged in" do
|
||||||
|
sign_out
|
||||||
|
post "/users/code/renew"
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "PUT /users/:id" do
|
||||||
|
let(:user) { create(:user, name: "old-name", role: "guest") }
|
||||||
|
|
||||||
|
it "returns 401 when current_user id mismatch" do
|
||||||
|
sign_in_as(create(:user))
|
||||||
|
put "/users/#{user.id}", params: { name: "new-name" }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns 400 when name is blank" do
|
||||||
|
sign_in_as(user)
|
||||||
|
put "/users/#{user.id}", params: { name: " " }
|
||||||
|
expect(response).to have_http_status(:bad_request)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "updates name and returns 201 with user slice" do
|
||||||
|
sign_in_as(user)
|
||||||
|
put "/users/#{user.id}", params: { name: "new-name" }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(json["id"]).to eq(user.id)
|
||||||
|
expect(json["name"]).to eq("new-name")
|
||||||
|
|
||||||
|
user.reload
|
||||||
|
expect(user.name).to eq("new-name")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "POST /users/verify" do
|
||||||
|
it "returns valid:false when code not found" do
|
||||||
|
post "/users/verify", params: { code: "nope" }
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["valid"]).to eq(false)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "creates IpAddress and UserIp, and returns valid:true with user slice" do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: "guest")
|
||||||
|
|
||||||
|
# request.remote_ip を固定
|
||||||
|
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("203.0.113.10")
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post "/users/verify", params: { code: user.inheritance_code }
|
||||||
|
}.to change(UserIp, :count).by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["valid"]).to eq(true)
|
||||||
|
expect(json["user"]["id"]).to eq(user.id)
|
||||||
|
expect(json["user"]["inheritance_code"]).to eq(user.inheritance_code)
|
||||||
|
expect(json["user"]["role"]).to eq("guest")
|
||||||
|
|
||||||
|
# ついでに IpAddress もできてることを確認(ipの保存形式がバイナリでも count で見れる)
|
||||||
|
expect(IpAddress.count).to be >= 1
|
||||||
|
end
|
||||||
|
|
||||||
|
it "is idempotent for same user+ip (does not create duplicate UserIp)" do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: "guest")
|
||||||
|
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("203.0.113.10")
|
||||||
|
|
||||||
|
post "/users/verify", params: { code: user.inheritance_code }
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post "/users/verify", params: { code: user.inheritance_code }
|
||||||
|
}.not_to change(UserIp, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["valid"]).to eq(true)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "GET /users/me" do
|
||||||
|
it "returns 404 when code not found" do
|
||||||
|
get "/users/me", params: { code: "nope" }
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns user slice when found" do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid, name: "me", role: "guest")
|
||||||
|
get "/users/me", params: { code: user.inheritance_code }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json["id"]).to eq(user.id)
|
||||||
|
expect(json["name"]).to eq("me")
|
||||||
|
expect(json["inheritance_code"]).to eq(user.inheritance_code)
|
||||||
|
expect(json["role"]).to eq("guest")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
require 'cgi'
|
||||||
|
require 'rails_helper'
|
||||||
|
require 'securerandom'
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe 'Wiki API', type: :request do
|
||||||
|
let!(:user) { create_member_user! }
|
||||||
|
|
||||||
|
let!(:tn) { TagName.create!(name: 'spec_wiki_title') }
|
||||||
|
let!(:page) do
|
||||||
|
WikiPage.create!(tag_name: tn, created_user: user, updated_user: user)
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki' do
|
||||||
|
it 'returns wiki pages with title' do
|
||||||
|
get '/wiki'
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json).not_to be_empty
|
||||||
|
|
||||||
|
expect(json[0]).to have_key('title')
|
||||||
|
expect(json.map { |p| p['title'] }).to include('spec_wiki_title')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/:id' do
|
||||||
|
subject(:request) do
|
||||||
|
get "/wiki/#{ page_id }"
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:page_id) { page.id }
|
||||||
|
|
||||||
|
context 'when wiki page exists' do
|
||||||
|
it 'returns wiki page with title' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'id' => page.id,
|
||||||
|
'title' => 'spec_wiki_title')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when wiki page does not exist' do
|
||||||
|
let(:page_id) { 9_999_999 }
|
||||||
|
|
||||||
|
it 'returns 404' do
|
||||||
|
request
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /wiki' do
|
||||||
|
let(:endpoint) { '/wiki' }
|
||||||
|
|
||||||
|
let(:member) { create(:user, role: 'member') }
|
||||||
|
let(:guest) { create(:user, role: 'guest') }
|
||||||
|
|
||||||
|
def auth_headers(user)
|
||||||
|
{ 'X-Transfer-Code' => user.inheritance_code }
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when not logged in' do
|
||||||
|
it 'returns 401' do
|
||||||
|
post endpoint, params: { title: 'Test', body: 'Hello' }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when logged in but not member' do
|
||||||
|
it 'returns 403' do
|
||||||
|
post endpoint, params: { title: 'Test', body: 'Hello' }, headers: auth_headers(guest)
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when params invalid' do
|
||||||
|
it 'returns 422 when title blank' do
|
||||||
|
post endpoint, params: { title: '', body: 'Hello' }, headers: auth_headers(member)
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 422 when body blank' do
|
||||||
|
post endpoint, params: { title: 'Test', body: '' }, headers: auth_headers(member)
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when success' do
|
||||||
|
it 'creates wiki_page and first content revision' do
|
||||||
|
expect do
|
||||||
|
post endpoint, params: { title: 'TestPage', body: "a\nb\nc", message: 'init' },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
end
|
||||||
|
.to change(WikiPage, :count).by(1)
|
||||||
|
.and change(WikiRevision, :count).by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
page_id = json.fetch('id')
|
||||||
|
expect(json.fetch('title')).to eq('TestPage')
|
||||||
|
|
||||||
|
page = WikiPage.find(page_id)
|
||||||
|
rev = page.current_revision
|
||||||
|
expect(rev).to be_present
|
||||||
|
expect(rev).to be_content
|
||||||
|
expect(rev.message).to eq('init')
|
||||||
|
|
||||||
|
# body が復元できること
|
||||||
|
expect(page.body).to eq("a\nb\nc")
|
||||||
|
|
||||||
|
# 行数とリレーションの整合
|
||||||
|
expect(rev.lines_count).to eq(3)
|
||||||
|
expect(rev.wiki_revision_lines.order(:position).pluck(:position)).to eq([0, 1, 2])
|
||||||
|
expect(rev.wiki_lines.pluck(:body)).to match_array(%w[a b c])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'reuses existing WikiLine rows by sha256' do
|
||||||
|
# 先に同じ行を作っておく
|
||||||
|
WikiLine.create!(sha256: Digest::SHA256.hexdigest('a'), body: 'a', created_at: Time.current, updated_at: Time.current)
|
||||||
|
|
||||||
|
post endpoint,
|
||||||
|
params: { title: 'Reuse', body: "a\na" },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
|
||||||
|
page = WikiPage.find(JSON.parse(response.body).fetch('id'))
|
||||||
|
rev = page.current_revision
|
||||||
|
expect(rev.lines_count).to eq(2)
|
||||||
|
|
||||||
|
# "a" の WikiLine が増殖しない(1行のはず)
|
||||||
|
expect(WikiLine.where(body: 'a').count).to eq(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'PUT /wiki/:id' do
|
||||||
|
let(:member) { create(:user, role: 'member', inheritance_code: SecureRandom.hex(16)) }
|
||||||
|
let(:guest) { create(:user, role: 'guest', inheritance_code: SecureRandom.hex(16)) }
|
||||||
|
|
||||||
|
def auth_headers(user)
|
||||||
|
{ 'X-Transfer-Code' => user.inheritance_code }
|
||||||
|
end
|
||||||
|
|
||||||
|
#let!(:page) { create(:wiki_page, title: 'TestPage') }
|
||||||
|
let!(:page) do
|
||||||
|
build(:wiki_page, title: 'TestPage').tap do |p|
|
||||||
|
puts p.errors.full_messages unless p.valid?
|
||||||
|
p.save!
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
before do
|
||||||
|
# 初期版を 1 つ作っておく(更新が“2版目”になるように)
|
||||||
|
Wiki::Commit.content!(page: page, body: "a\nb", created_user: member, message: 'init')
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when not logged in' do
|
||||||
|
it 'returns 401' do
|
||||||
|
put "/wiki/#{page.id}", params: { title: 'TestPage', body: 'x' }
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when logged in but not member' do
|
||||||
|
it 'returns 403' do
|
||||||
|
put "/wiki/#{page.id}",
|
||||||
|
params: { title: 'TestPage', body: 'x' },
|
||||||
|
headers: auth_headers(guest)
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when params invalid' do
|
||||||
|
it 'returns 422 when body blank' do
|
||||||
|
put "/wiki/#{page.id}",
|
||||||
|
params: { title: 'TestPage', body: '' },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 422 when title mismatched (if you forbid rename here)' do
|
||||||
|
put "/wiki/#{page.id}",
|
||||||
|
params: { title: 'OtherTitle', body: 'x' },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
# 君の controller 例だと title 変更は 422 にしてた
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when success' do
|
||||||
|
it 'creates new revision and returns 200' do
|
||||||
|
current_id = page.wiki_revisions.maximum(:id)
|
||||||
|
|
||||||
|
expect do
|
||||||
|
put "/wiki/#{page.id}",
|
||||||
|
params: { title: 'TestPage', body: "x\ny", message: 'edit', base_revision_id: current_id },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
end.to change(WikiRevision, :count).by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
page.reload
|
||||||
|
rev = page.current_revision
|
||||||
|
expect(rev).to be_content
|
||||||
|
expect(rev.message).to eq('edit')
|
||||||
|
expect(page.body).to eq("x\ny")
|
||||||
|
expect(rev.base_revision_id).to eq(current_id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# TODO: コンフリクト未実装のため,実装したらコメント外す.
|
||||||
|
# context 'when conflict' do
|
||||||
|
# it 'returns 409 when base_revision_id mismatches' do
|
||||||
|
# # 先に別ユーザ(同じ member でもOK)が 1 回更新して先頭を進める
|
||||||
|
# Wiki::Commit.content!(page: page, body: "zzz", created_user: member, message: 'other edit')
|
||||||
|
# page.reload
|
||||||
|
|
||||||
|
# stale_id = page.wiki_revisions.order(:id).first.id # わざと古い id
|
||||||
|
# put "/wiki/#{page.id}",
|
||||||
|
# params: { title: 'TestPage', body: 'x', base_revision_id: stale_id },
|
||||||
|
# headers: auth_headers(member)
|
||||||
|
|
||||||
|
# expect(response).to have_http_status(:conflict)
|
||||||
|
# json = JSON.parse(response.body)
|
||||||
|
# expect(json['error']).to eq('conflict')
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
|
||||||
|
context 'when page not found' do
|
||||||
|
it 'returns 404' do
|
||||||
|
put "/wiki/99999999",
|
||||||
|
params: { title: 'X', body: 'x' },
|
||||||
|
headers: auth_headers(member)
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/title/:title' do
|
||||||
|
it 'returns wiki page by title' do
|
||||||
|
get "/wiki/title/#{CGI.escape('spec_wiki_title')}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to have_key('id')
|
||||||
|
expect(json).to have_key('title')
|
||||||
|
expect(json['id']).to eq(page.id)
|
||||||
|
expect(json['title']).to eq('spec_wiki_title')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 404 when not found' do
|
||||||
|
get "/wiki/title/#{ CGI.escape('nope') }"
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/search' do
|
||||||
|
before do
|
||||||
|
# 追加で検索ヒット用
|
||||||
|
TagName.create!(name: 'spec_wiki_title_2')
|
||||||
|
WikiPage.create!(tag_name: TagName.find_by!(name: 'spec_wiki_title_2'),
|
||||||
|
created_user: user, updated_user: user)
|
||||||
|
|
||||||
|
TagName.create!(name: 'unrelated_title')
|
||||||
|
WikiPage.create!(tag_name: TagName.find_by!(name: 'unrelated_title'),
|
||||||
|
created_user: user, updated_user: user)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns up to 20 pages filtered by title like' do
|
||||||
|
get "/wiki/search?title=#{CGI.escape('spec_wiki')}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
|
||||||
|
titles = json.map { |p| p['title'] }
|
||||||
|
expect(titles).to include('spec_wiki_title', 'spec_wiki_title_2')
|
||||||
|
expect(titles).not_to include('unrelated_title')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns all when title param is blank' do
|
||||||
|
get "/wiki/search?title=#{CGI.escape('')}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json.map { |p| p['title'] }).to include('spec_wiki_title')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/changes' do
|
||||||
|
let!(:rev1) do
|
||||||
|
Wiki::Commit.content!(page: page, body: "a\nb", created_user: user, message: 'r1')
|
||||||
|
page.current_revision
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:rev2) do
|
||||||
|
Wiki::Commit.content!(page: page, body: "a\nc", created_user: user, message: 'r2')
|
||||||
|
page.current_revision
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns latest revisions (optionally filtered by page id)' do
|
||||||
|
get "/wiki/changes?id=#{page.id}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json).not_to be_empty
|
||||||
|
|
||||||
|
top = json.first
|
||||||
|
expect(top).to include(
|
||||||
|
'revision_id' => rev2.id,
|
||||||
|
'pred' => rev2.base_revision_id,
|
||||||
|
'succ' => nil,
|
||||||
|
'kind' => 'content',
|
||||||
|
'message' => 'r2'
|
||||||
|
)
|
||||||
|
expect(top['wiki_page']).to include('id' => page.id, 'title' => 'spec_wiki_title')
|
||||||
|
expect(top['user']).to include('id' => user.id, 'name' => user.name)
|
||||||
|
expect(top).to have_key('timestamp')
|
||||||
|
|
||||||
|
# order desc をざっくり担保
|
||||||
|
ids = json.map { |x| x['revision_id'] }
|
||||||
|
expect(ids).to eq(ids.sort.reverse)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns empty array when page has no revisions and filtered by id' do
|
||||||
|
# 別ページを作って revision 無し
|
||||||
|
tn2 = TagName.create!(name: 'spec_no_rev')
|
||||||
|
p2 = WikiPage.create!(tag_name: tn2, created_user: user, updated_user: user)
|
||||||
|
|
||||||
|
get "/wiki/changes?id=#{p2.id}"
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to eq([])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/title/:title/exists' do
|
||||||
|
it 'returns 204 when exists' do
|
||||||
|
get "/wiki/title/#{CGI.escape('spec_wiki_title')}/exists"
|
||||||
|
expect(response).to have_http_status(:no_content)
|
||||||
|
expect(response.body).to be_empty
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 404 when not exists' do
|
||||||
|
get "/wiki/title/#{CGI.escape('nope')}/exists"
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/:id/exists' do
|
||||||
|
it 'returns 204 when exists' do
|
||||||
|
get "/wiki/#{page.id}/exists"
|
||||||
|
expect(response).to have_http_status(:no_content)
|
||||||
|
expect(response.body).to be_empty
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 404 when not exists' do
|
||||||
|
get "/wiki/99999999/exists"
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/:id/diff' do
|
||||||
|
let!(:rev_a) do
|
||||||
|
Wiki::Commit.content!(page: page, body: "a\nb\nc", created_user: user, message: 'A')
|
||||||
|
page.current_revision
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:rev_b) do
|
||||||
|
Wiki::Commit.content!(page: page, body: "a\nx\nc", created_user: user, message: 'B')
|
||||||
|
page.current_revision
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns diff json between revisions' do
|
||||||
|
get "/wiki/#{page.id}/diff?from=#{rev_a.id}&to=#{rev_b.id}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'wiki_page_id' => page.id,
|
||||||
|
'title' => 'spec_wiki_title',
|
||||||
|
'older_revision_id' => rev_a.id,
|
||||||
|
'newer_revision_id' => rev_b.id
|
||||||
|
)
|
||||||
|
expect(json['diff']).to be_an(Array)
|
||||||
|
# ざっくり「b が消えて x が増えた」が含まれることを確認
|
||||||
|
types = json['diff'].map { |x| x['type'] }
|
||||||
|
expect(types).to include('removed', 'added').or include('removed').and include('added')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'uses latest as "to" when to is omitted' do
|
||||||
|
get "/wiki/#{page.id}/diff?from=#{rev_a.id}"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['older_revision_id']).to eq(rev_a.id)
|
||||||
|
expect(json['newer_revision_id']).to eq(page.current_revision.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 422 when "to" is redirect revision' do
|
||||||
|
# redirect revision を作る
|
||||||
|
tn2 = TagName.create!(name: 'redirect_target')
|
||||||
|
target = WikiPage.create!(tag_name: tn2, created_user: user, updated_user: user)
|
||||||
|
|
||||||
|
Wiki::Commit.redirect!(page: page, redirect_page: target, created_user: user, message: 'redir')
|
||||||
|
redirect_rev = page.current_revision
|
||||||
|
expect(redirect_rev).to be_redirect
|
||||||
|
|
||||||
|
get "/wiki/#{page.id}/diff?from=#{rev_a.id}&to=#{redirect_rev.id}"
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 422 when "from" is redirect revision' do
|
||||||
|
tn2 = TagName.create!(name: 'redirect_target2')
|
||||||
|
target = WikiPage.create!(tag_name: tn2, created_user: user, updated_user: user)
|
||||||
|
|
||||||
|
Wiki::Commit.redirect!(page: page, redirect_page: target, created_user: user, message: 'redir2')
|
||||||
|
redirect_rev = page.current_revision
|
||||||
|
|
||||||
|
get "/wiki/#{page.id}/diff?from=#{redirect_rev.id}&to=#{rev_b.id}"
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
|
||||||
|
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
|
||||||
|
# The generated `.rspec` file contains `--require spec_helper` which will cause
|
||||||
|
# this file to always be loaded, without a need to explicitly require it in any
|
||||||
|
# files.
|
||||||
|
#
|
||||||
|
# Given that it is always loaded, you are encouraged to keep this file as
|
||||||
|
# light-weight as possible. Requiring heavyweight dependencies from this file
|
||||||
|
# will add to the boot time of your test suite on EVERY test run, even for an
|
||||||
|
# individual file that may not need all of that loaded. Instead, consider making
|
||||||
|
# a separate helper file that requires the additional dependencies and performs
|
||||||
|
# the additional setup, and require it from the spec files that actually need
|
||||||
|
# it.
|
||||||
|
#
|
||||||
|
# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
|
||||||
|
RSpec.configure do |config|
|
||||||
|
# rspec-expectations config goes here. You can use an alternate
|
||||||
|
# assertion/expectation library such as wrong or the stdlib/minitest
|
||||||
|
# assertions if you prefer.
|
||||||
|
config.expect_with :rspec do |expectations|
|
||||||
|
# This option will default to `true` in RSpec 4. It makes the `description`
|
||||||
|
# and `failure_message` of custom matchers include text for helper methods
|
||||||
|
# defined using `chain`, e.g.:
|
||||||
|
# be_bigger_than(2).and_smaller_than(4).description
|
||||||
|
# # => "be bigger than 2 and smaller than 4"
|
||||||
|
# ...rather than:
|
||||||
|
# # => "be bigger than 2"
|
||||||
|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
|
||||||
|
end
|
||||||
|
|
||||||
|
# rspec-mocks config goes here. You can use an alternate test double
|
||||||
|
# library (such as bogus or mocha) by changing the `mock_with` option here.
|
||||||
|
config.mock_with :rspec do |mocks|
|
||||||
|
# Prevents you from mocking or stubbing a method that does not exist on
|
||||||
|
# a real object. This is generally recommended, and will default to
|
||||||
|
# `true` in RSpec 4.
|
||||||
|
mocks.verify_partial_doubles = true
|
||||||
|
end
|
||||||
|
|
||||||
|
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
|
||||||
|
# have no way to turn it off -- the option exists only for backwards
|
||||||
|
# compatibility in RSpec 3). It causes shared context metadata to be
|
||||||
|
# inherited by the metadata hash of host groups and examples, rather than
|
||||||
|
# triggering implicit auto-inclusion in groups with matching metadata.
|
||||||
|
config.shared_context_metadata_behavior = :apply_to_host_groups
|
||||||
|
|
||||||
|
# The settings below are suggested to provide a good initial experience
|
||||||
|
# with RSpec, but feel free to customize to your heart's content.
|
||||||
|
=begin
|
||||||
|
# This allows you to limit a spec run to individual examples or groups
|
||||||
|
# you care about by tagging them with `:focus` metadata. When nothing
|
||||||
|
# is tagged with `:focus`, all examples get run. RSpec also provides
|
||||||
|
# aliases for `it`, `describe`, and `context` that include `:focus`
|
||||||
|
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
|
||||||
|
config.filter_run_when_matching :focus
|
||||||
|
|
||||||
|
# Allows RSpec to persist some state between runs in order to support
|
||||||
|
# the `--only-failures` and `--next-failure` CLI options. We recommend
|
||||||
|
# you configure your source control system to ignore this file.
|
||||||
|
config.example_status_persistence_file_path = "spec/examples.txt"
|
||||||
|
|
||||||
|
# Limits the available syntax to the non-monkey patched syntax that is
|
||||||
|
# recommended. For more details, see:
|
||||||
|
# https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/
|
||||||
|
config.disable_monkey_patching!
|
||||||
|
|
||||||
|
# Many RSpec users commonly either run the entire suite or an individual
|
||||||
|
# file, and it's useful to allow more verbose output when running an
|
||||||
|
# individual spec file.
|
||||||
|
if config.files_to_run.one?
|
||||||
|
# Use the documentation formatter for detailed output,
|
||||||
|
# unless a formatter has already been configured
|
||||||
|
# (e.g. via a command-line flag).
|
||||||
|
config.default_formatter = "doc"
|
||||||
|
end
|
||||||
|
|
||||||
|
# Print the 10 slowest examples and example groups at the
|
||||||
|
# end of the spec run, to help surface which specs are running
|
||||||
|
# particularly slow.
|
||||||
|
config.profile_examples = 10
|
||||||
|
|
||||||
|
# Run specs in random order to surface order dependencies. If you find an
|
||||||
|
# order dependency and want to debug it, you can fix the order by providing
|
||||||
|
# the seed, which is printed after each run.
|
||||||
|
# --seed 1234
|
||||||
|
config.order = :random
|
||||||
|
|
||||||
|
# Seed global randomization in this process using the `--seed` CLI option.
|
||||||
|
# Setting this allows you to use `--seed` to deterministically reproduce
|
||||||
|
# test failures related to randomization by passing the same `--seed` value
|
||||||
|
# as the one that triggered the failure.
|
||||||
|
Kernel.srand config.seed
|
||||||
|
=end
|
||||||
|
end
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
module AuthHelper
|
||||||
|
def sign_in_as(user)
|
||||||
|
allow_any_instance_of(ApplicationController)
|
||||||
|
.to receive(:current_user).and_return(user)
|
||||||
|
end
|
||||||
|
|
||||||
|
def sign_out
|
||||||
|
allow_any_instance_of(ApplicationController)
|
||||||
|
.to receive(:current_user).and_return(nil)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module JsonHelper
|
||||||
|
def json
|
||||||
|
JSON.parse(response.body)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
require "rake"
|
||||||
|
|
||||||
|
|
||||||
|
module RakeTaskHelper
|
||||||
|
# Railsの rake task を一度だけロードする
|
||||||
|
def load_rails_tasks!
|
||||||
|
return if defined?(@rails_tasks_loaded) && @rails_tasks_loaded
|
||||||
|
@rails_tasks_loaded = true
|
||||||
|
|
||||||
|
Rake.application = Rake::Application.new
|
||||||
|
Rails.application.load_tasks
|
||||||
|
end
|
||||||
|
|
||||||
|
def run_rake_task(full_name)
|
||||||
|
load_rails_tasks!
|
||||||
|
|
||||||
|
task = Rake::Task[full_name] # ここは rake[...] じゃなくて良い
|
||||||
|
task.reenable
|
||||||
|
task.invoke
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
module TestRecords
|
||||||
|
def create_member_user!
|
||||||
|
User.create!(name: 'spec user',
|
||||||
|
inheritance_code: SecureRandom.hex(16),
|
||||||
|
role: 'member',
|
||||||
|
banned: false)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
require "rails_helper"
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe "nico:sync" do
|
||||||
|
def stub_python(json_array)
|
||||||
|
status = instance_double(Process::Status, success?: true)
|
||||||
|
allow(Open3).to receive(:capture3).and_return([json_array.to_json, "", status])
|
||||||
|
end
|
||||||
|
|
||||||
|
def create_tag!(name, category:)
|
||||||
|
tn = TagName.find_or_create_by!(name: name.to_s.strip)
|
||||||
|
Tag.find_or_create_by!(tag_name_id: tn.id) { |t| t.category = category }
|
||||||
|
end
|
||||||
|
|
||||||
|
def link_nico_to_tag!(nico_tag, tag)
|
||||||
|
# NicoTagRelation がある前提(君の model からそう見える)
|
||||||
|
NicoTagRelation.create!(nico_tag_id: nico_tag.id, tag_id: tag.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "既存 post を見つけて、nico tag と linked tag を追加し、差分が出たら bot を付ける" do
|
||||||
|
# 既存 post(正規表現で拾われるURL)
|
||||||
|
post = Post.create!(title: "old", url: "https://www.nicovideo.jp/watch/sm9", uploaded_user: nil)
|
||||||
|
|
||||||
|
# 既存の非nicoタグ(kept_non_nico_ids)
|
||||||
|
kept_general = create_tag!("spec_kept", category: "general")
|
||||||
|
PostTag.create!(post: post, tag: kept_general)
|
||||||
|
|
||||||
|
# 追加される linked tag を準備(nico tag に紐付く一般タグ)
|
||||||
|
linked = create_tag!("spec_linked", category: "general")
|
||||||
|
nico = create_tag!("nico:AAA", category: "nico")
|
||||||
|
link_nico_to_tag!(nico, linked)
|
||||||
|
|
||||||
|
# bot / tagme は task 内で使うので作っておく(Tag.bot/tagme がある前提)
|
||||||
|
Tag.bot
|
||||||
|
Tag.tagme
|
||||||
|
|
||||||
|
# pythonの出力(AAA が付く)
|
||||||
|
stub_python([{ "code" => "sm9", "title" => "t", "tags" => ["AAA"] }])
|
||||||
|
|
||||||
|
# 外部HTTPは今回「既存 post なので呼ばれない」はずだが、念のため塞ぐ
|
||||||
|
allow(URI).to receive(:open).and_return(StringIO.new("<html></html>"))
|
||||||
|
|
||||||
|
run_rake_task("nico:sync")
|
||||||
|
|
||||||
|
post.reload
|
||||||
|
active_tag_names = post.tags.joins(:tag_name).pluck("tag_names.name")
|
||||||
|
|
||||||
|
expect(active_tag_names).to include("spec_kept")
|
||||||
|
expect(active_tag_names).to include("nico:AAA")
|
||||||
|
expect(active_tag_names).to include("spec_linked")
|
||||||
|
|
||||||
|
# 差分が出るので bot が付く(kept_non_nico_ids != desired_non_nico_ids)
|
||||||
|
expect(active_tag_names).to include("bot操作")
|
||||||
|
end
|
||||||
|
|
||||||
|
it "既存 post にあった古い nico tag は active から外され、履歴として discard される" do
|
||||||
|
post = Post.create!(title: "old", url: "https://www.nicovideo.jp/watch/sm9", uploaded_user: nil)
|
||||||
|
|
||||||
|
# 旧nicoタグ(今回の同期結果に含まれない)
|
||||||
|
old_nico = create_tag!("nico:OLD", category: "nico")
|
||||||
|
old_pt = PostTag.create!(post: post, tag: old_nico)
|
||||||
|
expect(old_pt.discarded_at).to be_nil
|
||||||
|
|
||||||
|
# 今回は NEW のみ欲しい
|
||||||
|
new_nico = create_tag!("nico:NEW", category: "nico")
|
||||||
|
|
||||||
|
# bot/tagme 念のため
|
||||||
|
Tag.bot
|
||||||
|
Tag.tagme
|
||||||
|
|
||||||
|
stub_python([{ "code" => "sm9", "title" => "t", "tags" => ["NEW"] }])
|
||||||
|
allow(URI).to receive(:open).and_return(StringIO.new("<html></html>"))
|
||||||
|
|
||||||
|
run_rake_task("nico:sync")
|
||||||
|
|
||||||
|
# OLD は active から外れる(discarded_at が入る)
|
||||||
|
old_pts = PostTag.where(post_id: post.id, tag_id: old_nico.id).order(:id).to_a
|
||||||
|
expect(old_pts.last.discarded_at).to be_present
|
||||||
|
|
||||||
|
# NEW は active にいる
|
||||||
|
post.reload
|
||||||
|
active_names = post.tags.joins(:tag_name).pluck("tag_names.name")
|
||||||
|
expect(active_names).to include("nico:NEW")
|
||||||
|
expect(active_names).not_to include("nico:OLD")
|
||||||
|
end
|
||||||
|
end
|
||||||
Generated
+2
-1
@@ -29,7 +29,8 @@
|
|||||||
"react-router-dom": "^6.30.0",
|
"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"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.25.0",
|
"@eslint/js": "^9.25.0",
|
||||||
|
|||||||
@@ -31,7 +31,8 @@
|
|||||||
"react-router-dom": "^6.30.0",
|
"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"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.25.0",
|
"@eslint/js": "^9.25.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import toCamel from 'camelcase-keys'
|
import toCamel from 'camelcase-keys'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import ReactMarkdown from 'react-markdown'
|
import ReactMarkdown from 'react-markdown'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import remarkGFM from 'remark-gfm'
|
import remarkGFM from 'remark-gfm'
|
||||||
@@ -8,6 +8,7 @@ import remarkGFM from 'remark-gfm'
|
|||||||
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 { API_BASE_URL } from '@/config'
|
import { API_BASE_URL } from '@/config'
|
||||||
|
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
import type { Components } from 'react-markdown'
|
import type { Components } from 'react-markdown'
|
||||||
@@ -34,17 +35,16 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
|
|||||||
|
|
||||||
export default (({ title, body }: Props) => {
|
export default (({ title, body }: Props) => {
|
||||||
const [pageNames, setPageNames] = useState<string[]> ([])
|
const [pageNames, setPageNames] = useState<string[]> ([])
|
||||||
const [realBody, setRealBody] = useState<string> ('')
|
|
||||||
|
const remarkPlugins = useMemo (
|
||||||
|
() => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (!(body))
|
|
||||||
return
|
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const res = await axios.get (`${ API_BASE_URL }/wiki`)
|
const res = await axios.get (`${ API_BASE_URL }/wiki`)
|
||||||
const data = toCamel (res.data as any, { deep: true }) as WikiPage[]
|
const data: WikiPage[] = toCamel (res.data as any, { deep: true })
|
||||||
setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length))
|
setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length))
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
@@ -54,52 +54,8 @@ export default (({ title, body }: Props) => {
|
|||||||
}) ()
|
}) ()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
setRealBody ('')
|
|
||||||
}, [body])
|
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (!(body))
|
|
||||||
return
|
|
||||||
|
|
||||||
const matchIndices = (target: string, keyword: string) => {
|
|
||||||
const indices: number[] = []
|
|
||||||
let pos = 0
|
|
||||||
let idx
|
|
||||||
while ((idx = target.indexOf (keyword, pos)) >= 0)
|
|
||||||
{
|
|
||||||
indices.push (idx)
|
|
||||||
pos = idx + keyword.length
|
|
||||||
}
|
|
||||||
|
|
||||||
return indices
|
|
||||||
}
|
|
||||||
|
|
||||||
const linkIndices = (text: string, names: string[]): [string, [number, number]][] => {
|
|
||||||
const result: [string, [number, number]][] = []
|
|
||||||
|
|
||||||
names.forEach (name => {
|
|
||||||
matchIndices (text, name).forEach (idx => {
|
|
||||||
const start = idx
|
|
||||||
const end = idx + name.length
|
|
||||||
const overlaps = result.some (([, [st, ed]]) => start < ed && end > st)
|
|
||||||
if (!(overlaps))
|
|
||||||
result.push ([name, [start, end]])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
return result.sort (([, [a]], [, [b]]) => b - a)
|
|
||||||
}
|
|
||||||
|
|
||||||
setRealBody (
|
|
||||||
linkIndices (body, pageNames).reduce ((acc, [name, [start, end]]) => (
|
|
||||||
acc.slice (0, start)
|
|
||||||
+ `[${ name }](/wiki/${ encodeURIComponent (name) })`
|
|
||||||
+ acc.slice (end)), body))
|
|
||||||
}, [body, pageNames])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ReactMarkdown components={mdComponents} remarkPlugins={[remarkGFM]}>
|
<ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
|
||||||
{realBody || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
||||||
</ReactMarkdown>)
|
</ReactMarkdown>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import type { Content, Parent, Root, RootContent } from 'mdast'
|
||||||
|
|
||||||
|
const escapeForRegExp = (s: string) => s.replace (/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
|
||||||
|
|
||||||
|
export default (pageNames: string[], basePath = '/wiki'): ((tree: Root) => void) => {
|
||||||
|
const names = [...pageNames].sort ((a, b) => b.length - a.length)
|
||||||
|
|
||||||
|
if (names.length === 0)
|
||||||
|
{
|
||||||
|
return () => {
|
||||||
|
;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const re = new RegExp (`(${ names.map (escapeForRegExp).join ('|') })`, 'g')
|
||||||
|
|
||||||
|
return (tree: Root) => {
|
||||||
|
const edits: { parent: Parent; index: number; parts: RootContent[] }[] = []
|
||||||
|
|
||||||
|
const walk = (node: Content | Root, ancestors: Parent[]) => {
|
||||||
|
if (!(node) || (typeof node !== 'object'))
|
||||||
|
return
|
||||||
|
|
||||||
|
if (!(ancestors.some (ancestor => ['link',
|
||||||
|
'linkReference',
|
||||||
|
'image',
|
||||||
|
'imageReference',
|
||||||
|
'code',
|
||||||
|
'inlineCode'].includes (ancestor?.type)))
|
||||||
|
&& (node.type === 'text'))
|
||||||
|
{
|
||||||
|
const value = node.value ?? ''
|
||||||
|
if (value)
|
||||||
|
{
|
||||||
|
re.lastIndex = 0
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
let last = 0
|
||||||
|
const parts: RootContent[] = []
|
||||||
|
|
||||||
|
while (m = re.exec (value))
|
||||||
|
{
|
||||||
|
const start = m.index
|
||||||
|
const end = start + m[0].length
|
||||||
|
|
||||||
|
if (start > last)
|
||||||
|
parts.push ({ type: 'text', value: value.slice (last, start) })
|
||||||
|
|
||||||
|
const name = m[1]
|
||||||
|
parts.push ({ type: 'link',
|
||||||
|
url: `${ basePath }/${ encodeURIComponent (name) }`,
|
||||||
|
title: null,
|
||||||
|
children: [{ type: 'text', value: name }],
|
||||||
|
data: { hProperties: { 'data-wiki': '1' } } })
|
||||||
|
last = end
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parts.length)
|
||||||
|
{
|
||||||
|
if (last < value.length)
|
||||||
|
parts.push ({ type: 'text', value: value.slice (last) })
|
||||||
|
const parent = ancestors[ancestors.length - 1]
|
||||||
|
if (parent && Array.isArray (parent.children))
|
||||||
|
{
|
||||||
|
const index = parent.children.indexOf (node)
|
||||||
|
if (index >= 0)
|
||||||
|
edits.push ({ parent, index, parts })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const maybeChidren = (node as any).children
|
||||||
|
if (Array.isArray (maybeChidren))
|
||||||
|
{
|
||||||
|
const parent = node as Parent
|
||||||
|
|
||||||
|
for (let i = 0; i < maybeChidren.length; ++i)
|
||||||
|
{
|
||||||
|
const child: Content | undefined = maybeChidren[i]
|
||||||
|
if (!(child))
|
||||||
|
continue
|
||||||
|
walk (child, ancestors.concat (parent))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
walk (tree, [])
|
||||||
|
|
||||||
|
for (let i = edits.length - 1; i >= 0; --i)
|
||||||
|
{
|
||||||
|
const { parent, index, parts } = edits[i]
|
||||||
|
|
||||||
|
if (!(parent) || !(Array.isArray (parent.children)))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (0 <= index && index < parent.children.length)
|
||||||
|
parent.children.splice (index, 1, ...parts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ export default () => {
|
|||||||
if (/^\d+$/.test (title))
|
if (/^\d+$/.test (title))
|
||||||
{
|
{
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
setWikiPage (undefined)
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const res = await axios.get (`${ API_BASE_URL }/wiki/${ title }`)
|
const res = await axios.get (`${ API_BASE_URL }/wiki/${ title }`)
|
||||||
@@ -52,6 +53,7 @@ export default () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
setWikiPage (undefined)
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const res = await axios.get (
|
const res = await axios.get (
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import Forbidden from '@/pages/Forbidden'
|
|||||||
|
|
||||||
import 'react-markdown-editor-lite/lib/index.css'
|
import 'react-markdown-editor-lite/lib/index.css'
|
||||||
|
|
||||||
|
import type { FC } from 'react'
|
||||||
|
|
||||||
import type { User, WikiPage } from '@/types'
|
import type { User, WikiPage } from '@/types'
|
||||||
|
|
||||||
const mdParser = new MarkdownIt
|
const mdParser = new MarkdownIt
|
||||||
@@ -19,7 +21,7 @@ const mdParser = new MarkdownIt
|
|||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
|
|
||||||
export default ({ user }: Props) => {
|
export default (({ user }: Props) => {
|
||||||
if (!(['admin', 'member'].some (r => user?.role === r)))
|
if (!(['admin', 'member'].some (r => user?.role === r)))
|
||||||
return <Forbidden/>
|
return <Forbidden/>
|
||||||
|
|
||||||
@@ -27,8 +29,9 @@ export default ({ user }: Props) => {
|
|||||||
|
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
const [title, setTitle] = useState ('')
|
|
||||||
const [body, setBody] = useState ('')
|
const [body, setBody] = useState ('')
|
||||||
|
const [loading, setLoading] = useState (true)
|
||||||
|
const [title, setTitle] = useState ('')
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const formData = new FormData ()
|
const formData = new FormData ()
|
||||||
@@ -51,10 +54,12 @@ export default ({ user }: Props) => {
|
|||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
setLoading (true)
|
||||||
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }`)
|
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }`)
|
||||||
const data = res.data as WikiPage
|
const data = res.data as WikiPage
|
||||||
setTitle (data.title)
|
setTitle (data.title)
|
||||||
setBody (data.body)
|
setBody (data.body)
|
||||||
|
setLoading (false)
|
||||||
}) ()
|
}) ()
|
||||||
}, [id])
|
}, [id])
|
||||||
|
|
||||||
@@ -66,30 +71,33 @@ export default ({ user }: Props) => {
|
|||||||
<div className="max-w-xl mx-auto p-4 space-y-4">
|
<div className="max-w-xl mx-auto p-4 space-y-4">
|
||||||
<h1 className="text-2xl font-bold mb-2">Wiki ページを編輯</h1>
|
<h1 className="text-2xl font-bold mb-2">Wiki ページを編輯</h1>
|
||||||
|
|
||||||
{/* タイトル */}
|
{loading ? 'Loading...' : (
|
||||||
{/* TODO: タグ補完 */}
|
<>
|
||||||
<div>
|
{/* タイトル */}
|
||||||
<label className="block font-semibold mb-1">タイトル</label>
|
{/* TODO: タグ補完 */}
|
||||||
<input type="text"
|
<div>
|
||||||
value={title}
|
<label className="block font-semibold mb-1">タイトル</label>
|
||||||
onChange={e => setTitle (e.target.value)}
|
<input type="text"
|
||||||
className="w-full border p-2 rounded"/>
|
value={title}
|
||||||
</div>
|
onChange={e => setTitle (e.target.value)}
|
||||||
|
className="w-full border p-2 rounded"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* 本文 */}
|
{/* 本文 */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block font-semibold mb-1">本文</label>
|
<label className="block font-semibold mb-1">本文</label>
|
||||||
<MdEditor value={body}
|
<MdEditor value={body}
|
||||||
style={{ height: '500px' }}
|
style={{ height: '500px' }}
|
||||||
renderHTML={text => mdParser.render (text)}
|
renderHTML={text => mdParser.render (text)}
|
||||||
onChange={({ text }) => setBody (text)}/>
|
onChange={({ text }) => setBody (text)}/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<button onClick={handleSubmit}
|
<button onClick={handleSubmit}
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
|
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
|
||||||
追加
|
編輯
|
||||||
</button>
|
</button>
|
||||||
|
</>)}
|
||||||
</div>
|
</div>
|
||||||
</MainArea>)
|
</MainArea>)
|
||||||
}
|
}) satisfies FC<Props>
|
||||||
|
|||||||
Reference in New Issue
Block a user