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

273 lines
7.9 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] } }).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: filtered_posts.count(:id), next_cursor: }
  42. end
  43. def random
  44. post = filtered_posts.preload(tags: :tag_name).order('RAND()').first
  45. return head :not_found unless post
  46. viewed = current_user&.viewed?(post) || false
  47. render json: (post
  48. .as_json(include: { tags: { only: [:id, :category, :post_count],
  49. methods: [:name] } })
  50. .merge(viewed:))
  51. end
  52. def show
  53. post = Post.includes(tags: :tag_name).find(params[:id])
  54. return head :not_found unless post
  55. viewed = current_user&.viewed?(post) || false
  56. json = post.as_json
  57. json['tags'] = build_tag_tree_for(post.tags)
  58. json['related'] = post.related(limit: 20)
  59. json['viewed'] = viewed
  60. render json:
  61. end
  62. def create
  63. return head :unauthorized unless current_user
  64. return head :forbidden unless current_user.member?
  65. # TODO: URL が正規のものがチェック,不正ならエラー
  66. # TODO: URL は必須にする(タイトルは省略可).
  67. # TODO: サイトに応じて thumbnail_base 設定
  68. title = params[:title]
  69. url = params[:url]
  70. thumbnail = params[:thumbnail]
  71. tag_names = params[:tags].to_s.split(' ')
  72. original_created_from = params[:original_created_from]
  73. original_created_before = params[:original_created_before]
  74. post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
  75. original_created_from:, original_created_before:)
  76. post.thumbnail.attach(thumbnail)
  77. if post.save
  78. post.resized_thumbnail!
  79. tags = Tag.normalise_tags(tag_names)
  80. tags = Tag.expand_parent_tags(tags)
  81. sync_post_tags!(post, tags)
  82. render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
  83. methods: [:name] } }),
  84. status: :created
  85. else
  86. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  87. end
  88. end
  89. def viewed
  90. return head :unauthorized unless current_user
  91. current_user.viewed_posts << Post.find(params[:id])
  92. head :no_content
  93. end
  94. def unviewed
  95. return head :unauthorized unless current_user
  96. current_user.viewed_posts.delete(Post.find(params[:id]))
  97. head :no_content
  98. end
  99. def update
  100. return head :unauthorized unless current_user
  101. return head :forbidden unless current_user.member?
  102. title = params[:title]
  103. tag_names = params[:tags].to_s.split(' ')
  104. original_created_from = params[:original_created_from]
  105. original_created_before = params[:original_created_before]
  106. post = Post.find(params[:id].to_i)
  107. if post.update(title:, original_created_from:, original_created_before:)
  108. tags = post.tags.where(category: 'nico').to_a +
  109. Tag.normalise_tags(tag_names, with_tagme: false)
  110. tags = Tag.expand_parent_tags(tags)
  111. sync_post_tags!(post, tags)
  112. json = post.as_json
  113. json['tags'] = build_tag_tree_for(post.tags)
  114. render json:, status: :ok
  115. else
  116. render json: post.errors, status: :unprocessable_entity
  117. end
  118. end
  119. def changes
  120. id = params[:id]
  121. page = (params[:page].presence || 1).to_i
  122. limit = (params[:limit].presence || 20).to_i
  123. page = 1 if page < 1
  124. limit = 1 if limit < 1
  125. offset = (page - 1) * limit
  126. pts = PostTag.with_discarded
  127. pts = pts.where(post_id: id) if id.present?
  128. pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
  129. events = []
  130. pts.each do |pt|
  131. events << Event.new(
  132. post: pt.post,
  133. tag: pt.tag,
  134. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  135. change_type: 'add',
  136. timestamp: pt.created_at)
  137. if pt.discarded_at
  138. events << Event.new(
  139. post: pt.post,
  140. tag: pt.tag,
  141. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  142. change_type: 'remove',
  143. timestamp: pt.discarded_at)
  144. end
  145. end
  146. events.sort_by!(&:timestamp)
  147. events.reverse!
  148. render json: { changes: events.slice(offset, limit).as_json, count: events.size }
  149. end
  150. private
  151. def filtered_posts
  152. tag_names = params[:tags]&.split(' ')
  153. match_type = params[:match]
  154. if tag_names.present?
  155. filter_posts_by_tags(tag_names, match_type)
  156. else
  157. Post.all
  158. end
  159. end
  160. def filter_posts_by_tags tag_names, match_type
  161. posts = Post.joins(tags: :tag_name)
  162. if match_type == 'any'
  163. posts.where(tag_names: { name: tag_names }).distinct
  164. else
  165. posts.where(tag_names: { name: tag_names })
  166. .group('posts.id')
  167. .having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
  168. end
  169. end
  170. def sync_post_tags! post, desired_tags
  171. desired_tags.each do |t|
  172. t.save! if t.new_record?
  173. end
  174. desired_ids = desired_tags.map(&:id).to_set
  175. current_ids = post.tags.pluck(:id).to_set
  176. to_add = desired_ids - current_ids
  177. to_remove = current_ids - desired_ids
  178. Tag.where(id: to_add).find_each do |tag|
  179. begin
  180. PostTag.create!(post:, tag:, created_user: current_user)
  181. rescue ActiveRecord::RecordNotUnique
  182. ;
  183. end
  184. end
  185. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  186. pt.discard_by!(current_user)
  187. end
  188. end
  189. def build_tag_tree_for tags
  190. tags = tags.to_a
  191. tag_ids = tags.map(&:id)
  192. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  193. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  194. implications.each do |imp|
  195. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  196. end
  197. child_ids = children_ids_by_parent.values.flatten.uniq
  198. root_ids = tag_ids - child_ids
  199. tags_by_id = tags.index_by(&:id)
  200. memo = { }
  201. build_node = -> tag_id, path do
  202. tag = tags_by_id[tag_id]
  203. return nil unless tag
  204. if path.include?(tag_id)
  205. return tag.as_json(only: [:id, :category, :post_count],
  206. methods: [:name]).merge(children: [])
  207. end
  208. if memo.key?(tag_id)
  209. return memo[tag_id]
  210. end
  211. new_path = path + [tag_id]
  212. child_ids = children_ids_by_parent[tag_id] || []
  213. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  214. memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
  215. methods: [:name]).merge(children:)
  216. end
  217. root_ids.filter_map { |id| build_node.call(id, []) }
  218. end
  219. end