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

647 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 = truthy_param?(params[:force])
  145. merge = truthy_param?(params[: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(post,
  167. title:,
  168. original_created_from:,
  169. original_created_before:,
  170. tag_names:,
  171. parent_post_ids:)
  172. snapshot_to_apply =
  173. if post.version_no == base_version_no || force
  174. incoming_snapshot
  175. else
  176. changes = post_snapshot_changes(base_snapshot, current_snapshot, incoming_snapshot)
  177. conflicts = changes.select { |change| change[:conflict] }
  178. if merge && conflicts.empty?
  179. merge_post_snapshots(base_snapshot, current_snapshot, incoming_snapshot)
  180. else
  181. conflict_json = post_conflict_json(post:,
  182. base_version_no:,
  183. base_snapshot:,
  184. current_snapshot:,
  185. incoming_snapshot:,
  186. changes:,
  187. conflicts:)
  188. raise ActiveRecord::Rollback
  189. end
  190. end
  191. apply_post_snapshot!(post, snapshot_to_apply)
  192. end
  193. return render json: conflict_json, status: :conflict if conflict_json
  194. post.reload
  195. json = PostRepr.base(post, current_user)
  196. json['tags'] = build_tag_tree_for(post.tags)
  197. render json:, status: :ok
  198. rescue Tag::NicoTagNormalisationError
  199. head :bad_request
  200. rescue ArgumentError => e
  201. render json: { errors: [e.message] }, status: :unprocessable_entity
  202. rescue ActiveRecord::RecordInvalid => e
  203. render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
  204. end
  205. def changes
  206. id = params[:id].presence
  207. tag_id = params[:tag].presence
  208. page = (params[:page].presence || 1).to_i
  209. limit = (params[:limit].presence || 20).to_i
  210. page = 1 if page < 1
  211. limit = 1 if limit < 1
  212. offset = (page - 1) * limit
  213. pts = PostTag.with_discarded
  214. pts = pts.where(post_id: id) if id.present?
  215. pts = pts.where(tag_id:) if tag_id.present?
  216. pts = pts.includes(:post, :created_user, :deleted_user,
  217. tag: [:deerjikists, :materials, { tag_name: :wiki_page }])
  218. events = []
  219. pts.each do |pt|
  220. tag = TagRepr.base(pt.tag)
  221. post = pt.post
  222. events << Event.new(
  223. post:,
  224. tag:,
  225. user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
  226. change_type: 'add',
  227. timestamp: pt.created_at)
  228. if pt.discarded_at
  229. events << Event.new(
  230. post:,
  231. tag:,
  232. user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
  233. change_type: 'remove',
  234. timestamp: pt.discarded_at)
  235. end
  236. end
  237. events.sort_by!(&:timestamp)
  238. events.reverse!
  239. render json: { changes: (events.slice(offset, limit) || []).as_json, count: events.size }
  240. end
  241. private
  242. def filtered_posts
  243. tag_names = params[:tags].to_s.split
  244. match_type = params[:match]
  245. if tag_names.present?
  246. filter_posts_by_tags(tag_names, match_type)
  247. else
  248. Post.all
  249. end
  250. end
  251. def filter_posts_by_tags tag_names, match_type
  252. literals = tag_names.map do |raw_name|
  253. { name: TagName.canonicalise(raw_name.sub(/\Anot:/i, '')).first,
  254. negative: raw_name.downcase.start_with?('not:') }
  255. end
  256. return Post.all if literals.empty?
  257. if match_type == 'any'
  258. literals.reduce(Post.none) do |posts, literal|
  259. posts.or(tag_literal_relation(literal[:name], negative: literal[:negative]))
  260. end
  261. else
  262. literals.reduce(Post.all) do |posts, literal|
  263. ids = tagged_post_ids_for(literal[:name])
  264. if literal[:negative]
  265. posts.where.not(id: ids)
  266. else
  267. posts.where(id: ids)
  268. end
  269. end
  270. end
  271. end
  272. def tag_literal_relation name, negative:
  273. ids = tagged_post_ids_for(name)
  274. if negative
  275. Post.where.not(id: ids)
  276. else
  277. Post.where(id: ids)
  278. end
  279. end
  280. def tagged_post_ids_for(name) =
  281. Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
  282. def sync_post_tags! post, desired_tags
  283. desired_tags.each do |t|
  284. t.save! if t.new_record?
  285. end
  286. desired_ids = desired_tags.map(&:id).to_set
  287. current_ids = post.tags.pluck(:id).to_set
  288. to_add = desired_ids - current_ids
  289. to_remove = current_ids - desired_ids
  290. Tag.where(id: to_add).find_each do |tag|
  291. begin
  292. PostTag.create!(post:, tag:, created_user: current_user)
  293. rescue ActiveRecord::RecordNotUnique
  294. ;
  295. end
  296. end
  297. PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
  298. pt.discard_by!(current_user)
  299. end
  300. end
  301. def build_tag_tree_for tags
  302. tags = tags.to_a
  303. tag_ids = tags.map(&:id)
  304. implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
  305. children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
  306. implications.each do |imp|
  307. children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
  308. end
  309. child_ids = children_ids_by_parent.values.flatten.uniq
  310. root_ids = tag_ids - child_ids
  311. tags_by_id = tags.index_by(&:id)
  312. memo = { }
  313. build_node = -> tag_id, path do
  314. tag = tags_by_id[tag_id]
  315. return nil unless tag
  316. if path.include?(tag_id)
  317. return TagRepr.base(tag).merge(children: [])
  318. end
  319. if memo.key?(tag_id)
  320. return memo[tag_id]
  321. end
  322. new_path = path + [tag_id]
  323. child_ids = children_ids_by_parent[tag_id] || []
  324. children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
  325. memo[tag_id] = TagRepr.base(tag).merge(children:)
  326. end
  327. root_ids.filter_map { |id| build_node.call(id, []) }
  328. end
  329. def parse_parent_post_ids
  330. raise ArgumentError, 'parent_post_ids は必須です.' unless params.key?(:parent_post_ids)
  331. params[:parent_post_ids].to_s.split.map { |token|
  332. id = Integer(token, exception: false)
  333. raise ArgumentError, "親投稿 Id. が不正です: #{ token }" if id.nil? || id <= 0
  334. id
  335. }.uniq
  336. end
  337. def sync_parent_posts! post, parent_post_ids
  338. if parent_post_ids.include?(post.id)
  339. post.errors.add(:base, '自分自身を親投稿にはできません.')
  340. raise ActiveRecord::RecordInvalid, post
  341. end
  342. existing_ids = Post.where(id: parent_post_ids).pluck(:id)
  343. missing_ids = parent_post_ids - existing_ids
  344. if missing_ids.present?
  345. post.errors.add(:base, "存在しない親投稿 ID があります: #{ missing_ids.join(' ') }")
  346. raise ActiveRecord::RecordInvalid, post
  347. end
  348. current_ids = post.parent_posts.pluck(:id)
  349. ids_to_add = parent_post_ids - current_ids
  350. ids_to_remove = current_ids - parent_post_ids
  351. PostImplication.where(post_id: post.id, parent_post_id: ids_to_remove).delete_all
  352. ids_to_add.each do |parent_post_id|
  353. PostImplication.create_or_find_by!(post_id: post.id, parent_post_id:)
  354. end
  355. end
  356. def parse_base_version_no
  357. version_no = Integer(params[:base_version_no], exception: false)
  358. raise ArgumentError, 'base_version_no は必須です.' unless version_no&.positive?
  359. version_no
  360. end
  361. def truthy_param?(value) = ActiveModel::Type::Boolean.new.cast(value)
  362. def post_snapshot_from_version version
  363. { title: version.title,
  364. original_created_from: snapshot_time(version.original_created_from),
  365. original_created_before: snapshot_time(version.original_created_before),
  366. tag_names: version.tags.to_s.split.filter { !(_1.start_with?('nico:')) }.sort,
  367. parent_post_ids: snapshot_parent_post_ids_from_version(version) }
  368. end
  369. def post_snapshot_from_record post
  370. { title: post.title,
  371. original_created_from: snapshot_time(post.original_created_from),
  372. original_created_before: snapshot_time(post.original_created_before),
  373. tag_names: post.tags.joins(:tag_name).order('tag_names.name').pluck('tag_names.name'),
  374. parent_post_ids: post.parent_posts.order(:id).pluck(:id) }
  375. end
  376. def post_incoming_snapshot post, title:, original_created_from:, original_created_before:,
  377. tag_names:, parent_post_ids:
  378. { title:,
  379. original_created_from: snapshot_time(original_created_from),
  380. original_created_before: snapshot_time(original_created_before),
  381. tag_names: incoming_tag_names_for_snapshot(post, tag_names),
  382. parent_post_ids: parent_post_ids.sort }
  383. end
  384. def snapshot_parent_post_ids_from_version version
  385. if version.respond_to?(:parent_post_ids)
  386. version.parent_post_ids.to_s.split.map { |id| id.to_i }.sort
  387. elsif version.respond_to?(:parent_id) && version.parent_id
  388. [version.parent_id]
  389. else
  390. []
  391. end
  392. end
  393. def snapshot_time value
  394. return nil if value.blank?
  395. value = Time.zone.parse(value.to_s) if value in String
  396. value&.in_time_zone&.iso8601(6)
  397. rescue ArgumentError, TypeError
  398. value.to_s
  399. end
  400. def incoming_tag_names_for_snapshot post, raw_tag_names
  401. manual_names = normalised_manual_tag_names_for_snapshot(raw_tag_names)
  402. existing_tags =
  403. Tag
  404. .joins(:tag_name)
  405. .where(tag_names: { name: manual_names })
  406. .to_a
  407. expanded_names = Tag.expand_parent_tags(existing_tags).map(&:name)
  408. (manual_names + expanded_names).uniq.sort
  409. end
  410. def normalised_manual_tag_names_for_snapshot raw_tag_names
  411. if raw_tag_names.any? { |name| name.downcase.start_with?('nico:') }
  412. raise Tag::NicoTagNormalisationError
  413. end
  414. pairs = raw_tag_names.map do |raw_name|
  415. prefix, category =
  416. Tag::CATEGORY_PREFIXES.find { |p, _| raw_name.downcase.start_with?(p) } || ['', nil]
  417. name = TagName.canonicalise(raw_name.sub(/\A#{ Regexp.escape(prefix) }/i, '')).first
  418. [name, category]
  419. end
  420. names = pairs.map(&:first)
  421. has_deerjikist = pairs.any? do |name, category|
  422. category == :deerjikist ||
  423. Tag.joins(:tag_name).where(category: :deerjikist, tag_names: { name: }).exists?
  424. end
  425. names << Tag.no_deerjikist.name unless has_deerjikist
  426. names.uniq.sort
  427. end
  428. def post_conflict_json post:, base_version_no:, base_snapshot:,
  429. current_snapshot:, incoming_snapshot:, changes:, conflicts:
  430. { error: 'conflict',
  431. message: '競合が発生しました.',
  432. post_id: post.id,
  433. base_version_no:,
  434. current_version_no: post.version_no,
  435. base: base_snapshot,
  436. current: current_snapshot,
  437. mine: incoming_snapshot,
  438. changes:,
  439. conflicts:,
  440. mergeable: conflicts.empty? }
  441. end
  442. def post_snapshot_changes base_snapshot, current_snapshot, incoming_snapshot
  443. [scalar_snapshot_change(:title, 'タイトル',
  444. base_snapshot, current_snapshot, incoming_snapshot),
  445. scalar_snapshot_change(:original_created_from, 'オリジナルの作成日時(以降)',
  446. base_snapshot, current_snapshot, incoming_snapshot),
  447. scalar_snapshot_change(:original_created_before, 'オリジナルの作成日時(より前)',
  448. base_snapshot, current_snapshot, incoming_snapshot),
  449. set_snapshot_change(:tag_names, 'タグ',
  450. base_snapshot, current_snapshot, incoming_snapshot),
  451. set_snapshot_change(:parent_post_ids, '親投稿',
  452. base_snapshot, current_snapshot, incoming_snapshot)].compact
  453. end
  454. def scalar_snapshot_change field, label, base_snapshot, current_snapshot, incoming_snapshot
  455. base = base_snapshot[field]
  456. current = current_snapshot[field]
  457. mine = incoming_snapshot[field]
  458. return nil if current == base && mine == base
  459. { field:, label:, base:, current:, mine:,
  460. changed_by_current: current != base,
  461. changed_by_me: mine != base,
  462. conflict: scalar_snapshot_conflict?(base, current, mine) }
  463. end
  464. def scalar_snapshot_conflict? base, current, mine
  465. current != base && mine != base && current != mine
  466. end
  467. def set_snapshot_change field, label, base_snapshot, current_snapshot, incoming_snapshot
  468. base = base_snapshot[field].to_a
  469. current = current_snapshot[field].to_a
  470. mine = incoming_snapshot[field].to_a
  471. added_by_current = current - base
  472. removed_by_current = base - current
  473. added_by_me = mine - base
  474. removed_by_me = base - mine
  475. if (added_by_current.empty? &&
  476. removed_by_current.empty? &&
  477. added_by_me.empty? &&
  478. removed_by_me.empty?)
  479. return nil
  480. end
  481. { field:, label:, base:, current:, mine:, added_by_current:, removed_by_current:,
  482. added_by_me:, removed_by_me:,
  483. changed_by_current: added_by_current.present? || removed_by_current.present?,
  484. changed_by_me: added_by_me.present? || removed_by_me.present?,
  485. conflict: set_snapshot_conflict?(added_by_current:,
  486. removed_by_current:,
  487. added_by_me:,
  488. removed_by_me:) }
  489. end
  490. def set_snapshot_conflict? added_by_current:, removed_by_current:,
  491. added_by_me:, removed_by_me:
  492. (added_by_current & removed_by_me).present? || (removed_by_current & added_by_me).present?
  493. end
  494. def apply_post_snapshot! post, snapshot
  495. PostVersionRecorder.ensure_snapshot!(post, created_by_user: current_user)
  496. post.update!(title: snapshot[:title],
  497. original_created_from: snapshot[:original_created_from],
  498. original_created_before: snapshot[:original_created_before])
  499. tags = Tag.normalise_tags!(snapshot[:tag_names], with_tagme: false)
  500. TagVersioning.record_tag_snapshots!(tags, created_by_user: current_user)
  501. tags = Tag.expand_parent_tags(tags)
  502. sync_post_tags!(post, tags)
  503. sync_parent_posts!(post, snapshot[:parent_post_ids])
  504. PostVersionRecorder.record!(post:, event_type: :update, created_by_user: current_user)
  505. end
  506. def merge_post_snapshots base_snapshot, current_snapshot, incoming_snapshot
  507. [:title, :original_created_from, :original_created_before, :tag_names, :parent_post_ids].map {
  508. [_1, merge_scaler_snapshot_value(base_snapshot[_1],
  509. current_snapshot[_1],
  510. incoming_snapshot[_1])]
  511. }.to_h
  512. end
  513. def merge_scaler_snapshot_value base, current, mine
  514. return mine if current == base
  515. return current if mine == base || current == mine
  516. raise ArgumentError, '競合してゐる項目はマージできません.'
  517. end
  518. end