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

642 lines
21 KiB

  1. class PostsController < ApplicationController
  2. Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
  3. def index
  4. url = params[:url].presence
  5. title = params[:title].presence
  6. original_created_from = params[:original_created_from].presence
  7. original_created_to = params[:original_created_to].presence
  8. created_between = params[:created_from].presence, params[:created_to].presence
  9. updated_between = params[:updated_from].presence, params[:updated_to].presence
  10. order = params[:order].to_s.split(':', 2).map(&:strip)
  11. unless order[0].in?(['title', 'url', 'original_created_at', 'created_at', 'updated_at'])
  12. order[0] = 'original_created_at'
  13. end
  14. unless order[1].in?(['asc', 'desc'])
  15. order[1] =
  16. if order[0].in?(['title', 'url'])
  17. 'asc'
  18. else
  19. 'desc'
  20. end
  21. end
  22. page = (params[:page].presence || 1).to_i
  23. limit = (params[:limit].presence || 20).to_i
  24. page = 1 if page < 1
  25. limit = 1 if limit < 1
  26. offset = (page - 1) * limit
  27. pt_max_sql =
  28. PostTag
  29. .select('post_id, MAX(updated_at) AS max_updated_at')
  30. .group('post_id')
  31. .to_sql
  32. updated_at_all_sql =
  33. 'GREATEST(posts.updated_at,' +
  34. 'COALESCE(pt_max.max_updated_at, posts.updated_at))'
  35. q =
  36. filtered_posts
  37. .joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
  38. .reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
  39. .preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
  40. .with_attached_thumbnail
  41. q = q.where('posts.url LIKE ?', "%#{ url }%") if url
  42. q = q.where('posts.title LIKE ?', "%#{ title }%") if title
  43. if original_created_from
  44. q = q.where('posts.original_created_before > ?', original_created_from)
  45. end
  46. if original_created_to
  47. q = q.where('posts.original_created_from <= ?', original_created_to)
  48. end
  49. q = q.where('posts.created_at >= ?', created_between[0]) if created_between[0]
  50. q = q.where('posts.created_at <= ?', created_between[1]) if created_between[1]
  51. if updated_between[0]
  52. q = q.where("#{ updated_at_all_sql } >= ?", updated_between[0])
  53. end
  54. if updated_between[1]
  55. q = q.where("#{ updated_at_all_sql } <= ?", updated_between[1])
  56. end
  57. sort_sql =
  58. case order[0]
  59. when 'original_created_at'
  60. 'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE,' +
  61. 'posts.original_created_from,' +
  62. 'posts.created_at) '
  63. when 'updated_at'
  64. updated_at_all_sql
  65. else
  66. "posts.#{ order[0] }"
  67. end
  68. posts = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, posts.id #{ order[1] }"))
  69. .limit(limit)
  70. .offset(offset)
  71. .to_a
  72. q = q.except(:select, :order)
  73. render json: { posts: posts.map { |post|
  74. PostRepr.base(post).merge(updated_at: post.updated_at_all).tap do |json|
  75. json['thumbnail'] =
  76. if post.thumbnail.attached?
  77. rails_storage_proxy_url(post.thumbnail, only_path: false)
  78. else
  79. nil
  80. end
  81. end
  82. }, count: q.group_values.present? ? q.count.size : q.count }
  83. end
  84. def random
  85. post = filtered_posts.preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
  86. .order('RAND()')
  87. .first
  88. return head :not_found unless post
  89. render json: PostRepr.base(post, current_user)
  90. end
  91. def show
  92. post = Post.includes(tags: [:deerjikists, :materials, { tag_name: :wiki_page }]).find_by(id: params[:id])
  93. return head :not_found unless post
  94. render json: PostRepr.base(post, current_user)
  95. .merge(tags: build_tag_tree_for(post.tags),
  96. related: PostRepr.many(post.related(limit: 20)))
  97. end
  98. def create
  99. return head :unauthorized unless current_user
  100. return head :forbidden unless current_user.gte_member?
  101. # TODO: サイトに応じて thumbnail_base 設定
  102. title = params[:title].presence
  103. url = params[:url]
  104. thumbnail = params[:thumbnail]
  105. tag_names = params[:tags].to_s.split
  106. original_created_from = params[:original_created_from]
  107. original_created_before = params[:original_created_before]
  108. parent_post_ids = parse_parent_post_ids
  109. post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
  110. original_created_from:, original_created_before:)
  111. post.thumbnail.attach(thumbnail) if thumbnail.present?
  112. ApplicationRecord.transaction do
  113. post.save!
  114. tags = Tag.normalise_tags!(tag_names)
  115. TagVersioning.record_tag_snapshots!(tags, created_by_user: current_user)
  116. tags = Tag.expand_parent_tags(tags)
  117. sync_post_tags!(post, tags)
  118. sync_parent_posts!(post, parent_post_ids)
  119. post.resized_thumbnail!
  120. PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user)
  121. end
  122. post.reload
  123. render json: PostRepr.base(post), status: :created
  124. rescue Tag::NicoTagNormalisationError
  125. head :bad_request
  126. rescue ArgumentError => e
  127. render json: { errors: [e.message] }, status: :unprocessable_entity
  128. rescue ActiveRecord::RecordInvalid => e
  129. render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
  130. end
  131. def viewed
  132. return head :unauthorized unless current_user
  133. current_user.viewed_posts << Post.find(params[:id])
  134. head :no_content
  135. end
  136. def unviewed
  137. return head :unauthorized unless current_user
  138. current_user.viewed_posts.delete(Post.find(params[:id]))
  139. head :no_content
  140. end
  141. def update
  142. return head :unauthorized unless current_user
  143. return head :forbidden unless current_user.gte_member?
  144. force = bool?(:force)
  145. merge = bool?(:merge)
  146. return head :bad_request if force && merge
  147. base_version_no = nil
  148. base_version_no = parse_base_version_no unless force
  149. title = params[:title].presence
  150. tag_names = params[:tags].to_s.split
  151. original_created_from = params[:original_created_from]
  152. original_created_before = params[:original_created_before]
  153. parent_post_ids = parse_parent_post_ids
  154. post = nil
  155. conflict_json = nil
  156. ApplicationRecord.transaction do
  157. post = Post.lock.find(params[:id].to_i)
  158. base_version = nil
  159. base_snapshot = nil
  160. current_snapshot = nil
  161. unless force
  162. base_version = post.post_versions.find_by!(version_no: base_version_no)
  163. base_snapshot = post_snapshot_from_version(base_version)
  164. current_snapshot = post_snapshot_from_record(post)
  165. end
  166. incoming_snapshot = post_incoming_snapshot(title:,
  167. original_created_from:,
  168. original_created_before:,
  169. tag_names:,
  170. parent_post_ids:)
  171. snapshot_to_apply =
  172. if force || post.version_no == base_version_no || current_snapshot == base_snapshot
  173. incoming_snapshot
  174. else
  175. changes = post_snapshot_changes(base_snapshot, current_snapshot, incoming_snapshot)
  176. conflicts = changes.select { |change| change[:conflict] }
  177. if merge && conflicts.empty?
  178. merge_post_snapshots(base_snapshot, current_snapshot, incoming_snapshot)
  179. else
  180. conflict_json = post_conflict_json(post:,
  181. base_version_no:,
  182. base_snapshot:,
  183. current_snapshot:,
  184. incoming_snapshot:,
  185. changes:,
  186. conflicts:)
  187. raise ActiveRecord::Rollback
  188. end
  189. end
  190. apply_post_snapshot!(post, snapshot_to_apply)
  191. end
  192. return render json: conflict_json, status: :conflict if conflict_json
  193. post.reload
  194. json = PostRepr.base(post, current_user)
  195. json['tags'] = build_tag_tree_for(post.tags)
  196. render json:, status: :ok
  197. rescue Tag::NicoTagNormalisationError
  198. head :bad_request
  199. rescue ArgumentError => e
  200. render json: { errors: [e.message] }, status: :unprocessable_entity
  201. rescue ActiveRecord::RecordInvalid => e
  202. render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
  203. end
  204. def changes
  205. id = params[:id].presence
  206. tag_id = params[:tag].presence
  207. page = (params[:page].presence || 1).to_i
  208. limit = (params[:limit].presence || 20).to_i
  209. page = 1 if page < 1
  210. limit = 1 if limit < 1
  211. offset = (page - 1) * limit
  212. pts = PostTag.with_discarded
  213. pts = pts.where(post_id: id) if id.present?
  214. pts = pts.where(tag_id:) if tag_id.present?
  215. pts = pts.includes(:post, :created_user, :deleted_user,
  216. tag: [:deerjikists, :materials, { tag_name: :wiki_page }])
  217. events = []
  218. pts.each do |pt|
  219. tag = TagRepr.base(pt.tag)
  220. post = pt.post
  221. events << Event.new(
  222. post:,
  223. tag:,
  224. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  225. change_type: 'add',
  226. timestamp: pt.created_at)
  227. if pt.discarded_at
  228. events << Event.new(
  229. post:,
  230. tag:,
  231. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  232. change_type: 'remove',
  233. timestamp: pt.discarded_at)
  234. end
  235. end
  236. events.sort_by!(&:timestamp)
  237. events.reverse!
  238. render json: { changes: (events.slice(offset, limit) || []).as_json, count: events.size }
  239. end
  240. private
  241. def filtered_posts
  242. tag_names = params[:tags].to_s.split
  243. match_type = params[:match]
  244. if tag_names.present?
  245. filter_posts_by_tags(tag_names, match_type)
  246. else
  247. Post.all
  248. end
  249. end
  250. def filter_posts_by_tags tag_names, match_type
  251. literals = tag_names.map do |raw_name|
  252. { name: TagName.canonicalise(raw_name.sub(/\Anot:/i, '')).first,
  253. negative: raw_name.downcase.start_with?('not:') }
  254. end
  255. return Post.all if literals.empty?
  256. if match_type == 'any'
  257. literals.reduce(Post.none) do |posts, literal|
  258. posts.or(tag_literal_relation(literal[:name], negative: literal[:negative]))
  259. end
  260. else
  261. literals.reduce(Post.all) do |posts, literal|
  262. ids = tagged_post_ids_for(literal[:name])
  263. if literal[:negative]
  264. posts.where.not(id: ids)
  265. else
  266. posts.where(id: ids)
  267. end
  268. end
  269. end
  270. end
  271. def tag_literal_relation name, negative:
  272. ids = tagged_post_ids_for(name)
  273. if negative
  274. Post.where.not(id: ids)
  275. else
  276. Post.where(id: ids)
  277. end
  278. end
  279. def tagged_post_ids_for(name) =
  280. Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
  281. def sync_post_tags! post, desired_tags
  282. desired_tags.each do |t|
  283. t.save! if t.new_record?
  284. end
  285. desired_ids = desired_tags.map(&:id).to_set
  286. current_ids = post.tags.pluck(:id).to_set
  287. to_add = desired_ids - current_ids
  288. to_remove = current_ids - desired_ids
  289. Tag.where(id: to_add).find_each do |tag|
  290. begin
  291. PostTag.create!(post:, tag:, created_user: current_user)
  292. rescue ActiveRecord::RecordNotUnique
  293. ;
  294. end
  295. end
  296. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  297. pt.discard_by!(current_user)
  298. end
  299. end
  300. def build_tag_tree_for tags
  301. tags = tags.to_a
  302. tag_ids = tags.map(&:id)
  303. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  304. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  305. implications.each do |imp|
  306. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  307. end
  308. child_ids = children_ids_by_parent.values.flatten.uniq
  309. root_ids = tag_ids - child_ids
  310. tags_by_id = tags.index_by(&:id)
  311. memo = { }
  312. build_node = -> tag_id, path do
  313. tag = tags_by_id[tag_id]
  314. return nil unless tag
  315. if path.include?(tag_id)
  316. return TagRepr.base(tag).merge(children: [])
  317. end
  318. if memo.key?(tag_id)
  319. return memo[tag_id]
  320. end
  321. new_path = path + [tag_id]
  322. child_ids = children_ids_by_parent[tag_id] || []
  323. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  324. memo[tag_id] = TagRepr.base(tag).merge(children:)
  325. end
  326. root_ids.filter_map { |id| build_node.call(id, []) }
  327. end
  328. def parse_parent_post_ids
  329. raise ArgumentError, 'parent_post_ids は必須です.' unless params.key?(:parent_post_ids)
  330. params[:parent_post_ids].to_s.split.map { |token|
  331. id = Integer(token, exception: false)
  332. raise ArgumentError, "親投稿 Id. が不正です: #{ token }" if id.nil? || id <= 0
  333. id
  334. }.uniq
  335. end
  336. def sync_parent_posts! post, parent_post_ids
  337. if parent_post_ids.include?(post.id)
  338. post.errors.add(:base, '自分自身を親投稿にはできません.')
  339. raise ActiveRecord::RecordInvalid, post
  340. end
  341. existing_ids = Post.where(id: parent_post_ids).pluck(:id)
  342. missing_ids = parent_post_ids - existing_ids
  343. if missing_ids.present?
  344. post.errors.add(:base, "存在しない親投稿 ID があります: #{ missing_ids.join(' ') }")
  345. raise ActiveRecord::RecordInvalid, post
  346. end
  347. current_ids = post.parent_posts.pluck(:id)
  348. ids_to_add = parent_post_ids - current_ids
  349. ids_to_remove = current_ids - parent_post_ids
  350. PostImplication.where(post_id: post.id, parent_post_id: ids_to_remove).delete_all
  351. ids_to_add.each do |parent_post_id|
  352. PostImplication.create_or_find_by!(post_id: post.id, parent_post_id:)
  353. end
  354. end
  355. def parse_base_version_no
  356. version_no = Integer(params[:base_version_no], exception: false)
  357. raise ArgumentError, 'base_version_no は必須です.' unless version_no&.positive?
  358. version_no
  359. end
  360. def post_snapshot_from_version version
  361. { title: version.title,
  362. original_created_from: snapshot_time(version.original_created_from),
  363. original_created_before: snapshot_time(version.original_created_before),
  364. tag_names: editable_tag_names_from_version(version),
  365. parent_post_ids: snapshot_parent_post_ids_from_version(version) }
  366. end
  367. def editable_tag_names_from_version version
  368. version.tags.to_s.split.reject { |name| name.downcase.start_with?('nico:') }.sort
  369. end
  370. def post_snapshot_from_record post
  371. { title: post.title,
  372. original_created_from: snapshot_time(post.original_created_from),
  373. original_created_before: snapshot_time(post.original_created_before),
  374. tag_names: editable_tag_names_from_post(post),
  375. parent_post_ids: post.parent_posts.order(:id).pluck(:id) }
  376. end
  377. def editable_tag_names_from_post post
  378. post.tags.not_nico.joins(:tag_name).order('tag_names.name').pluck('tag_names.name')
  379. end
  380. def post_incoming_snapshot title:, original_created_from:, original_created_before:,
  381. tag_names:, parent_post_ids:
  382. { title:,
  383. original_created_from: snapshot_time(original_created_from),
  384. original_created_before: snapshot_time(original_created_before),
  385. tag_names: incoming_tag_names_for_snapshot(tag_names),
  386. parent_post_ids: parent_post_ids.sort }
  387. end
  388. def snapshot_parent_post_ids_from_version version
  389. if version.respond_to?(:parent_post_ids)
  390. version.parent_post_ids.to_s.split.map { |id| id.to_i }.sort
  391. elsif version.respond_to?(:parent_id) && version.parent_id
  392. [version.parent_id]
  393. else
  394. []
  395. end
  396. end
  397. def snapshot_time value
  398. return nil if value.blank?
  399. value = Time.zone.parse(value.to_s) if value in String
  400. value&.in_time_zone&.iso8601(6)
  401. rescue ArgumentError, TypeError
  402. value.to_s
  403. end
  404. def incoming_tag_names_for_snapshot raw_tag_names
  405. tags = Tag.normalise_tags!(raw_tag_names, with_tagme: false)
  406. Tag.expand_parent_tags(tags).map(&:name).uniq.sort
  407. end
  408. def post_conflict_json post:, base_version_no:, base_snapshot:,
  409. current_snapshot:, incoming_snapshot:, changes:, conflicts:
  410. { error: 'conflict',
  411. message: '競合が発生しました.',
  412. post_id: post.id,
  413. base_version_no:,
  414. current_version_no: post.version_no,
  415. base: base_snapshot,
  416. current: current_snapshot,
  417. mine: incoming_snapshot,
  418. changes:,
  419. conflicts:,
  420. mergeable: conflicts.empty? }
  421. end
  422. def post_snapshot_changes base_snapshot, current_snapshot, incoming_snapshot
  423. [scalar_snapshot_change(:title, 'タイトル',
  424. base_snapshot, current_snapshot, incoming_snapshot),
  425. scalar_snapshot_change(:original_created_from, 'オリジナルの作成日時(以降)',
  426. base_snapshot, current_snapshot, incoming_snapshot),
  427. scalar_snapshot_change(:original_created_before, 'オリジナルの作成日時(より前)',
  428. base_snapshot, current_snapshot, incoming_snapshot),
  429. set_snapshot_change(:tag_names, 'タグ',
  430. base_snapshot, current_snapshot, incoming_snapshot),
  431. set_snapshot_change(:parent_post_ids, '親投稿',
  432. base_snapshot, current_snapshot, incoming_snapshot)].compact
  433. end
  434. def scalar_snapshot_change field, label, base_snapshot, current_snapshot, incoming_snapshot
  435. base = base_snapshot[field]
  436. current = current_snapshot[field]
  437. mine = incoming_snapshot[field]
  438. return nil if current == base && mine == base
  439. { field:, label:, base:, current:, mine:,
  440. changed_by_current: current != base,
  441. changed_by_me: mine != base,
  442. conflict: scalar_snapshot_conflict?(base, current, mine) }
  443. end
  444. def scalar_snapshot_conflict? base, current, mine
  445. current != base && mine != base && current != mine
  446. end
  447. def set_snapshot_change field, label, base_snapshot, current_snapshot, incoming_snapshot
  448. base = base_snapshot[field].to_a
  449. current = current_snapshot[field].to_a
  450. mine = incoming_snapshot[field].to_a
  451. added_by_current = current - base
  452. removed_by_current = base - current
  453. added_by_me = mine - base
  454. removed_by_me = base - mine
  455. if (added_by_current.empty? &&
  456. removed_by_current.empty? &&
  457. added_by_me.empty? &&
  458. removed_by_me.empty?)
  459. return nil
  460. end
  461. { field:, label:, base:, current:, mine:, added_by_current:, removed_by_current:,
  462. added_by_me:, removed_by_me:,
  463. changed_by_current: added_by_current.present? || removed_by_current.present?,
  464. changed_by_me: added_by_me.present? || removed_by_me.present?,
  465. conflict: set_snapshot_conflict?(added_by_current:,
  466. removed_by_current:,
  467. added_by_me:,
  468. removed_by_me:) }
  469. end
  470. def set_snapshot_conflict? added_by_current:, removed_by_current:,
  471. added_by_me:, removed_by_me:
  472. (added_by_current & removed_by_me).present? || (removed_by_current & added_by_me).present?
  473. end
  474. def apply_post_snapshot! post, snapshot
  475. PostVersionRecorder.ensure_snapshot!(post, created_by_user: current_user)
  476. post.update!(title: snapshot[:title],
  477. original_created_from: snapshot[:original_created_from],
  478. original_created_before: snapshot[:original_created_before])
  479. editable_tags = Tag.normalise_tags!(snapshot[:tag_names], with_tagme: false)
  480. TagVersioning.record_tag_snapshots!(editable_tags, created_by_user: current_user)
  481. readonly_tags = post.tags.nico.to_a
  482. tags = readonly_tags + editable_tags
  483. tags = Tag.expand_parent_tags(tags)
  484. sync_post_tags!(post, tags)
  485. sync_parent_posts!(post, snapshot[:parent_post_ids])
  486. PostVersionRecorder.record!(post:, event_type: :update, created_by_user: current_user)
  487. end
  488. def merge_post_snapshots base_snapshot, current_snapshot, incoming_snapshot
  489. [:title, :original_created_from, :original_created_before].map {
  490. [_1, merge_scalar_snapshot_value(base_snapshot[_1],
  491. current_snapshot[_1],
  492. incoming_snapshot[_1])]
  493. }.to_h.merge([:tag_names, :parent_post_ids].map {
  494. [_1, merge_set_snapshot_value(base_snapshot[_1],
  495. current_snapshot[_1],
  496. incoming_snapshot[_1])]
  497. }.to_h)
  498. end
  499. def merge_scalar_snapshot_value base, current, mine
  500. return mine if current == base
  501. return current if mine == base || current == mine
  502. raise ArgumentError, '競合してゐる項目はマージできません.'
  503. end
  504. def merge_set_snapshot_value base, current, mine
  505. base = base.to_a
  506. current = current.to_a
  507. mine = mine.to_a
  508. added_by_current = current - base
  509. removed_by_current = base - current
  510. added_by_me = mine - base
  511. removed_by_me = base - mine
  512. merged = base + added_by_current + added_by_me
  513. merged -= removed_by_current
  514. merged -= removed_by_me
  515. merged.uniq.sort
  516. end
  517. end