ぼざクリタグ広場 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.
 
 
 
 
 
 

285 lines
8.3 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. post.reload
  85. render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
  86. methods: [:name, :has_wiki] } }),
  87. status: :created
  88. else
  89. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  90. end
  91. rescue Tag::NicoTagNormalisationError
  92. head :bad_request
  93. end
  94. def viewed
  95. return head :unauthorized unless current_user
  96. current_user.viewed_posts << Post.find(params[:id])
  97. head :no_content
  98. end
  99. def unviewed
  100. return head :unauthorized unless current_user
  101. current_user.viewed_posts.delete(Post.find(params[:id]))
  102. head :no_content
  103. end
  104. def update
  105. return head :unauthorized unless current_user
  106. return head :forbidden unless current_user.member?
  107. title = params[:title].presence
  108. tag_names = params[:tags].to_s.split(' ')
  109. original_created_from = params[:original_created_from]
  110. original_created_before = params[:original_created_before]
  111. post = Post.find(params[:id].to_i)
  112. if post.update(title:, original_created_from:, original_created_before:)
  113. tags = post.tags.where(category: 'nico').to_a +
  114. Tag.normalise_tags(tag_names, with_tagme: false)
  115. tags = Tag.expand_parent_tags(tags)
  116. sync_post_tags!(post, tags)
  117. post.reload
  118. json = post.as_json
  119. json['tags'] = build_tag_tree_for(post.tags)
  120. render json:, status: :ok
  121. else
  122. render json: post.errors, status: :unprocessable_entity
  123. end
  124. rescue Tag::NicoTagNormalisationError
  125. head :bad_request
  126. end
  127. def changes
  128. id = params[:id]
  129. page = (params[:page].presence || 1).to_i
  130. limit = (params[:limit].presence || 20).to_i
  131. page = 1 if page < 1
  132. limit = 1 if limit < 1
  133. offset = (page - 1) * limit
  134. pts = PostTag.with_discarded
  135. pts = pts.where(post_id: id) if id.present?
  136. pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
  137. events = []
  138. pts.each do |pt|
  139. events << Event.new(
  140. post: pt.post,
  141. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  142. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  143. change_type: 'add',
  144. timestamp: pt.created_at)
  145. if pt.discarded_at
  146. events << Event.new(
  147. post: pt.post,
  148. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  149. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  150. change_type: 'remove',
  151. timestamp: pt.discarded_at)
  152. end
  153. end
  154. events.sort_by!(&:timestamp)
  155. events.reverse!
  156. render json: { changes: events.slice(offset, limit).as_json, count: events.size }
  157. end
  158. private
  159. def filtered_posts
  160. tag_names = params[:tags].to_s.split(' ')
  161. match_type = params[:match]
  162. if tag_names.present?
  163. filter_posts_by_tags(tag_names, match_type)
  164. else
  165. Post.all
  166. end
  167. end
  168. def filter_posts_by_tags tag_names, match_type
  169. tag_names = TagName.canonicalise(tag_names)
  170. posts = Post.joins(tags: :tag_name)
  171. if match_type == 'any'
  172. posts.where(tag_names: { name: tag_names }).distinct
  173. else
  174. posts.where(tag_names: { name: tag_names })
  175. .group('posts.id')
  176. .having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
  177. end
  178. end
  179. def sync_post_tags! post, desired_tags
  180. desired_tags.each do |t|
  181. t.save! if t.new_record?
  182. end
  183. desired_ids = desired_tags.map(&:id).to_set
  184. current_ids = post.tags.pluck(:id).to_set
  185. to_add = desired_ids - current_ids
  186. to_remove = current_ids - desired_ids
  187. Tag.where(id: to_add).find_each do |tag|
  188. begin
  189. PostTag.create!(post:, tag:, created_user: current_user)
  190. rescue ActiveRecord::RecordNotUnique
  191. ;
  192. end
  193. end
  194. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  195. pt.discard_by!(current_user)
  196. end
  197. end
  198. def build_tag_tree_for tags
  199. tags = tags.to_a
  200. tag_ids = tags.map(&:id)
  201. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  202. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  203. implications.each do |imp|
  204. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  205. end
  206. child_ids = children_ids_by_parent.values.flatten.uniq
  207. root_ids = tag_ids - child_ids
  208. tags_by_id = tags.index_by(&:id)
  209. memo = { }
  210. build_node = -> tag_id, path do
  211. tag = tags_by_id[tag_id]
  212. return nil unless tag
  213. if path.include?(tag_id)
  214. return tag.as_json(only: [:id, :category, :post_count],
  215. methods: [:name, :has_wiki]).merge(children: [])
  216. end
  217. if memo.key?(tag_id)
  218. return memo[tag_id]
  219. end
  220. new_path = path + [tag_id]
  221. child_ids = children_ids_by_parent[tag_id] || []
  222. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  223. memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
  224. methods: [:name, :has_wiki]).merge(children:)
  225. end
  226. root_ids.filter_map { |id| build_node.call(id, []) }
  227. end
  228. end