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

277 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: URL が正規のものがチェック,不正ならエラー
  70. # TODO: URL は必須にする(タイトルは省略可).
  71. # TODO: サイトに応じて thumbnail_base 設定
  72. title = params[:title].presence
  73. url = params[:url]
  74. thumbnail = params[:thumbnail]
  75. tag_names = params[:tags].to_s.split(' ')
  76. original_created_from = params[:original_created_from]
  77. original_created_before = params[:original_created_before]
  78. post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
  79. original_created_from:, original_created_before:)
  80. post.thumbnail.attach(thumbnail)
  81. if post.save
  82. post.resized_thumbnail!
  83. tags = Tag.normalise_tags(tag_names)
  84. tags = Tag.expand_parent_tags(tags)
  85. sync_post_tags!(post, tags)
  86. render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
  87. methods: [:name, :has_wiki] } }),
  88. status: :created
  89. else
  90. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  91. end
  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. end
  123. def changes
  124. id = params[:id]
  125. page = (params[:page].presence || 1).to_i
  126. limit = (params[:limit].presence || 20).to_i
  127. page = 1 if page < 1
  128. limit = 1 if limit < 1
  129. offset = (page - 1) * limit
  130. pts = PostTag.with_discarded
  131. pts = pts.where(post_id: id) if id.present?
  132. pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
  133. events = []
  134. pts.each do |pt|
  135. events << Event.new(
  136. post: pt.post,
  137. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  138. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  139. change_type: 'add',
  140. timestamp: pt.created_at)
  141. if pt.discarded_at
  142. events << Event.new(
  143. post: pt.post,
  144. tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
  145. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  146. change_type: 'remove',
  147. timestamp: pt.discarded_at)
  148. end
  149. end
  150. events.sort_by!(&:timestamp)
  151. events.reverse!
  152. render json: { changes: events.slice(offset, limit).as_json, count: events.size }
  153. end
  154. private
  155. def filtered_posts
  156. tag_names = params[:tags].to_s.split(' ')
  157. match_type = params[:match]
  158. if tag_names.present?
  159. filter_posts_by_tags(tag_names, match_type)
  160. else
  161. Post.all
  162. end
  163. end
  164. def filter_posts_by_tags tag_names, match_type
  165. posts = Post.joins(tags: :tag_name)
  166. if match_type == 'any'
  167. posts.where(tag_names: { name: tag_names }).distinct
  168. else
  169. posts.where(tag_names: { name: tag_names })
  170. .group('posts.id')
  171. .having('COUNT(DISTINCT tag_names.id) = ?', tag_names.uniq.size)
  172. end
  173. end
  174. def sync_post_tags! post, desired_tags
  175. desired_tags.each do |t|
  176. t.save! if t.new_record?
  177. end
  178. desired_ids = desired_tags.map(&:id).to_set
  179. current_ids = post.tags.pluck(:id).to_set
  180. to_add = desired_ids - current_ids
  181. to_remove = current_ids - desired_ids
  182. Tag.where(id: to_add).find_each do |tag|
  183. begin
  184. PostTag.create!(post:, tag:, created_user: current_user)
  185. rescue ActiveRecord::RecordNotUnique
  186. ;
  187. end
  188. end
  189. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  190. pt.discard_by!(current_user)
  191. end
  192. end
  193. def build_tag_tree_for tags
  194. tags = tags.to_a
  195. tag_ids = tags.map(&:id)
  196. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  197. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  198. implications.each do |imp|
  199. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  200. end
  201. child_ids = children_ids_by_parent.values.flatten.uniq
  202. root_ids = tag_ids - child_ids
  203. tags_by_id = tags.index_by(&:id)
  204. memo = { }
  205. build_node = -> tag_id, path do
  206. tag = tags_by_id[tag_id]
  207. return nil unless tag
  208. if path.include?(tag_id)
  209. return tag.as_json(only: [:id, :category, :post_count],
  210. methods: [:name, :has_wiki]).merge(children: [])
  211. end
  212. if memo.key?(tag_id)
  213. return memo[tag_id]
  214. end
  215. new_path = path + [tag_id]
  216. child_ids = children_ids_by_parent[tag_id] || []
  217. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  218. memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
  219. methods: [:name, :has_wiki]).merge(children:)
  220. end
  221. root_ids.filter_map { |id| build_node.call(id, []) }
  222. end
  223. end