ぼざクリタグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

279 lines
8.2 KiB

  1. class PostsController < ApplicationController
  2. Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
  3. def index
  4. page = (params[:page].presence || 1).to_i
  5. limit = (params[:limit].presence || 20).to_i
  6. cursor = params[:cursor].presence
  7. page = 1 if page < 1
  8. limit = 1 if limit < 1
  9. offset = (page - 1) * limit
  10. sort_sql =
  11. 'COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
  12. 'posts.original_created_from,' +
  13. 'posts.created_at)'
  14. q =
  15. filtered_posts
  16. .preload(tags: :tag_name)
  17. .with_attached_thumbnail
  18. .select("posts.*, #{ sort_sql } AS sort_ts")
  19. .order(Arel.sql("#{ sort_sql } DESC"))
  20. posts = (
  21. if cursor
  22. q.where("#{ sort_sql } < ?", Time.iso8601(cursor)).limit(limit + 1)
  23. else
  24. q.limit(limit).offset(offset)
  25. end).to_a
  26. next_cursor = nil
  27. if cursor && posts.length > limit
  28. next_cursor = posts.last.read_attribute('sort_ts').iso8601(6)
  29. posts = posts.first(limit)
  30. end
  31. render json: { posts: posts.map { |post|
  32. post.as_json(include: { tags: { only: [:id, :category, :post_count],
  33. methods: [:name, :has_wiki] } }).tap do |json|
  34. json['thumbnail'] =
  35. if post.thumbnail.attached?
  36. rails_storage_proxy_url(post.thumbnail, only_path: false)
  37. else
  38. nil
  39. end
  40. end
  41. }, count: if filtered_posts.group_values.present?
  42. filtered_posts.count.size
  43. else
  44. filtered_posts.count
  45. end, next_cursor: }
  46. end
  47. def random
  48. post = filtered_posts.preload(tags: :tag_name).order('RAND()').first
  49. return head :not_found unless post
  50. viewed = current_user&.viewed?(post) || false
  51. render json: (post
  52. .as_json(include: { tags: { only: [:id, :category, :post_count],
  53. methods: [:name, :has_wiki] } })
  54. .merge(viewed:))
  55. end
  56. def show
  57. post = Post.includes(tags: :tag_name).find(params[:id])
  58. return head :not_found unless post
  59. viewed = current_user&.viewed?(post) || false
  60. json = post.as_json
  61. json['tags'] = build_tag_tree_for(post.tags)
  62. json['related'] = post.related(limit: 20)
  63. json['viewed'] = viewed
  64. render json:
  65. end
  66. def create
  67. return head :unauthorized unless current_user
  68. return head :forbidden unless current_user.member?
  69. # TODO: サイトに応じて thumbnail_base 設定
  70. title = params[:title].presence
  71. url = params[:url]
  72. thumbnail = params[:thumbnail]
  73. tag_names = params[:tags].to_s.split(' ')
  74. original_created_from = params[:original_created_from]
  75. original_created_before = params[:original_created_before]
  76. post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
  77. original_created_from:, original_created_before:)
  78. post.thumbnail.attach(thumbnail)
  79. if post.save
  80. post.resized_thumbnail!
  81. tags = Tag.normalise_tags(tag_names)
  82. tags = Tag.expand_parent_tags(tags)
  83. sync_post_tags!(post, tags)
  84. render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
  85. methods: [:name, :has_wiki] } }),
  86. status: :created
  87. else
  88. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  89. end
  90. rescue Tag::NicoTagNormalisationError
  91. head :bad_request
  92. end
  93. def viewed
  94. return head :unauthorized unless current_user
  95. current_user.viewed_posts << Post.find(params[:id])
  96. head :no_content
  97. end
  98. def unviewed
  99. return head :unauthorized unless current_user
  100. current_user.viewed_posts.delete(Post.find(params[:id]))
  101. head :no_content
  102. end
  103. def update
  104. return head :unauthorized unless current_user
  105. return head :forbidden unless current_user.member?
  106. title = params[:title].presence
  107. tag_names = params[:tags].to_s.split(' ')
  108. original_created_from = params[:original_created_from]
  109. original_created_before = params[:original_created_before]
  110. post = Post.find(params[:id].to_i)
  111. if post.update(title:, original_created_from:, original_created_before:)
  112. tags = post.tags.where(category: 'nico').to_a +
  113. Tag.normalise_tags(tag_names, with_tagme: false)
  114. tags = Tag.expand_parent_tags(tags)
  115. sync_post_tags!(post, tags)
  116. json = post.as_json
  117. json['tags'] = build_tag_tree_for(post.tags)
  118. render json:, status: :ok
  119. else
  120. render json: post.errors, status: :unprocessable_entity
  121. end
  122. rescue Tag::NicoTagNormalisationError
  123. head :bad_request
  124. end
  125. def changes
  126. id = params[:id]
  127. page = (params[:page].presence || 1).to_i
  128. limit = (params[:limit].presence || 20).to_i
  129. page = 1 if page < 1
  130. limit = 1 if limit < 1
  131. offset = (page - 1) * limit
  132. pts = PostTag.with_discarded
  133. pts = pts.where(post_id: id) if id.present?
  134. pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
  135. events = []
  136. pts.each do |pt|
  137. events << Event.new(
  138. post: pt.post,
  139. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  140. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  141. change_type: 'add',
  142. timestamp: pt.created_at)
  143. if pt.discarded_at
  144. events << Event.new(
  145. post: pt.post,
  146. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  147. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  148. change_type: 'remove',
  149. timestamp: pt.discarded_at)
  150. end
  151. end
  152. events.sort_by!(&:timestamp)
  153. events.reverse!
  154. render json: { changes: events.slice(offset, limit).as_json, count: events.size }
  155. end
  156. private
  157. def filtered_posts
  158. tag_names = params[:tags].to_s.split(' ')
  159. match_type = params[:match]
  160. if tag_names.present?
  161. filter_posts_by_tags(tag_names, match_type)
  162. else
  163. Post.all
  164. end
  165. end
  166. def filter_posts_by_tags tag_names, match_type
  167. posts = Post.joins(tags: :tag_name)
  168. if match_type == 'any'
  169. posts.where(tag_names: { name: tag_names }).distinct
  170. else
  171. posts.where(tag_names: { name: tag_names })
  172. .group('posts.id')
  173. .having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
  174. end
  175. end
  176. def sync_post_tags! post, desired_tags
  177. desired_tags.each do |t|
  178. t.save! if t.new_record?
  179. end
  180. desired_ids = desired_tags.map(&:id).to_set
  181. current_ids = post.tags.pluck(:id).to_set
  182. to_add = desired_ids - current_ids
  183. to_remove = current_ids - desired_ids
  184. Tag.where(id: to_add).find_each do |tag|
  185. begin
  186. PostTag.create!(post:, tag:, created_user: current_user)
  187. rescue ActiveRecord::RecordNotUnique
  188. ;
  189. end
  190. end
  191. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  192. pt.discard_by!(current_user)
  193. end
  194. end
  195. def build_tag_tree_for tags
  196. tags = tags.to_a
  197. tag_ids = tags.map(&:id)
  198. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  199. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  200. implications.each do |imp|
  201. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  202. end
  203. child_ids = children_ids_by_parent.values.flatten.uniq
  204. root_ids = tag_ids - child_ids
  205. tags_by_id = tags.index_by(&:id)
  206. memo = { }
  207. build_node = -> tag_id, path do
  208. tag = tags_by_id[tag_id]
  209. return nil unless tag
  210. if path.include?(tag_id)
  211. return tag.as_json(only: [:id, :category, :post_count],
  212. methods: [:name, :has_wiki]).merge(children: [])
  213. end
  214. if memo.key?(tag_id)
  215. return memo[tag_id]
  216. end
  217. new_path = path + [tag_id]
  218. child_ids = children_ids_by_parent[tag_id] || []
  219. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  220. memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
  221. methods: [:name, :has_wiki]).merge(children:)
  222. end
  223. root_ids.filter_map { |id| build_node.call(id, []) }
  224. end
  225. end