コミットを比較

...

88 コミット

作成者 SHA1 メッセージ 日付
みてるぞ 63c1dd197c #297 2026-03-22 19:52:14 +09:00
みてるぞ 76f8e6875e #297 2026-03-22 01:00:15 +09:00
みてるぞ 57e82b6ffd #297 2026-03-22 00:58:58 +09:00
みてるぞ 505961898e #297 2026-03-21 20:52:59 +09:00
みてるぞ e133c684c8 #297 2026-03-21 20:06:25 +09:00
みてるぞ 3d80ded6f9 Merge remote-tracking branch 'origin/main' into feature/297 2026-03-21 19:59:14 +09:00
みてるぞ ee93ff8ea0 タグ一覧ページの作成(#61) (#298)
#61

#61

Merge remote-tracking branch 'origin/main' into feature/061

#61

#61

#61

#61

#61

#61

#61

#61

#61

#61

日づけ不詳の表示修正

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #298
2026-03-21 19:58:02 +09:00
みてるぞ 54a55875b3 #297 2026-03-21 12:40:24 +09:00
みてるぞ 40a62ccb22 #297 2026-03-21 12:38:26 +09:00
みてるぞ e5da633dfe #297 2026-03-21 05:39:44 +09:00
みてるぞ 23d9cf8ad0 #297 2026-03-21 05:34:59 +09:00
みてるぞ 40c1eec2cf #297 2026-03-21 05:19:51 +09:00
みてるぞ 83c801d8ce #297 2026-03-21 05:16:04 +09:00
みてるぞ 3469c58b53 #297 2026-03-21 04:57:46 +09:00
みてるぞ 1a451c5038 #297 2026-03-21 04:39:09 +09:00
みてるぞ d39b99f0ab #297 2026-03-21 04:32:07 +09:00
みてるぞ 8cf7107445 上映会のし組み作り(#295) (#296)
#295

#295

#295

#295

#295

#295

#295

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #296
2026-03-18 23:01:04 +09:00
みてるぞ ffadd03c49 PostHistoryPage で重複サムネが表示されないバグ(#278) (#293)
#278

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #293
2026-03-14 03:11:34 +09:00
みてるぞ bcce7f2011 削除タグが履歴で取得されるとフロントが落ちるバグ(#290) (#292)
#290

#290

'frontend/src/pages/posts/PostHistoryPage.tsx' を更新

'frontend/src/types.ts' を更新

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #292
2026-03-14 00:25:18 +09:00
みてるぞ d772cceb5e TagName サニタイズ(#281) (#289)
#281

#281

Merge remote-tracking branch 'origin/main' into feature/281

#281

#281 テストまだ通ってないので要確認

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #289
2026-03-12 21:58:16 +09:00
みてるぞ 176519b929 tags の論理削除対応(#287) (#288)
#287

#287

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #288
2026-03-11 22:55:57 +09:00
みてるぞ 238d236b2b OR 検索と NOT 検索(#68) (#286)
Merge remote-tracking branch 'origin/main' into feature/068

#68 テスト・ケース作成

#68

#68 まづは NOT に対応

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #286
2026-03-08 23:17:44 +09:00
みてるぞ 9e3cbd2469 投稿検索ページ(#206) (#274)
#206 エラー修正

#206 updated_at の並び順修正

Merge remote-tracking branch 'origin/main' into feature/206

Merge branch 'main' into feature/206

Merge branch 'main' into feature/206

Merge branch 'main' into feature/206

#206

#206

#206

#206

#206

#206 タグ補完追加

#206

#206

#206

#206

#206

Merge remote-tracking branch 'origin/main' into feature/206

#206

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #274
2026-03-08 23:12:16 +09:00
みてるぞ 16e9b8ca49 タグの合併処理追加(#282) (#284)
#282

#282

#282

#282

#282

#282

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #284
2026-03-08 15:46:05 +09:00
みてるぞ 7885f6dfb9 feat: “ニジラー情報不詳” タグの自動付与(#106) (#196)
#106

#106 エラー対応

#106

Merge branch 'main' into '#106'

Merge branch 'main' into '#106'

Merge remote-tracking branch 'origin/main' into '#106'

#106 誤字

Merge remote-tracking branch 'origin/main' into '#106'

#106 ニジラー情報なし

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #196
2026-03-07 13:58:43 +09:00
みてるぞ 98330b00bb ニコニコ同期にてニジラー情報自動記載(#276) (#277)
#276

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #277
2026-03-05 23:10:37 +09:00
みてるぞ e0e7a22c38 ニジラー管理(#247) (#275)
#247

#247

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #275
2026-03-05 20:35:11 +09:00
みてるぞ 7d1a87f452 表のレーアウト統一(#194) (#271)
#194

#194

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #271
2026-02-24 21:29:00 +09:00
みてるぞ a0d6aeb91e タグ補完ウィンドウ(#103) (#269)
#103

Merge remote-tracking branch 'origin/main' into feature/103

#103

#103 タグ補完からニコタグ除外

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #269
2026-02-22 23:32:01 +09:00
みてるぞ be983e4ad1 オリジナルの投稿日時 Safari でのバグ修正(#129) (#265)
Merge branch 'main' into feature/129

#129

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #265
2026-02-22 02:15:07 +09:00
みてるぞ 82302cd3d1 Representations 追加(#241) (#267)
#241

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #267
2026-02-22 01:50:56 +09:00
みてるぞ a01c63d972 PostEmbed の安全性強化(#130) (#263)
#130

#130

#130

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #263
2026-02-13 12:39:51 +09:00
みてるぞ 16bfc6eba2 プレフィクスのバグ修正(#124) (#261)
#124

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #261
2026-02-11 17:42:34 +09:00
みてるぞ 67c2590f2b 既存タグ名と同名の Wiki を新規作成できないバグ修正(#257) (#260)
#257

Merge remote-tracking branch 'origin/main' into feature/257

#257

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #260
2026-02-11 15:22:49 +09:00
みてるぞ eb975e5301 プリフェッチ実装(#140) (#256)
Merge branch 'main' into feature/140

#140

Merge remote-tracking branch 'origin/main' into feature/140

#140

#140

#140

#140

#140

Merge remote-tracking branch 'origin/main' into feature/140

#140

#140

#140

#140

#140

#140

#140

#140

#140

#140

#140

Merge remote-tracking branch 'origin/main' into feature/140

Merge remote-tracking branch 'origin/main' into feature/140

#140 ぼちぼち

Merge remote-tracking branch 'origin/main' into feature/140

#140

#140

#140

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #256
2026-02-11 13:27:28 +09:00
みてるぞ 1a776e348a クエリ・パフォーマンスの改善(#258) (#259)
#258

#258

#258

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #259
2026-02-11 13:26:10 +09:00
みてるぞ 9b7fc9059d バグ対応(#253) (#255)
#253

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #255
2026-02-08 13:48:41 +09:00
みてるぞ 797e67ac37 アニメーション(#139) (#252)
#139

#139

#139

#139

#139

Merge branch 'feature/140' into feature/139

Merge remote-tracking branch 'origin/main' into feature/139

#140

Merge remote-tracking branch 'origin/main' into feature/140

Merge remote-tracking branch 'origin/main' into feature/140

#140 ぼちぼち

Merge remote-tracking branch 'origin/main' into feature/140

#140

#140

#140

#139 アニメーション

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #252
2026-02-05 23:25:27 +09:00
みてるぞ f3cd108b2e ニコニコ同期にて “ニコニコ” および “動画” を自動付与するやぅに(#156) (#251)
#156

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #251
2026-01-31 15:00:56 +09:00
みてるぞ 5dd683bd4f サムネ再取得(#193) (#250)
#193

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #250
2026-01-31 11:38:32 +09:00
みてるぞ 5451d9ec9f ニコニコ同期時にオリジナルの投稿日時連携,形式のバグ修正(#246) (#249)
#246

#246

#246

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #249
2026-01-31 03:22:23 +09:00
みてるぞ 5a02be0517 ニコニコ同期でオリジナルの投稿日時連携(#246) (#248)
#246

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #248
2026-01-31 03:07:19 +09:00
みてるぞ 39ec57c142 feat: タグ補完から 0 件を除外(#109) (#245)
#109

#109

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #245
2026-01-29 22:48:03 +09:00
みてるぞ 01646ebcb7 feat: 別名タグをサジェストに展開(#28) (#244)
#28 件数 0 件除外をついでに対応(フロントのみ;バックエンドは後で対応)

#28

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #244
2026-01-29 07:32:13 +09:00
みてるぞ 200d457d22 feat: 別名を検索に展開(#20) (#243)
#20

#20 テスト・ケースのみ追記

#20

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #243
2026-01-28 23:47:56 +09:00
みてるぞ effde89b07 feat: WikiPagesController#index と WikiPagesController#search を統合(#222) (#240)
#222

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #240
2026-01-27 08:05:41 +09:00
みてるぞ 19c622c5bf feat: user_post_views から id を削除(#230) (#239)
#230

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #239
2026-01-27 01:04:16 +09:00
みてるぞ 9d68367a5a feat: user_ips の id を削除(#231) (#238)
#231

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #238
2026-01-27 00:43:52 +09:00
みてるぞ 7acdc16c75 feat: ip_addersses.ip_address をユニークに(#229) (#237)
#229

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #237
2026-01-26 23:59:14 +09:00
みてるぞ 0f64ec00f4 feat: 投稿にニコタグ追加できてしまふバグ修正(#125) (#236)
#125

#125

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #236
2026-01-25 00:17:36 +09:00
みてるぞ ef3d428a06 feat: Wiki 有無判定軽量化(#233) (#234)
#233 Backend が対応できてなかったのでそっちも対応させた.

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #234
2026-01-23 01:08:27 +09:00
みてるぞ f6de272f55 feat: 類似度算出バッチ修正,ほか(#228) (#232)
#228

#228

#228

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #232
2026-01-22 23:30:08 +09:00
みてるぞ 86209dcc84 feat: URL 正規化(#208) (#226)
#208

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #226
2026-01-20 12:39:33 +09:00
みてるぞ 16ecbd1fc9 【再掲】feat: D & D による上位タグ設定(#184) (#211)
#184 修正

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge branch 'main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

#184

#184

#184

#184

#184

#184

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #211
2026-01-18 00:52:21 +09:00
みてるぞ dd838fdf80 feat: Wiki 過去版取得で更新日時が異なる問題修正(#111) (#207)
#111

Merge remote-tracking branch 'origin/main' into feature/111

Merge branch 'main' into feature/111

#111

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #207
2026-01-17 09:15:54 +09:00
みてるぞ c8c262e34d feat: バグ直し(#223) (#224)
#223

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #224
2026-01-15 22:02:20 +09:00
みてるぞ fa2030f9a5 feat: タグ名を別管理に変更(#215) (#219)
Merge branch 'main' into feature/215

#215 ニコニコ同期テスト

#215 テスト・ケース追加

#215 テスト・ケース追加

#215 テスト・ケース追加

#215 テスト・ケース追加

Merge remote-tracking branch 'origin/main' into feature/215

Merge branch 'main' into feature/215

#215

#215

Merge remote-tracking branch 'origin/main' into feature/215

#215

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #219
2026-01-15 12:40:41 +09:00
みてるぞ 74141f2a84 feat: Wiki 自動リンクをテキスト領域のみに制限(#93) (#218)
Merge branch 'main' into #93

#93

Merge remote-tracking branch 'origin/main' into #93

#93

#93

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #218
2026-01-13 19:51:21 +09:00
みてるぞ f2b774ab1d feat: posts.title を Nullable に(#209) (#212)
Merge branch 'feature/209' of https://git.miteruzo.com/miteruzo/btrc-hub into feature/209

Merge branch 'main' into feature/209

Merge remote-tracking branch 'origin/main' into feature/209

#209

#209

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #212
2026-01-12 14:38:06 +09:00
みてるぞ 622f47a856 feat: テスト自動化(#104) (#220)
#104

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #220
2026-01-12 14:30:56 +09:00
みてるぞ 189175fe84 feat: 不要ソースの削除(#214) (#216)
#214

#214

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #216
2026-01-11 23:09:23 +09:00
みてるぞ 5160aacc53 Revert "feat: D & D による上位タグ設定(#184) (#186)"
This reverts commit 5f306b04b8.
2026-01-07 03:31:23 +09:00
みてるぞ 5f306b04b8 feat: D & D による上位タグ設定(#184) (#186)
Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge branch 'main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge remote-tracking branch 'origin/main' into feature/184

Merge branch 'main' into feature/184

Merge branch 'main' into feature/184

#184

#184

#184

#184

#184

#184

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #186
2026-01-07 03:26:05 +09:00
みてるぞ b309263df5 feat: 関聯タグ(#92) (#197)
Merge branch 'main' into #92

Merge remote-tracking branch 'origin/main' into #92

#92

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #197
2026-01-07 03:25:27 +09:00
みてるぞ 3f2c0a52b9 feat: posts.thumbnail_base を Nullable に(#75) (#198)
Merge remote-tracking branch 'origin/main' into feature/075

#75

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #198
2026-01-06 12:43:22 +09:00
みてるぞ 49888627c9 Merge pull request '#203' (#204) from feature/203 into main
Reviewed-on: #204
2026-01-04 19:10:01 +09:00
みてるぞ df38835f6e #203 2026-01-04 19:09:31 +09:00
みてるぞ 02ea0df683 #201 (#202)
#201

Reviewed-on: #202
2026-01-04 19:00:54 +09:00
みてるぞ 611455ec55 feat: Wiki の管理方法変更(#188) (#195)
Merge branch 'feature/188' of https://git.miteruzo.com/miteruzo/btrc-hub into feature/188

#188

Merge branch 'main' into feature/188

#188

#188

#188

#188

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #195
2026-01-04 18:52:17 +09:00
みてるぞ 6cf42e38c6 feat: 対応外の投稿を iframe で埋込む(#157) (#199)
#157

#157 対応外の投稿を iframe で埋込む

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #199
2026-01-01 21:19:10 +09:00
みてるぞ d224ccef4c feat: 広場のページネーション(#169) (#189)
#169 バグ修正

Merge remote-tracking branch 'origin/main' into feature/169

#169

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #189
2025-12-30 11:13:03 +09:00
みてるぞ 0344b61557 feat: 関聯する Wiki がない TagLink 修正(#107) (#192)
#107

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #192
2025-12-28 20:53:32 +09:00
みてるぞ c93f8585a1 feat: #112 の修正(#190) (#191)
Merge branch 'main' into feature/190

#190

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #191
2025-12-28 04:46:33 +09:00
みてるぞ c0cf97b80d feat: ニコニコ連携先をニコタグにできないやぅに修正(#142) (#144)
Merge branch 'main' into feature/142

Merge branch 'main' into feature/142

#142 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #144
2025-12-26 00:30:01 +09:00
みてるぞ cdf04f7514 feat: Wiki の URL におけるタイトルを完全一致に変更(#100) (#153)
Merge branch 'main' into feature/100

#100 要らんとこ変へてたので直した

#100 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #153
2025-12-25 02:51:55 +09:00
みてるぞ 0353961a72 feat: 403 解消(#168) (#187)
#168

#168

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #187
2025-12-23 23:37:58 +09:00
みてるぞ 34c227f326 feat: アニメーション修正(#183) (#185)
#183

#183

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #185
2025-12-20 02:36:32 +09:00
みてるぞ 468ef44bf9 feat: #84 のバグ対応(#181) (#182)
#181 バグ

#181

#181

#181

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #182
2025-12-15 01:13:52 +09:00
みてるぞ 43a55dbfcf feat: #176 のバグ対応(#179) (#180)
#179 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #180
2025-12-14 16:51:57 +09:00
みてるぞ 92d9fe7733 feat: アニメーションの一部実装(#176) (#178)
#176 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #178
2025-12-14 16:24:04 +09:00
みてるぞ f36837f0d8 feat: 耕作履歴ページ作成(#112) (#177)
#112 現在ページの表示を太く

#112 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #177
2025-12-14 03:49:03 +09:00
みてるぞ 9a656a9e6e feat: 投稿とタグのリレーション・テーブルについて論理削除と履歴を追加(#84) (#148)
#84 マイグレ修正

Merge remote-tracking branch 'origin/main' into feature/084

#84 構文エラー修正

#84

#84

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #148
2025-12-13 16:34:45 +09:00
みてるぞ 3b32d4d8ac feat: 上位タグのバグ修正(#174) (#175)
#174 エラー回避と誤記修正

#174 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #175
2025-12-10 20:18:48 +09:00
みてるぞ d50a302d26 feat: 上位タグ(#64) (#173)
#64 おそらく完成

Merge remote-tracking branch 'origin/main' into feature/064

#64 バックエンドぼちぼち

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #173
2025-12-09 12:34:26 +09:00
みてるぞ 06cd569fc5 ニコタグ一括連携の削除(#166) (#167)
'backend/lib/tasks/link_nico.rake' を削除

Reviewed-on: #167
2025-12-07 12:28:43 +09:00
みてるぞ 8a126e2e92 feat: ユーザに IP アドレスを紐づけ(#29) (#165)
#29 対応完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #165
2025-11-26 23:48:45 +09:00
みてるぞ 5cc47e42e1 feat: タグ希望タグを新規時のみにする(#128) (#145)
#128 完了

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #145
2025-11-26 22:33:50 +09:00
みてるぞ 19a17e7ba7 feat: ランダム抽出のバグ修正(#132) (#141)
#132

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #141
2025-10-04 22:49:04 +09:00
174個のファイルの変更10223行の追加1463行の削除
+1
ファイルの表示
@@ -0,0 +1 @@
--require spec_helper
+6
ファイルの表示
@@ -46,6 +46,8 @@ group :development, :test do
# Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/]
gem "rubocop-rails-omakase", require: false
gem 'factory_bot_rails'
end
@@ -63,3 +65,7 @@ gem 'diff-lcs'
gem 'dotenv-rails'
gem 'whenever', require: false
gem 'discard'
gem "rspec-rails", "~> 8.0", :groups => [:development, :test]
+27
ファイルの表示
@@ -90,6 +90,8 @@ GEM
crass (1.0.6)
date (3.4.1)
diff-lcs (1.6.2)
discard (1.4.0)
activerecord (>= 4.2, < 9.0)
dotenv (3.1.8)
dotenv-rails (3.1.8)
dotenv (= 3.1.8)
@@ -97,6 +99,11 @@ GEM
drb (2.2.1)
ed25519 (1.4.0)
erubi (1.13.1)
factory_bot (6.5.6)
activesupport (>= 6.1.0)
factory_bot_rails (6.5.1)
factory_bot (~> 6.5)
railties (>= 6.1.0)
ffi (1.17.2-aarch64-linux-gnu)
ffi (1.17.2-aarch64-linux-musl)
ffi (1.17.2-arm-linux-gnu)
@@ -296,6 +303,23 @@ GEM
io-console (~> 0.5)
rexml (3.4.1)
rouge (3.30.0)
rspec-core (3.13.6)
rspec-support (~> 3.13.0)
rspec-expectations (3.13.5)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-mocks (3.13.7)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-rails (8.0.2)
actionpack (>= 7.2)
activesupport (>= 7.2)
railties (>= 7.2)
rspec-core (~> 3.13)
rspec-expectations (~> 3.13)
rspec-mocks (~> 3.13)
rspec-support (~> 3.13)
rspec-support (3.13.6)
rss (0.3.1)
rexml
rubocop (1.75.6)
@@ -420,7 +444,9 @@ DEPENDENCIES
bootsnap
brakeman
diff-lcs
discard
dotenv-rails
factory_bot_rails
gollum
image_processing (~> 1.14)
jwt
@@ -430,6 +456,7 @@ DEPENDENCIES
puma (>= 5.0)
rack-cors
rails (~> 8.0.2)
rspec-rails (~> 8.0)
rubocop-rails-omakase
sprockets-rails
sqlite3 (>= 2.1)
+11
ファイルの表示
@@ -11,4 +11,15 @@ class ApplicationController < ActionController::API
code = request.headers['X-Transfer-Code'] || request.headers['HTTP_X_TRANSFER_CODE']
@current_user = User.find_by(inheritance_code: code)
end
def bool? key, default: false
return default if params[key].nil?
s = params[key].to_s.strip.downcase
if default
!(s.in?(['0', 'false', 'off', 'no']))
else
s.in?(['', '1', 'true', 'on', 'yes'])
end
end
end
+47
ファイルの表示
@@ -0,0 +1,47 @@
class DeerjikistsController < ApplicationController
def show
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
return head :bad_request if platform.blank? || code.blank?
deerjikist = Deerjikist
.joins(:tag)
.includes(tag: :tag_name)
.find_by(platform:, code:)
if deerjikist
render json: DeerjikistRepr.base(deerjikist)
else
head :not_found
end
end
def update
return head :unauthorized unless current_user
return head :forbidden unless current_user.gte_member?
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
tag_id = params[:tag_id].to_i
return head :bad_request if platform.blank? || code.blank? || tag_id <= 0
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
d.tag_id = tag_id
d.save!
end
render json: DeerjikistRepr.base(deerjikist)
end
def destroy
return head :unauthorized unless current_user
return head :forbidden unless current_user.gte_member?
platform = params[:platform].to_s.strip
code = params[:code].to_s.strip
return head :bad_request if platform.blank? || code.blank?
Deerjikist.find([platform, code]).destroy!
head :no_content
end
end
-20
ファイルの表示
@@ -1,20 +0,0 @@
class IpAddressesController < ApplicationController
def index
@ip_addresses = IpAddress.all
render json: @ip_addresses
end
def show
render json: @ip_address
end
def create
end
def update
end
def destroy
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class NicoTagRelationController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
+10 -7
ファイルの表示
@@ -3,10 +3,12 @@ class NicoTagsController < ApplicationController
limit = (params[:limit] || 20).to_i
cursor = params[:cursor].presence
q = Tag.nico_tags.includes(:linked_tags).order(updated_at: :desc)
q = Tag.nico_tags
.includes(:tag_name, tag_name: :wiki_page, linked_tags: { tag_name: :wiki_page })
.order(updated_at: :desc)
q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor
tags = q.limit(limit + 1)
tags = q.limit(limit + 1).to_a
next_cursor = nil
if tags.size > limit
@@ -15,13 +17,15 @@ class NicoTagsController < ApplicationController
end
render json: { tags: tags.map { |tag|
tag.as_json(include: :linked_tags)
TagRepr.base(tag).merge(linked_tags: tag.linked_tags.map { |lt|
TagRepr.base(lt)
})
}, next_cursor: }
end
def update
return head :unauthorized unless current_user
return head :forbidden unless current_user.member?
return head :forbidden unless current_user.gte_member?
id = params[:id].to_i
@@ -30,12 +34,11 @@ class NicoTagsController < ApplicationController
linked_tag_names = params[:tags].to_s.split(' ')
linked_tags = Tag.normalise_tags(linked_tag_names, with_tagme: false)
return head :bad_request if linked_tags.filter { |t| t.category == 'nico' }.present?
return head :bad_request if linked_tags.any? { |t| t.category == 'nico' }
tag.linked_tags = linked_tags
tag.updated_at = Time.now
tag.save!
render json: tag.linked_tags, status: :ok
render json: tag.linked_tags.map { |t| TagRepr.base(t) }, status: :ok
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class PostTagsController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
+259 -61
ファイルの表示
@@ -1,29 +1,89 @@
require 'open-uri'
require 'nokogiri'
class PostsController < ApplicationController
# GET /posts
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
def index
limit = params[:limit].presence&.to_i
cursor = params[:cursor].presence
url = params[:url].presence
title = params[:title].presence
original_created_from = params[:original_created_from].presence
original_created_to = params[:original_created_to].presence
created_between = params[:created_from].presence, params[:created_to].presence
updated_between = params[:updated_from].presence, params[:updated_to].presence
created_at = ('COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
'posts.original_created_from,' +
'posts.created_at)')
q = filtered_posts.order(Arel.sql("#{ created_at } DESC"))
q = q.where("#{ created_at } < ?", Time.iso8601(cursor)) if cursor
posts = limit ? q.limit(limit + 1) : q
next_cursor = nil
if limit && posts.size > limit
next_cursor = posts.last.created_at.iso8601(6)
posts = posts.first(limit)
order = params[:order].to_s.split(':', 2).map(&:strip)
unless order[0].in?(['title', 'url', 'original_created_at', 'created_at', 'updated_at'])
order[0] = 'original_created_at'
end
unless order[1].in?(['asc', 'desc'])
order[1] =
if order[0].in?(['title', 'url'])
'asc'
else
'desc'
end
end
page = (params[:page].presence || 1).to_i
limit = (params[:limit].presence || 20).to_i
page = 1 if page < 1
limit = 1 if limit < 1
offset = (page - 1) * limit
pt_max_sql =
PostTag
.select('post_id, MAX(updated_at) AS max_updated_at')
.group('post_id')
.to_sql
updated_at_all_sql =
'GREATEST(posts.updated_at,' +
'COALESCE(pt_max.max_updated_at, posts.updated_at))'
q =
filtered_posts
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
.preload(tags: { tag_name: :wiki_page })
.with_attached_thumbnail
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
q = q.where('posts.title LIKE ?', "%#{ title }%") if title
if original_created_from
q = q.where('posts.original_created_before > ?', original_created_from)
end
if original_created_to
q = q.where('posts.original_created_from <= ?', original_created_to)
end
q = q.where('posts.created_at >= ?', created_between[0]) if created_between[0]
q = q.where('posts.created_at <= ?', created_between[1]) if created_between[1]
if updated_between[0]
q = q.where("#{ updated_at_all_sql } >= ?", updated_between[0])
end
if updated_between[1]
q = q.where("#{ updated_at_all_sql } <= ?", updated_between[1])
end
sort_sql =
case order[0]
when 'original_created_at'
'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE,' +
'posts.original_created_from,' +
'posts.created_at) '
when 'updated_at'
updated_at_all_sql
else
"posts.#{ order[0] }"
end
posts = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, posts.id #{ order[1] }"))
.limit(limit)
.offset(offset)
.to_a
q = q.except(:select, :order)
render json: { posts: posts.map { |post|
post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }).tap do |json|
PostRepr.base(post).merge(updated_at: post.updated_at_all).tap do |json|
json['thumbnail'] =
if post.thumbnail.attached?
rails_storage_proxy_url(post.thumbnail, only_path: false)
@@ -31,58 +91,55 @@ class PostsController < ApplicationController
nil
end
end
}, next_cursor: }
}, count: q.group_values.present? ? q.count.size : q.count }
end
def random
post = filtered_posts.order('RAND()').first
post = filtered_posts.preload(tags: { tag_name: :wiki_page })
.order('RAND()')
.first
return head :not_found unless post
viewed = current_user&.viewed?(post) || false
render json: (post
.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } })
.merge(viewed:))
render json: PostRepr.base(post, current_user)
end
# GET /posts/1
def show
post = Post.includes(:tags).find(params[:id])
post = Post.includes(tags: { tag_name: :wiki_page }).find_by(id: params[:id])
return head :not_found unless post
viewed = current_user&.viewed?(post) || false
render json: (post
.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } })
.merge(related: post.related(limit: 20), viewed:))
render json: PostRepr.base(post, current_user)
.merge(tags: build_tag_tree_for(post.tags),
related: post.related(limit: 20))
end
# POST /posts
def create
return head :unauthorized unless current_user
return head :forbidden unless current_user.member?
return head :forbidden unless current_user.gte_member?
# TODO: URL が正規のものがチェック,不正ならエラー
# TODO: URL は必須にする(タイトルは省略可).
# TODO: サイトに応じて thumbnail_base 設定
title = params[:title]
title = params[:title].presence
url = params[:url]
thumbnail = params[:thumbnail]
tag_names = params[:tags].to_s.split(' ')
tag_names = params[:tags].to_s.split
original_created_from = params[:original_created_from]
original_created_before = params[:original_created_before]
post = Post.new(title:, url:, thumbnail_base: '', uploaded_user: current_user,
post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
original_created_from:, original_created_before:)
post.thumbnail.attach(thumbnail)
if post.save
post.resized_thumbnail!
post.tags = Tag.normalise_tags(tag_names)
render json: post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }),
status: :created
tags = Tag.normalise_tags(tag_names)
tags = Tag.expand_parent_tags(tags)
sync_post_tags!(post, tags)
post.reload
render json: PostRepr.base(post), status: :created
else
render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
end
rescue Tag::NicoTagNormalisationError
head :bad_request
end
def viewed
@@ -99,47 +156,188 @@ class PostsController < ApplicationController
head :no_content
end
# PATCH/PUT /posts/1
def update
return head :unauthorized unless current_user
return head :forbidden unless current_user.member?
return head :forbidden unless current_user.gte_member?
title = params[:title]
tag_names = params[:tags].to_s.split(' ')
title = params[:title].presence
tag_names = params[:tags].to_s.split
original_created_from = params[:original_created_from]
original_created_before = params[:original_created_before]
post = Post.find(params[:id].to_i)
tags = post.tags.where(category: 'nico').to_a + Tag.normalise_tags(tag_names)
if post.update(title:, tags:, original_created_from:, original_created_before:)
render json: post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }),
status: :ok
if post.update(title:, original_created_from:, original_created_before:)
tags = post.tags.where(category: 'nico').to_a +
Tag.normalise_tags(tag_names, with_tagme: false)
tags = Tag.expand_parent_tags(tags)
sync_post_tags!(post, tags)
post.reload
json = post.as_json
json['tags'] = build_tag_tree_for(post.tags)
render json:, status: :ok
else
render json: post.errors, status: :unprocessable_entity
end
rescue Tag::NicoTagNormalisationError
head :bad_request
end
# DELETE /posts/1
def destroy
def changes
id = params[:id].presence
tag_id = params[:tag].presence
page = (params[:page].presence || 1).to_i
limit = (params[:limit].presence || 20).to_i
page = 1 if page < 1
limit = 1 if limit < 1
offset = (page - 1) * limit
pts = PostTag.with_discarded
pts = pts.where(post_id: id) if id.present?
pts = pts.where(tag_id:) if tag_id.present?
pts = pts.includes(:post, :created_user, :deleted_user,
tag: { tag_name: :wiki_page })
events = []
pts.each do |pt|
tag = TagRepr.base(pt.tag)
post = pt.post
events << Event.new(
post:,
tag:,
user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
change_type: 'add',
timestamp: pt.created_at)
if pt.discarded_at
events << Event.new(
post:,
tag:,
user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
change_type: 'remove',
timestamp: pt.discarded_at)
end
end
events.sort_by!(&:timestamp)
events.reverse!
render json: { changes: (events.slice(offset, limit) || []).as_json, count: events.size }
end
private
def filtered_posts
tag_names = params[:tags]&.split(' ')
tag_names = params[:tags].to_s.split
match_type = params[:match]
tag_names.present? ? filter_posts_by_tags(tag_names, match_type) : Post.all
if tag_names.present?
filter_posts_by_tags(tag_names, match_type)
else
Post.all
end
end
def filter_posts_by_tags tag_names, match_type
posts = Post.joins(:tags)
literals = tag_names.map do |raw_name|
{ name: TagName.canonicalise(raw_name.sub(/\Anot:/i, '')).first,
negative: raw_name.downcase.start_with?('not:') }
end
return Post.all if literals.empty?
if match_type == 'any'
posts = posts.where(tags: { name: tag_names }).distinct
literals.reduce(Post.none) do |posts, literal|
posts.or(tag_literal_relation(literal[:name], negative: literal[:negative]))
end
else
tag_names.each do |tag|
posts = posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
literals.reduce(Post.all) do |posts, literal|
ids = tagged_post_ids_for(literal[:name])
if literal[:negative]
posts.where.not(id: ids)
else
posts.where(id: ids)
end
end
end
posts.distinct
end
def tag_literal_relation name, negative:
ids = tagged_post_ids_for(name)
if negative
Post.where.not(id: ids)
else
Post.where(id: ids)
end
end
def tagged_post_ids_for(name) =
Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
def sync_post_tags! post, desired_tags
desired_tags.each do |t|
t.save! if t.new_record?
end
desired_ids = desired_tags.map(&:id).to_set
current_ids = post.tags.pluck(:id).to_set
to_add = desired_ids - current_ids
to_remove = current_ids - desired_ids
Tag.where(id: to_add).find_each do |tag|
begin
PostTag.create!(post:, tag:, created_user: current_user)
rescue ActiveRecord::RecordNotUnique
;
end
end
PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
pt.discard_by!(current_user)
end
end
def build_tag_tree_for tags
tags = tags.to_a
tag_ids = tags.map(&:id)
implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
children_ids_by_parent = Hash.new { |h, k| h[k] = [] }
implications.each do |imp|
children_ids_by_parent[imp.parent_tag_id] << imp.tag_id
end
child_ids = children_ids_by_parent.values.flatten.uniq
root_ids = tag_ids - child_ids
tags_by_id = tags.index_by(&:id)
memo = { }
build_node = -> tag_id, path do
tag = tags_by_id[tag_id]
return nil unless tag
if path.include?(tag_id)
return TagRepr.base(tag).merge(children: [])
end
if memo.key?(tag_id)
return memo[tag_id]
end
new_path = path + [tag_id]
child_ids = children_ids_by_parent[tag_id] || []
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
memo[tag_id] = TagRepr.base(tag).merge(children:)
end
root_ids.filter_map { |id| build_node.call(id, []) }
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class SettingsController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class TagAliasesController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
+27
ファイルの表示
@@ -0,0 +1,27 @@
class TagChildrenController < ApplicationController
def create
return head :unauthorized unless current_user
return head :forbidden unless current_user.admin?
parent_id = params[:parent_id]
child_id = params[:child_id]
return head :bad_request if parent_id.blank? || child_id.blank?
Tag.find(parent_id).children << Tag.find(child_id) rescue nil
head :no_content
end
def destroy
return head :unauthorized unless current_user
return head :forbidden unless current_user.admin?
parent_id = params[:parent_id]
child_id = params[:child_id]
return head :bad_request if parent_id.blank? || child_id.blank?
Tag.find(parent_id).children.delete(Tag.find(child_id)) rescue nil
head :no_content
end
end
+159 -24
ファイルの表示
@@ -1,46 +1,181 @@
class TagsController < ApplicationController
def index
post_id = params[:post]
tags = if post_id.present?
Tag.joins(:posts).where(posts: { id: post_id })
else
Tag.all
end
render json: tags
name = params[:name].presence
category = params[:category].presence
post_count_between = (params[:post_count_gte].presence || -1).to_i,
(params[:post_count_lte].presence || -1).to_i
post_count_between[0] = nil if post_count_between[0] < 0
post_count_between[1] = nil if post_count_between[1] < 0
created_between = params[:created_from].presence, params[:created_to].presence
updated_between = params[:updated_from].presence, params[:updated_to].presence
order = params[:order].to_s.split(':', 2).map(&:strip)
unless order[0].in?(['name', 'category', 'post_count', 'created_at', 'updated_at'])
order[0] = 'post_count'
end
unless order[1].in?(['asc', 'desc'])
order[1] = order[0].in?(['name', 'category']) ? 'asc' : 'desc'
end
page = (params[:page].presence || 1).to_i
limit = (params[:limit].presence || 20).to_i
page = 1 if page < 1
limit = 1 if limit < 1
offset = (page - 1) * limit
q =
if post_id.present?
Tag.joins(:posts, :tag_name)
else
Tag.joins(:tag_name)
end
.includes(:tag_name, tag_name: :wiki_page)
q = q.where(posts: { id: post_id }) if post_id.present?
q = q.where('tag_names.name LIKE ?', "%#{ name }%") if name
q = q.where(category: category) if category
q = q.where('tags.post_count >= ?', post_count_between[0]) if post_count_between[0]
q = q.where('tags.post_count <= ?', post_count_between[1]) if post_count_between[1]
q = q.where('tags.created_at >= ?', created_between[0]) if created_between[0]
q = q.where('tags.created_at <= ?', created_between[1]) if created_between[1]
q = q.where('tags.updated_at >= ?', updated_between[0]) if updated_between[0]
q = q.where('tags.updated_at <= ?', updated_between[1]) if updated_between[1]
sort_sql =
case order[0]
when 'name'
'tag_names.name'
when 'category'
'CASE tags.category ' +
"WHEN 'deerjikist' THEN 0 " +
"WHEN 'meme' THEN 1 " +
"WHEN 'character' THEN 2 " +
"WHEN 'general' THEN 3 " +
"WHEN 'material' THEN 4 " +
"WHEN 'meta' THEN 5 " +
"WHEN 'nico' THEN 6 END"
else
"tags.#{ order[0] }"
end
tags = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, tags.id #{ order[1] }"))
.limit(limit)
.offset(offset)
.to_a
render json: { tags: TagRepr.base(tags), count: q.size }
end
def autocomplete
q = params[:q].to_s.strip
return render json: [] if q.blank?
q = params[:q].to_s.strip.sub(/\Anot:/i, '')
tags = (Tag
.where('(category = ? AND name LIKE ?) OR name LIKE ?',
'nico', "nico:#{ q }%", "#{ q }%")
.order('post_count DESC, name ASC')
.limit(20))
render json: tags
with_nico = bool?(:nico, default: true)
present_only = bool?(:present, default: true)
alias_rows =
TagName
.where('name LIKE ?', "#{ q }%")
.where.not(canonical_id: nil)
.pluck(:canonical_id, :name)
matched_alias_by_tag_name_id = { }
canonical_ids = []
alias_rows.each do |canonical_id, alias_name|
canonical_ids << canonical_id
matched_alias_by_tag_name_id[canonical_id] ||= alias_name
end
base = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
base = base.where('tags.post_count > 0') if present_only
canonical_hit =
base
.where(((with_nico ? '(tags.category = ? AND tag_names.name LIKE ?) OR ' : '') +
'tag_names.name LIKE ?'),
*(with_nico ? ['nico', "nico:#{ q }%"] : []), "#{ q }%")
tags =
if canonical_ids.present?
canonical_hit.or(base.where(tag_name_id: canonical_ids.uniq))
else
canonical_hit
end
tags = tags.order(Arel.sql('post_count DESC, tag_names.name')).limit(20).to_a
render json: tags.map { |tag|
TagRepr.base(tag).merge(matched_alias: matched_alias_by_tag_name_id[tag.tag_name_id])
}
end
def show
tag = Tag.find(params[:id])
render json: tag
end
def show_by_name
tag = Tag.find_by(name: params[:name])
tag = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
.find_by(id: params[:id])
if tag
render json: tag
render json: TagRepr.base(tag)
else
head :not_found
end
end
def create
def show_by_name
name = params[:name].to_s.strip
return head :bad_request if name.blank?
tag = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
.find_by(tag_names: { name: })
if tag
render json: TagRepr.base(tag)
else
head :not_found
end
end
def deerjikists
tag = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
.find_by(id: params[:id])
return head :not_found unless tag
render json: DeerjikistRepr.many(tag.deerjikists)
end
def deerjikists_by_name
name = params[:name].to_s.strip
return head :bad_request if name.blank?
tag = Tag.joins(:tag_name)
.includes(:tag_name, tag_name: :wiki_page)
.find_by(tag_names: { name: })
return head :not_found unless tag
render json: DeerjikistRepr.many(tag.deerjikists)
end
def update
end
return head :unauthorized unless current_user
return head :forbidden unless current_user.gte_member?
def destroy
name = params[:name].presence
category = params[:category].presence
tag = Tag.find(params[:id])
if name.present?
tag.tag_name.update!(name:)
end
if category.present?
tag.update!(category:)
end
render json: TagRepr.base(tag)
end
end
+32
ファイルの表示
@@ -0,0 +1,32 @@
class TheatreCommentsController < ApplicationController
def index
no_gt = params[:no_gt].to_i
no_gt = 0 if no_gt.negative?
comments = TheatreComment
.where(theatre_id: params[:theatre_id])
.where('no > ?', no_gt)
.order(no: :desc)
render json: comments.as_json(include: { user: { only: [:id, :name] } })
end
def create
return head :unauthorized unless current_user
content = params[:content]
return head :unprocessable_entity if content.blank?
theatre = Theatre.find_by(id: params[:theatre_id])
return head :not_found unless theatre
comment = nil
theatre.with_lock do
no = theatre.next_comment_no
comment = TheatreComment.create!(theatre:, no:, user: current_user, content:)
theatre.update!(next_comment_no: no + 1)
end
render json: comment, status: :created
end
end
+54
ファイルの表示
@@ -0,0 +1,54 @@
class TheatresController < ApplicationController
def show
theatre = Theatre.find_by(id: params[:id])
return head :not_found unless theatre
render json: TheatreRepr.base(theatre)
end
def watching
return head :unauthorized unless current_user
theatre = Theatre.find_by(id: params[:id])
return head :not_found unless theatre
host_flg = false
post_id = nil
post_started_at = nil
theatre.with_lock do
TheatreWatchingUser.find_or_initialize_by(theatre:, user: current_user).tap {
_1.expires_at = 30.seconds.from_now
}.save!
if (!(theatre.host_user_id?) ||
!(theatre.watching_users.exists?(id: theatre.host_user_id)))
theatre.update!(host_user_id: current_user.id)
end
host_flg = theatre.host_user_id == current_user.id
post_id = theatre.current_post_id
post_started_at = theatre.current_post_started_at
end
render json: {
host_flg:, post_id:, post_started_at:,
watching_users: theatre.watching_users.as_json(only: [:id, :name]) }
end
def next_post
return head :unauthorized unless current_user
theatre = Theatre.find_by(id: params[:id])
return head :not_found unless theatre
return head :forbidden if theatre.host_user != current_user
post = Post.where("url LIKE '%nicovideo.jp%'")
.or(Post.where("url LIKE '%youtube.com%'"))
.order('RAND()')
.first
theatre.update!(current_post: post, current_post_started_at: Time.current)
head :no_content
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class UserIpsController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
-16
ファイルの表示
@@ -1,16 +0,0 @@
class UserPostViewsController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
+10 -5
ファイルの表示
@@ -6,15 +6,20 @@ class UsersController < ApplicationController
end
def verify
ip_bin = IPAddr.new(request.remote_ip).hton
ip_address = IpAddress.find_or_create_by!(ip_address: ip_bin)
user = User.find_by(inheritance_code: params[:code])
render json: if user
{ valid: true, user: user.slice(:id, :name, :inheritance_code, :role) }
else
{ valid: false }
end
return render json: { valid: false } unless user
UserIp.find_or_create_by!(user:, ip_address:)
render json: { valid: true, user: user.slice(:id, :name, :inheritance_code, :role) }
end
def renew
return head :unauthorized unless current_user
user = current_user
user.inheritance_code = SecureRandom.uuid
user.save!
+126 -72
ファイルの表示
@@ -1,35 +1,70 @@
class WikiPagesController < ApplicationController
def index
wiki_pages = WikiPage.all
rescue_from Wiki::Commit::Conflict, with: :render_wiki_conflict
render json: wiki_pages
def index
title = params[:title].to_s.strip
if title.blank?
return render json: WikiPageRepr.base(WikiPage.joins(:tag_name).includes(:tag_name))
end
q = WikiPage.joins(:tag_name).includes(:tag_name)
.where('tag_names.name LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
render json: WikiPageRepr.base(q.limit(20))
end
def show
render_wiki_page_or_404 WikiPage.find(params[:id])
page = WikiPage.joins(:tag_name)
.includes(:tag_name)
.find_by(id: params[:id])
render_wiki_page_or_404 page
end
def show_by_title
render_wiki_page_or_404 WikiPage.find_by(title: params[:title])
title = params[:title].to_s.strip
page = WikiPage.joins(:tag_name)
.includes(:tag_name)
.find_by(tag_name: { name: title })
render_wiki_page_or_404 page
end
def exists
if WikiPage.exists?(id: params[:id])
head :no_content
else
head :not_found
end
end
def exists_by_title
title = params[:title].to_s.strip
if WikiPage.joins(:tag_name).exists?(tag_names: { name: title })
head :no_content
else
head :not_found
end
end
def diff
id = params[:id]
from = params[:from]
return head :bad_request if id.blank?
from = params[:from].presence
to = params[:to].presence
return head :bad_request if id.blank? || from.blank?
wiki_page_from = WikiPage.find(id)
wiki_page_to = WikiPage.find(id)
wiki_page_from.sha = from
wiki_page_to.sha = to
page = WikiPage.joins(:tag_name).includes(:tag_name).find(id)
diffs = Diff::LCS.sdiff(wiki_page_from.body, wiki_page_to.body)
from_rev = from && page.wiki_revisions.find(from)
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
if ((from_rev && !(from_rev.content?)) || !(to_rev&.content?))
return head :unprocessable_entity
end
diffs = Diff::LCS.sdiff(from_rev&.body&.lines || [], to_rev.body.lines)
diff_json = diffs.map { |change|
case change.action
when ?=
{ type: 'context', content: change.old_element }
when ?|
when ?!
[{ type: 'removed', content: change.old_element },
{ type: 'added', content: change.new_element }]
when ?+
@@ -39,97 +74,116 @@ class WikiPagesController < ApplicationController
end
}.flatten.compact
render json: { wiki_page_id: wiki_page_from.id,
title: wiki_page_from.title,
older_sha: wiki_page_from.sha,
newer_sha: wiki_page_to.sha,
diff: diff_json }
render json: { wiki_page_id: page.id,
title: page.title,
older_revision_id: from_rev&.id,
newer_revision_id: to_rev.id,
diff: diff_json }
end
def create
return head :unauthorized unless current_user
return head :forbidden unless ['admin', 'member'].include?(current_user.role)
return head :forbidden unless current_user.gte_member?
wiki_page = WikiPage.new(title: params[:title], created_user: current_user, updated_user: current_user)
if wiki_page.save
wiki_page.set_body params[:body], user: current_user
render json: wiki_page, status: :created
name = params[:title]&.strip
body = params[:body].to_s
return head :unprocessable_entity if name.blank? || body.blank?
tag_name = TagName.find_undiscard_or_create_by!(name:)
page = WikiPage.new(tag_name:, created_user: current_user, updated_user: current_user)
if page.save
message = params[:message].presence
Wiki::Commit.content!(page:, body:, created_user: current_user, message:)
render json: WikiPageRepr.base(page), status: :created
else
render json: { errors: wiki_page.errors.full_messages }, status: :unprocessable_entity
render json: { errors: page.errors.full_messages },
status: :unprocessable_entity
end
end
def update
return head :unauthorized unless current_user
return head :forbidden unless current_user.member?
return head :forbidden unless current_user.gte_member?
title = params[:title]
body = params[:body]
title = params[:title]&.strip
body = params[:body].to_s
return head :unprocessable_entity if title.blank? || body.blank?
wiki_page = WikiPage.find(params[:id])
wiki_page.title = title
wiki_page.updated_user = current_user
wiki_page.set_body(body, user: current_user)
wiki_page.save!
page = WikiPage.find(params[:id])
base_revision_id = page.current_revision.id
if params[:title].present? && params[:title].strip != page.title
return head :unprocessable_entity
end
message = params[:message].presence
Wiki::Commit.content!(page:,
body:,
created_user: current_user,
message:,
base_revision_id:)
head :ok
end
def search
title = params[:title]&.strip
q = WikiPage.all
q = q.where('title LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%") if title.present?
render json: q.limit(20)
index
end
def changes
id = params[:id]
log = if id.present?
wiki.page("#{ id }.md")&.versions
else
wiki.repo.log('main', nil)
end
return render json: [] unless log
id = params[:id].presence
q = WikiRevision.joins(wiki_page: :tag_name)
.includes(:created_user, wiki_page: :tag_name)
.order(id: :desc)
q = q.where(wiki_page_id: id) if id
render json: log.map { |commit|
wiki_page = WikiPage.find(commit.message.split(' ')[1].to_i)
wiki_page.sha = commit.id
next nil if wiki_page.sha.blank?
user = User.find(commit.author.name.to_i)
{ sha: wiki_page.sha,
pred: wiki_page.pred,
succ: wiki_page.succ,
wiki_page: wiki_page && { id: wiki_page.id, title: wiki_page.title },
user: user && { id: user.id, name: user.name },
change_type: commit.message.split(' ')[0].downcase[0...(-1)],
timestamp: commit.authored_date }
render json: q.limit(200).map { |rev|
{ revision_id: rev.id,
pred: rev.base_revision_id,
succ: nil,
wiki_page: { id: rev.wiki_page_id, title: rev.wiki_page.title },
user: rev.created_user && { id: rev.created_user.id, name: rev.created_user.name },
kind: rev.kind,
message: rev.message,
timestamp: rev.created_at }
}.compact
end
private
WIKI_PATH = Rails.root.join('wiki').to_s
def render_wiki_page_or_404 page
return head :not_found unless page
def wiki
@wiki ||= Gollum::Wiki.new(WIKI_PATH)
rev = find_revision(page)
return head :not_found unless rev
if rev.redirect?
return (
redirect_to wiki_page_by_title_path(title: rev.redirect_page.title),
status: :moved_permanently)
end
body = rev.body
revision_id = rev.id
pred = page.pred_revision_id(revision_id)
succ = page.succ_revision_id(revision_id)
updated_at = rev.created_at
render json: WikiPageRepr.base(page).merge(body:, revision_id:, pred:, succ:, updated_at:)
end
def render_wiki_page_or_404 wiki_page
return head :not_found unless wiki_page
def find_revision page
if params[:version].present?
page.wiki_revisions.find_by(id: params[:version])
else
page.current_revision
end
end
wiki_page.sha = params[:version].presence
body = wiki_page.body
sha = wiki_page.sha
pred = wiki_page.pred
succ = wiki_page.succ
render json: wiki_page.as_json.merge(body:, sha:, pred:, succ:)
def render_wiki_conflict err
render json: { error: 'conflict', message: err.message }, status: :conflict
end
end
+21
ファイルの表示
@@ -0,0 +1,21 @@
class Deerjikist < ApplicationRecord
self.primary_key = :platform, :code
belongs_to :tag
validates :platform, presence: true
validates :code, presence: true
validates :tag_id, presence: true
validate :tag_must_be_deerjikist
enum :platform, nico: 'nico', youtube: 'youtube'
private
def tag_must_be_deerjikist
if tag && !(tag.deerjikist?)
errors.add :tag, 'タグはニジラー・カテゴリである必要があります.'
end
end
end
+20
ファイルの表示
@@ -0,0 +1,20 @@
module MyDiscard
extend ActiveSupport::Concern
included { include Discard::Model }
class_methods do
def find_undiscard_or_create_by! attrs, &block
record = with_discarded.find_by(attrs)
if record&.discarded?
record.undiscard!
record.update_columns(created_at: record.reload.updated_at)
end
record or create!(attrs, &block)
rescue ActiveRecord::RecordNotUnique
retry
end
end
end
+1
ファイルの表示
@@ -6,6 +6,7 @@ class NicoTagRelation < ApplicationRecord
validates :tag_id, presence: true
validate :nico_tag_must_be_nico
validate :tag_mustnt_be_nico
private
+53 -24
ファイルの表示
@@ -1,21 +1,25 @@
require 'mini_magick'
class Post < ApplicationRecord
require 'mini_magick'
belongs_to :parent, class_name: 'Post', optional: true, foreign_key: 'parent_id'
belongs_to :uploaded_user, class_name: 'User', optional: true
has_many :post_tags, dependent: :destroy
has_many :tags, through: :post_tags
has_many :user_post_views, dependent: :destroy
has_many :post_similarities_as_post,
class_name: 'PostSimilarity',
foreign_key: :post_id
has_many :post_similarities_as_target_post,
class_name: 'PostSimilarity',
foreign_key: :target_post_id
has_many :post_tags, dependent: :destroy, inverse_of: :post
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
has_many :tags, through: :active_post_tags
has_many :user_post_views, dependent: :delete_all
has_many :post_similarities, dependent: :delete_all
has_one_attached :thumbnail
before_validation :normalise_url
validates :url, presence: true, uniqueness: true
validate :validate_original_created_range
validate :url_must_be_http_url
def as_json options = { }
super(options).merge({ thumbnail: thumbnail.attached? ?
@@ -26,19 +30,15 @@ class Post < ApplicationRecord
super(options).merge(thumbnail: nil)
end
def related(limit: nil)
ids_with_cos =
post_similarities_as_post.select(:target_post_id, :cos)
.map { |ps| [ps.target_post_id, ps.cos] } +
post_similarities_as_target_post.select(:post_id, :cos)
.map { |ps| [ps.post_id, ps.cos] }
def related limit: nil
ids = post_similarities.order(cos: :desc)
ids = ids.limit(limit) if limit
ids = ids.pluck(:target_post_id)
return Post.none if ids.empty?
sorted = ids_with_cos.sort_by { |_, cos| -cos }
ids = sorted.map(&:first)
ids = ids.first(limit) if limit
Post.where(id: ids).index_by(&:id).values_at(*ids)
Post.where(id: ids)
.with_attached_thumbnail
.order(Arel.sql("FIELD(posts.id, #{ ids.join(',') })"))
end
def resized_thumbnail!
@@ -67,4 +67,33 @@ class Post < ApplicationRecord
errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
end
end
def url_must_be_http_url
begin
u = URI.parse(url)
rescue URI::InvalidURIError
errors.add(:url, 'URL が不正です.')
return
end
if !(u in URI::HTTP) || u.host.blank?
errors.add(:url, 'URL が不正です.')
return
end
end
def normalise_url
return if url.blank?
self.url = url.strip
u = URI.parse(url)
return unless u in URI::HTTP
u.host = u.host.downcase if u.host
u.path = u.path.sub(/\/\Z/, '') if u.path.present?
self.url = u.to_s
rescue URI::InvalidURIError
;
end
end
+4 -2
ファイルの表示
@@ -1,4 +1,6 @@
class PostSimilarity < ApplicationRecord
belongs_to :post, class_name: 'Post', foreign_key: 'post_id'
belongs_to :target_post, class_name: 'Post', foreign_key: 'target_post_id'
self.primary_key = :post_id, :target_post_id
belongs_to :post
belongs_to :target_post, class_name: 'Post'
end
+22
ファイルの表示
@@ -1,7 +1,29 @@
class PostTag < ApplicationRecord
include Discard::Model
before_destroy do
raise ActiveRecord::ReadOnlyRecord, '消さないでください.'
end
belongs_to :post
belongs_to :tag, counter_cache: :post_count
belongs_to :created_user, class_name: 'User', optional: true
belongs_to :deleted_user, class_name: 'User', optional: true
validates :post_id, presence: true
validates :tag_id, presence: true
validates :post_id, uniqueness: {
scope: :tag_id,
conditions: -> { where(discarded_at: nil) } }
def discard_by! deleted_user
return self if discarded?
transaction do
update!(discarded_at: Time.current, deleted_user:)
Tag.where(id: tag_id).update_all('post_count = GREATEST(post_count - 1, 0)')
end
self
end
end
+175 -39
ファイルの表示
@@ -1,72 +1,208 @@
class Tag < ApplicationRecord
has_many :post_tags, dependent: :destroy
has_many :posts, through: :post_tags
has_many :tag_aliases, dependent: :destroy
include MyDiscard
class NicoTagNormalisationError < ArgumentError
;
end
default_scope -> { kept }
has_many :post_tags, inverse_of: :tag
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :tag
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
has_many :posts, through: :active_post_tags
has_many :nico_tag_relations, foreign_key: :nico_tag_id, dependent: :destroy
has_many :linked_tags, through: :nico_tag_relations, source: :tag
has_many :reversed_nico_tag_relations, class_name: 'NicoTagRelation',
foreign_key: :tag_id,
dependent: :destroy
has_many :reversed_nico_tag_relations,
class_name: 'NicoTagRelation', foreign_key: :tag_id, dependent: :destroy
has_many :linked_nico_tags, through: :reversed_nico_tag_relations, source: :nico_tag
enum :category, { deerjikist: 'deerjikist',
meme: 'meme',
character: 'character',
general: 'general',
material: 'material',
nico: 'nico',
meta: 'meta' }
has_many :tag_implications, foreign_key: :parent_tag_id, dependent: :destroy
has_many :children, through: :tag_implications, source: :tag
has_many :reversed_tag_implications,
class_name: 'TagImplication', foreign_key: :tag_id, dependent: :destroy
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
has_many :tag_similarities, dependent: :delete_all
has_many :tag_similarities_as_target,
class_name: 'TagSimilarity', foreign_key: :target_tag_id, dependent: :delete_all
has_many :deerjikists, dependent: :delete_all
belongs_to :tag_name
delegate :wiki_page, to: :tag_name
delegate :name, to: :tag_name, allow_nil: true
validates :tag_name, presence: true
enum :category, deerjikist: 'deerjikist',
meme: 'meme',
character: 'character',
general: 'general',
material: 'material',
nico: 'nico',
meta: 'meta'
validates :name, presence: true, length: { maximum: 255 }
validates :category, presence: true, inclusion: { in: Tag.categories.keys }
validate :nico_tag_name_must_start_with_nico
validate :tag_name_must_be_canonical
validate :category_must_be_deerjikist_with_deerjikists
scope :nico_tags, -> { where(category: :nico) }
scope :nico_tags, -> { nico }
CATEGORY_PREFIXES = {
'gen:' => 'general',
'djk:' => 'deerjikist',
'meme:' => 'meme',
'chr:' => 'character',
'mtr:' => 'material',
'meta:' => 'meta' }.freeze
'general:' => :general,
'gen:' => :general,
'deerjikist:' => :deerjikist,
'djk:' => :deerjikist,
'meme:' => :meme,
'character:' => :character,
'chr:' => :character,
'material:' => :material,
'mtr:' => :material,
'meta:' => :meta }.freeze
def name= val
(self.tag_name ||= build_tag_name).name = val
end
def has_wiki = wiki_page.present?
def self.tagme
@tagme ||= Tag.find_or_initialize_by(name: 'タグ希望') do |tag|
tag.category = 'meta'
end
@tagme ||= find_or_create_by_tag_name!('タグ希望', category: :meta)
end
def self.bot
@bot ||= Tag.find_or_initialize_by(name: 'bot操作') do |tag|
tag.category = 'meta'
end
@bot ||= find_or_create_by_tag_name!('bot操作', category: :meta)
end
def self.normalise_tags tag_names, with_tagme: true
def self.no_deerjikist
@no_deerjikist ||= find_or_create_by_tag_name!('ニジラー情報不詳', category: :meta)
end
def self.video
@video ||= find_or_create_by_tag_name!('動画', category: :meta)
end
def self.niconico
@niconico ||= find_or_create_by_tag_name!('ニコニコ', category: :meta)
end
def self.normalise_tags tag_names, with_tagme: true, deny_nico: true
if deny_nico && tag_names.any? { |n| n.downcase.start_with?('nico:') }
raise NicoTagNormalisationError
end
tags = tag_names.map do |name|
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.start_with?(p) } || ['', nil]
name.delete_prefix!(pf)
Tag.find_or_initialize_by(name:).tap do |tag|
if cat && tag.category != cat
tag.category = cat
tag.save!
end
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.downcase.start_with?(p) } || ['', nil]
name = TagName.canonicalise(name.sub(/\A#{ pf }/i, '')).first
find_or_create_by_tag_name!(name, category: (cat || :general)).tap do |tag|
tag.update!(category: cat) if cat && tag.category != cat
end
end
tags << Tag.tagme if with_tagme && tags.size < 20 && tags.none?(Tag.tagme)
tags.uniq
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
tags << Tag.no_deerjikist if tags.all? { |t| !(t.deerjikist?) }
tags.uniq(&:id)
end
def self.expand_parent_tags tags
return [] if tags.blank?
seen = Set.new
result = []
stack = tags.compact.dup
until stack.empty?
tag = stack.pop
next unless tag
tag.parents.each do |parent|
next if seen.include?(parent.id)
seen << parent.id
result << parent
stack << parent
end
end
(result + tags).uniq { |t| t.id }
end
def self.find_or_create_by_tag_name! name, category:
tn = TagName.find_undiscard_or_create_by!(name: name.to_s.strip)
tn = tn.canonical if tn.canonical_id?
Tag.find_undiscard_or_create_by!(tag_name_id: tn.id) do |t|
t.category = category
end
rescue ActiveRecord::RecordNotUnique
retry
end
def self.merge_tags! target_tag, source_tags
target_tag => Tag
Tag.transaction do
Array(source_tags).compact.uniq.each do |source_tag|
source_tag => Tag
next if source_tag == target_tag
source_tag.post_tags.kept.find_each do |source_pt|
post_id = source_pt.post_id
source_pt.discard_by!(nil)
unless PostTag.kept.exists?(post_id:, tag: target_tag)
PostTag.create!(post_id:, tag: target_tag)
end
end
source_tag_name = source_tag.tag_name
if source_tag_name.wiki_page.present?
raise ActiveRecord::RecordInvalid.new(source_tag_name)
end
source_tag.discard!
if source_tag.nico?
source_tag_name.discard!
else
source_tag_name.update_columns(canonical_id: target_tag.tag_name_id,
updated_at: Time.current)
end
end
# 投稿件数を再集計
target_tag.update_columns(post_count: PostTag.kept.where(tag: target_tag).count)
end
target_tag.reload
end
private
def nico_tag_name_must_start_with_nico
if ((category == 'nico' && !(name.start_with?('nico:'))) ||
(category != 'nico' && name.start_with?('nico:')))
n = name.to_s
if ((nico? && !(n.downcase.start_with?('nico:'))) ||
(!(nico?) && n.downcase.start_with?('nico:')))
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
end
end
def tag_name_must_be_canonical
if tag_name&.canonical_id?
errors.add :tag_name, 'tag_names へは実体を示す必要があります.'
end
end
def category_must_be_deerjikist_with_deerjikists
if !(deerjikist?) && deerjikists.exists?
errors.add :category, 'ニジラーと紐づいてゐるタグはニジラー・カテゴリである必要があります.'
end
end
end
-6
ファイルの表示
@@ -1,6 +0,0 @@
class TagAlias < ApplicationRecord
belongs_to :tag
validates :tag_id, presence: true
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
end
+17
ファイルの表示
@@ -0,0 +1,17 @@
class TagImplication < ApplicationRecord
belongs_to :tag, class_name: 'Tag'
belongs_to :parent_tag, class_name: 'Tag'
validates :tag_id, presence: true, uniqueness: { scope: :parent_tag_id }
validates :parent_tag_id, presence: true
validate :parent_tag_mustnt_be_itself
private
def parent_tag_mustnt_be_itself
if parent_tag == tag
errors.add :parent_tag_id, '親タグは子タグと同一であってはなりません.'
end
end
end
+53
ファイルの表示
@@ -0,0 +1,53 @@
class TagName < ApplicationRecord
include MyDiscard
default_scope -> { kept }
has_one :tag
has_one :wiki_page
belongs_to :canonical, class_name: 'TagName', optional: true
has_many :aliases, class_name: 'TagName', foreign_key: :canonical_id
validates :name, presence: true, length: { maximum: 255 }, uniqueness: true
validate :canonical_must_be_canonical
validate :alias_name_must_not_have_prefix
validate :canonical_must_not_be_present_with_tag_or_wiki_page
validate :name_must_be_sanitised
def self.canonicalise names
names = Array(names).map { |n| n.to_s.strip }.reject(&:blank?)
return [] if names.blank?
tns = TagName.includes(:canonical).where(name: names).index_by(&:name)
names.map { |name| tns[name]&.canonical&.name || name }.uniq
end
private
def canonical_must_be_canonical
if canonical&.canonical_id?
errors.add :canonical, 'canonical は実体を示す必要があります.'
end
end
def alias_name_must_not_have_prefix
if canonical_id? && name.to_s.include?(':')
errors.add :name, 'エーリアス名にプレフィクスを含むことはできません.'
end
end
def canonical_must_not_be_present_with_tag_or_wiki_page
if canonical_id? && (tag || wiki_page)
errors.add :canonical, 'タグもしくは Wiki の参照がある名前はエーリアスになれません.'
end
end
def name_must_be_sanitised
if name? && name != TagNameSanitisationRule.sanitise(name)
errors.add :name, '名前に使用できない文字が含まれてゐます.'
end
end
end
+58
ファイルの表示
@@ -0,0 +1,58 @@
class TagNameSanitisationRule < ApplicationRecord
include Discard::Model
self.primary_key = :priority
default_scope -> { kept }
validates :source_pattern, presence: true, uniqueness: true
validate :source_pattern_must_be_regexp
class << self
def sanitise(name) =
rules.reduce(name.dup) { |name, (pattern, replacement)| name.gsub(pattern, replacement) }
def apply!
TagName.find_each do |tn|
name = sanitise(tn.name)
next if name == tn.name
TagName.transaction do
existing_tn = TagName.find_by(name:)
if existing_tn
existing_tn = existing_tn.canonical || existing_tn
next if existing_tn.id == tn.id
existing_tag = Tag.find_by(tag_name_id: existing_tn.id)
source_tag = Tag.find_by(tag_name_id: tn.id)
if existing_tag
Tag.merge_tags!(existing_tag, source_tag) if tn.tag
elsif source_tag
source_tag.update_columns(tag_name_id: existing_tn.id, updated_at: Time.current)
end
tn.discard!
next
end
# TagName 側の自動サニタイズを回避
tn.update_columns(name:, updated_at: Time.current)
end
end
end
private
def rules = kept.order(:priority).map { |r| [Regexp.new(r.source_pattern), r.replacement] }
end
private
def source_pattern_must_be_regexp
Regexp.new(source_pattern)
rescue RegexpError
errors.add :source_pattern, '変な正規表現だね〜(笑)'
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
class TagSimilarity < ApplicationRecord
self.primary_key = :tag_id, :target_tag_id
belongs_to :tag
belongs_to :target_tag, class_name: 'Tag'
end
+13
ファイルの表示
@@ -0,0 +1,13 @@
class Theatre < ApplicationRecord
include MyDiscard
has_many :comments, class_name: 'TheatreComment'
has_many :theatre_watching_users, dependent: :delete_all
has_many :active_theatre_watching_users, -> { active },
class_name: 'TheatreWatchingUser', inverse_of: :theatre
has_many :watching_users, through: :active_theatre_watching_users, source: :user
belongs_to :host_user, class_name: 'User', optional: true
belongs_to :current_post, class_name: 'Post', optional: true
belongs_to :created_by_user, class_name: 'User'
end
+8
ファイルの表示
@@ -0,0 +1,8 @@
class TheatreComment < ApplicationRecord
include Discard::Model
self.primary_key = :theatre_id, :no
belongs_to :theatre
belongs_to :user
end
+13
ファイルの表示
@@ -0,0 +1,13 @@
class TheatreWatchingUser < ApplicationRecord
self.primary_key = :theatre_id, :user_id
belongs_to :theatre
belongs_to :user
scope :active, -> { where('expires_at >= ?', Time.current) }
scope :expired, -> { where('expires_at < ?', Time.current) }
def active? = expires_at >= Time.current
def refresh! = update!(expires_at: 30.seconds.from_now)
end
+9 -16
ファイルの表示
@@ -1,30 +1,23 @@
class User < ApplicationRecord
enum :role, { guest: 'guest', member: 'member', admin: 'admin' }
enum :role, guest: 'guest', member: 'member', admin: 'admin'
validates :name, length: { maximum: 255 }
validates :inheritance_code, presence: true, length: { maximum: 64 }
validates :role, presence: true, inclusion: { in: roles.keys }
validates :banned, inclusion: { in: [true, false] }
has_many :posts
has_many :created_posts,
class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
has_many :settings
has_many :ip_addresses
has_many :user_ips, dependent: :destroy
has_many :ip_addresses, through: :user_ips
has_many :user_post_views, dependent: :destroy
has_many :viewed_posts, through: :user_post_views, source: :post
has_many :created_wiki_pages, class_name: 'WikiPage', foreign_key: 'created_user_id', dependent: :nullify
has_many :updated_wiki_pages, class_name: 'WikiPage', foreign_key: 'updated_user_id', dependent: :nullify
has_many :created_wiki_pages,
class_name: 'WikiPage', foreign_key: :created_user_id, dependent: :nullify
has_many :updated_wiki_pages,
class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify
def viewed? post
user_post_views.exists? post_id: post.id
end
def member?
['member', 'admin'].include?(role)
end
def admin?
role == 'admin'
end
def viewed?(post) = user_post_views.exists?(post_id: post.id)
def gte_member? = member? || admin?
end
+2
ファイルの表示
@@ -1,4 +1,6 @@
class UserIp < ApplicationRecord
self.primary_key = :user_id, :ip_address_id
belongs_to :user
belongs_to :ip_address
+2
ファイルの表示
@@ -1,4 +1,6 @@
class UserPostView < ApplicationRecord
self.primary_key = :user_id, :post_id
belongs_to :user
belongs_to :post
+15
ファイルの表示
@@ -0,0 +1,15 @@
class WikiLine < ApplicationRecord
has_many :wiki_revision_lines, dependent: :restrict_with_exception
validates :sha256, presence: true, uniqueness: true, length: { is: 64 }
validates :body, presence: true
def self.upsert_by_body! body
sha = Digest::SHA256.hexdigest(body)
now = Time.current
upsert(sha256: sha, body:, created_at: now, updated_at: now)
find_by!(sha256: sha)
end
end
+41 -65
ファイルの表示
@@ -1,80 +1,56 @@
require 'gollum-lib'
require 'set'
class WikiPage < ApplicationRecord
belongs_to :tag, optional: true
belongs_to :created_user, class_name: 'User', foreign_key: 'created_user_id'
belongs_to :updated_user, class_name: 'User', foreign_key: 'updated_user_id'
include MyDiscard
validates :title, presence: true, length: { maximum: 255 }, uniqueness: true
default_scope -> { kept }
def as_json options = { }
self.sha = nil
super options
has_many :wiki_revisions, dependent: :destroy
belongs_to :created_user, class_name: 'User'
belongs_to :updated_user, class_name: 'User'
has_many :redirected_from_revisions,
class_name: 'WikiRevision',
foreign_key: :redirect_page_id,
dependent: :nullify
belongs_to :tag_name
validates :tag_name, presence: true
def title = tag_name.name
def title= val
(self.tag_name ||= build_tag_name).name = val
end
def sha= val
if val.present?
@sha = val
@page = wiki.page("#{ id }.md", @sha)
else
@page = wiki.page("#{ id }.md")
@sha = @page.versions.first.id
end
vers = @page.versions
idx = vers.find_index { |ver| ver.id == @sha }
if idx
@pred = vers[idx + 1]&.id
@succ = idx.positive? ? vers[idx - 1].id : nil
@updated_at = vers[idx].authored_date
else
@sha = nil
@pred = nil
@succ = nil
@updated_at = nil
end
@sha
end
def sha
@sha
end
def pred
@pred
end
def succ
@succ
end
def updated_at
@updated_at
end
def current_revision = wiki_revisions.order(id: :desc).first
def body
sha = nil unless @page
@page&.raw_data&.force_encoding('UTF-8')
rev = current_revision
rev.body if rev&.content?
end
def set_body content, user:
commit_info = { name: user.id.to_s,
email: 'dummy@example.com' }
page = wiki.page("#{ id }.md")
if page
commit_info[:message] = "Updated #{ id }"
wiki.update_page(page, id.to_s, :markdown, content, commit_info)
else
commit_info[:message] = "Created #{ id }"
wiki.write_page(id.to_s, :markdown, content, commit_info)
def resolve_redirect limit: 10
page = self
visited = Set.new
limit.times do
return page if visited.include?(page.id)
visited.add(page.id)
rev = page.current_revision
return page if !(rev&.redirect?) || !(rev.redirect_page)
page = rev.redirect_page
end
page
end
private
WIKI_PATH = Rails.root.join('wiki').to_s
def wiki
@wiki ||= Gollum::Wiki.new(WIKI_PATH)
end
def pred_revision_id(revision_id) =
wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
def succ_revision_id(revision_id) =
wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
end
+55
ファイルの表示
@@ -0,0 +1,55 @@
class WikiRevision < ApplicationRecord
belongs_to :wiki_page
belongs_to :base_revision, class_name: 'WikiRevision', optional: true
belongs_to :created_user, class_name: 'User'
belongs_to :redirect_page, class_name: 'WikiPage', optional: true
has_many :wiki_revision_lines, dependent: :delete_all
has_many :wiki_lines, through: :wiki_revision_lines
enum :kind, content: 0, redirect: 1
validates :kind, presence: true
validates :lines_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :tree_sha256, length: { is: 64 }, allow_nil: true
validate :kind_consistency
def body
return unless content?
wiki_revision_lines
.includes(:wiki_line)
.order(:position)
.map { |rev| rev.wiki_line.body }
.join("\n")
end
private
def kind_consistency
if content?
if tree_sha256.blank?
errors.add(:tree_sha256, '種類がページの場合は必須です.')
end
if redirect_page_id.present?
errors.add(:redirect_page_id, '種類がページの場合は空である必要があります.')
end
end
if redirect?
if redirect_page_id.blank?
errors.add(:redirect_page_id, '種類がリダイレクトの場合は必須です.')
end
if tree_sha256.present?
errors.add(:tree_sha256, '種類がリダイレクトの場合は空である必要があります.')
end
if lines_count.to_i > 0
errors.add(:lines_count, '種類がリダイレクトの場合は 0 である必要があります.')
end
end
end
end
+8
ファイルの表示
@@ -0,0 +1,8 @@
class WikiRevisionLine < ApplicationRecord
belongs_to :wiki_revision
belongs_to :wiki_line
validates :position, presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :position, uniqueness: { scope: :wiki_revision_id }
end
+16
ファイルの表示
@@ -0,0 +1,16 @@
# frozen_string_literal: true
module DeerjikistRepr
BASE = { only: [:platform, :code], include: { tag: TagRepr::BASE } }.freeze
module_function
def base deerjikist
deerjikist.as_json(BASE)
end
def many deerjikists
deerjikists.map { |d| base(d) }
end
end
+20
ファイルの表示
@@ -0,0 +1,20 @@
# frozen_string_literal: true
module PostRepr
BASE = { include: { tags: TagRepr::BASE, uploaded_user: UserRepr::BASE } }.freeze
module_function
def base post, current_user = nil
json = post.as_json(BASE)
return json.merge(viewed: false) unless current_user
viewed = current_user.viewed?(post)
json.merge(viewed:)
end
def many posts, current_user = nil
posts.map { |p| base(p, current_user) }
end
end
+17
ファイルの表示
@@ -0,0 +1,17 @@
# frozen_string_literal: true
module TagRepr
BASE = { only: [:id, :category, :post_count, :created_at, :updated_at],
methods: [:name, :has_wiki] }.freeze
module_function
def base tag
tag.as_json(BASE)
end
def many tags
tags.map { |t| base(t) }
end
end
+17
ファイルの表示
@@ -0,0 +1,17 @@
# frozen_string_literal: true
module TheatreRepr
BASE = { only: [:id, :name, :opens_at, :closes_at, :created_at, :updated_at],
include: { created_by_user: { only: [:id, :name] } } }.freeze
module_function
def base theatre
theatre.as_json(BASE)
end
def many theatre
theatre.map { |t| base(t) }
end
end
+16
ファイルの表示
@@ -0,0 +1,16 @@
# frozen_string_literal: true
module UserRepr
BASE = { only: [:id, :name] }.freeze
module_function
def base user
user.as_json(BASE)
end
def many users
users.map { |u| base(u) }
end
end
+16
ファイルの表示
@@ -0,0 +1,16 @@
# frozen_string_literal: true
module WikiPageRepr
BASE = { methods: [:title] }.freeze
module_function
def base wiki_page
wiki_page.as_json(BASE)
end
def many wiki_pages
wiki_pages.map { |p| base(p) }
end
end
+106
ファイルの表示
@@ -0,0 +1,106 @@
module Similarity
class Calc
def self.call model, tgt
similarity_model = "#{ model.name }Similarity".constantize
# 最大保存件数
n = 20
similarity_model.delete_all
posts = model.includes(tgt).select(:id).to_a
tag_ids = { }
tag_cnts = { }
posts.each do |p|
arr = p.public_send(tgt).map(&:id).sort
tag_ids[p.id] = arr
tag_cnts[p.id] = arr.size
end
intersection_size = -> a, b do
i = 0
j = 0
cnt = 0
while i < a.size && j < b.size
a_i = a[i]
b_j = b[j]
if a_i == b_j
cnt += 1
i += 1
j += 1
elsif a_i < b_j
i += 1
else
j += 1
end
end
cnt
end
push_topk = -> list, cos, target_id do
return if list.size >= n && cos <= list[-1][0]
idx = nil
list.each_with_index do |(c, tid), i|
if tid == target_id
idx = i
break
end
end
if idx
return if cos <= list[idx][0]
list.delete_at(idx)
end
insert_at = list.size
list.each_with_index do |(c, _), i|
if cos > c
insert_at = i
break
end
end
list.insert(insert_at, [cos, target_id])
list.pop if list.size > n
end
top = Hash.new { |h, key| h[key] = [] }
ids = posts.map(&:id)
ids.each_with_index do |post_id, i|
a = tag_ids[post_id]
a_cnt = tag_cnts[post_id]
((i + 1)...ids.size).each do |j|
target_id = ids[j]
b = tag_ids[target_id]
b_cnt = tag_cnts[target_id]
norm = Math.sqrt(a_cnt * b_cnt)
cos = norm.zero? ? 0.0 : intersection_size.(a, b).fdiv(norm)
push_topk.(top[post_id], cos, target_id)
push_topk.(top[target_id], cos, post_id)
end
end
buf = []
flush = -> do
return if buf.empty?
similarity_model.insert_all!(buf)
buf.clear
end
top.each do |post_id, list|
list.each do |cos, target_post_id|
buf << { "#{ model.name.underscore }_id".to_sym => post_id,
"target_#{ model.name.underscore }_id".to_sym => target_post_id,
cos: }
flush.call if buf.size >= 1_000
end
end
flush.call
end
end
end
+122
ファイルの表示
@@ -0,0 +1,122 @@
require 'digest'
module Wiki
class Commit
class Conflict < StandardError
;
end
def self.content! page:, body:, created_user:, message: nil, base_revision_id: nil
new(page:, created_user:).content!(body:, message:, base_revision_id:)
end
def self.redirect! page:, redirect_page:, created_user:, message: nil, base_revision_id: nil
new(page:, created_user:).redirect!(redirect_page:, message:, base_revision_id:)
end
def initialize page:, created_user:
@page = page
@created_user = created_user
end
def content! body:, message:, base_revision_id:
normalised = normalise_body(body)
lines = split_lines(normalised)
line_shas = lines.map { |line| Digest::SHA256.hexdigest(line) }
tree_sha = Digest::SHA256.hexdigest(line_shas.join(','))
line_id_by_sha = upsert_lines!(lines, line_shas)
line_ids = line_shas.map { |sha| line_id_by_sha.fetch(sha) }
ActiveRecord::Base.transaction do
@page.lock!
if base_revision_id.present?
current_id = @page.wiki_revisions.maximum(:id)
if current_id && current_id != base_revision_id.to_i
raise Conflict,
"競合が発生してゐます(現在の Id.#{ current_id },ベース Id.#{ base_revision_id })."
end
end
rev = WikiRevision.create!(
wiki_page: @page,
base_revision_id:,
created_user: @created_user,
kind: :content,
redirect_page_id: nil,
message:,
lines_count: lines.length,
tree_sha256: tree_sha)
rows = line_ids.each_with_index.map do |line_id, pos|
{ wiki_revision_id: rev.id, wiki_line_id: line_id, position: pos }
end
WikiRevisionLine.insert_all!(rows)
rev
end
end
def redirect! redirect_page:, message:, base_revision_id:
ActiveRecord::Base.transaction do
@page.lock!
if base_revision_id.present?
current_id = @page.wiki_revisions.maximum(:id)
if current_id && current_id != base_revision_id.to_i
raise Conflict,
"競合が発生してゐます(現在の Id.#{ current_id },ベース Id.#{ base_revision_id })."
end
end
WikiRevision.create!(
wiki_page: @page,
base_revision_id:,
created_user: @created_user,
kind: :redirect,
redirect_page:,
message:,
lines_count: 0,
tree_sha256: nil)
end
end
private
def normalise_body body
s = body.to_s
s.gsub!("\r\n", "\n")
s.encode('UTF-8', invalid: :replace, undef: :replace, replace: '🖕')
end
def split_lines body
body.split("\n")
end
def upsert_lines! lines, line_shas
now = Time.current
id_by_sha = WikiLine.where(sha256: line_shas).pluck(:sha256, :id).to_h
missing_rows = []
line_shas.each_with_index do |sha, i|
next if id_by_sha.key?(sha)
missing_rows << { sha256: sha,
body: lines[i],
created_at: now,
updated_at: now }
end
if missing_rows.any?
WikiLine.upsert_all(missing_rows)
id_by_sha = WikiLine.where(sha256: line_shas).pluck(:sha256, :id).to_h
end
id_by_sha
end
end
end
+3
ファイルの表示
@@ -11,6 +11,9 @@ module Backend
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 8.0
config.i18n.available_locales = [:ja, :en]
config.i18n.default_locale = :ja
# Please, add to the `ignore` list any other `lib` subdirectories that do
# not contain `.rb` files, or that should not be reloaded or eager loaded.
# Common ones are `templates`, `generators`, or `middleware`, for example.
+5 -1
ファイルの表示
@@ -28,4 +28,8 @@
# enabled: "ON"
en:
hello: "Hello world"
activerecord:
errors:
messages:
record_invalid: "Validation failed: %{errors}"
taken: 'イキスギ!'
+2
ファイルの表示
@@ -0,0 +1,2 @@
ja:
hello: 'ぬ゛〜゛ん゛'
+72 -33
ファイルの表示
@@ -1,45 +1,84 @@
Rails.application.routes.draw do
get 'tags/nico', to: 'nico_tags#index'
put 'tags/nico/:id', to: 'nico_tags#update'
get 'tags/autocomplete', to: 'tags#autocomplete'
get 'tags/name/:name', to: 'tags#show_by_name'
get 'posts/random', to: 'posts#random'
post 'posts/:id/viewed', to: 'posts#viewed'
delete 'posts/:id/viewed', to: 'posts#unviewed'
get 'preview/title', to: 'preview#title'
get 'preview/thumbnail', to: 'preview#thumbnail'
get 'wiki/title/:title', to: 'wiki_pages#show_by_title'
get 'wiki/search', to: 'wiki_pages#search'
get 'wiki/changes', to: 'wiki_pages#changes'
get 'wiki/:id/diff', to: 'wiki_pages#diff'
get 'wiki/:id', to: 'wiki_pages#show'
get 'wiki', to: 'wiki_pages#index'
post 'wiki', to: 'wiki_pages#create'
put 'wiki/:id', to: 'wiki_pages#update'
post 'users/code/renew', to: 'users#renew'
resources :nico_tags, path: 'tags/nico', only: [:index, :update]
scope 'tags/:parent_id/children', controller: :tag_children do
post ':child_id', action: :create
delete ':child_id', action: :destroy
end
resources :tags, only: [:index, :show, :update] do
collection do
get :autocomplete
scope :name do
get ':name/deerjikists', action: :deerjikists_by_name
get ':name', action: :show_by_name
end
end
member do
get :deerjikists
end
end
scope :preview, controller: :preview do
get :title
get :thumbnail
end
resources :wiki_pages, path: 'wiki', only: [:index, :show, :create, :update] do
collection do
get :search
get :changes
scope :title do
get ':title/exists', action: :exists_by_title
get ':title', action: :show_by_title
end
end
member do
get :exists
get :diff
end
end
resources :posts, only: [:index, :show, :create, :update] do
collection do
get :random
get :changes
end
member do
post :viewed
delete :viewed, action: :unviewed
end
end
resources :posts
resources :ip_addresses
resources :nico_tag_relations
resources :post_tags
resources :settings
resources :tag_aliases
resources :tags
resources :user_ips
resources :user_post_views
resources :users, only: [:create, :update] do
collection do
post :verify
get :me
post 'code/renew', action: :renew
end
end
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
resources :deerjikists, only: [] do
collection do
scope ':platform/:code' do
get '', action: :show
put '', action: :update
delete '', action: :destroy
end
end
end
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
# get "up" => "rails/health#show", as: :rails_health_check
resources :theatres, only: [:show] do
member do
put :watching
patch :next_post
end
# Defines the root path route ("/")
# root "posts#index"
resources :comments, controller: :theatre_comments, only: [:index, :create]
end
end
+9
ファイルの表示
@@ -0,0 +1,9 @@
class CreateTagImplications < ActiveRecord::Migration[8.0]
def change
create_table :tag_implications do |t|
t.references :tag, null: false, foreign_key: { to_table: :tags }
t.references :parent_tag, null: false, foreign_key: { to_table: :tags }
t.timestamps
end
end
end
+36
ファイルの表示
@@ -0,0 +1,36 @@
class AddDiscardToPostTags < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
DELETE
pt1
FROM
post_tags pt1
INNER JOIN
post_tags pt2
ON
pt1.post_id = pt2.post_id
AND pt1.tag_id = pt2.tag_id
AND pt1.id > pt2.id
;
SQL
add_column :post_tags, :discarded_at, :datetime
add_index :post_tags, :discarded_at
add_column :post_tags, :is_active, :boolean,
as: 'discarded_at IS NULL', stored: true
add_column :post_tags, :active_unique_key, :string,
as: "CASE WHEN discarded_at IS NULL THEN CONCAT(post_id, ':', tag_id) ELSE NULL END",
stored: true
add_index :post_tags, :active_unique_key, unique: true, name: 'idx_post_tags_active_unique'
add_index :post_tags, [:post_id, :discarded_at]
add_index :post_tags, [:tag_id, :discarded_at]
end
def down
raise ActiveRecord::IrreversibleMigration, '戻せません.'
end
end
+5
ファイルの表示
@@ -0,0 +1,5 @@
class RenameIpAdressColumnToIpAddresses < ActiveRecord::Migration[8.0]
def change
rename_column :ip_addresses, :ip_adress, :ip_address
end
end
+27
ファイルの表示
@@ -0,0 +1,27 @@
class AddUniqueIndexToTagImplications < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
DELETE
ti1
FROM
tag_implications ti1
INNER JOIN
tag_implications ti2
ON
ti1.tag_id = ti2.tag_id
AND ti1.parent_tag_id = ti2.parent_tag_id
AND ti1.id > ti2.id
;
SQL
add_index :tag_implications, [:tag_id, :parent_tag_id],
unique: true,
name: 'index_tag_implications_on_tag_id_and_parent_tag_id'
end
def down
# NOTE: 重複削除は復元されなぃ.
remove_index :tag_implications,
name: 'index_tag_implications_on_tag_id_and_parent_tag_id'
end
end
+5
ファイルの表示
@@ -0,0 +1,5 @@
class RemoveTagFromWikiPages < ActiveRecord::Migration[7.0]
def change
remove_reference :wiki_pages, :tag, if_exists: true
end
end
+11
ファイルの表示
@@ -0,0 +1,11 @@
class CreateWikiLines < ActiveRecord::Migration[7.0]
def change
create_table :wiki_lines do |t|
t.string :sha256, null: false, limit: 64
t.text :body, null: false
t.timestamps
end
add_index :wiki_lines, :sha256, unique: true
end
end
+19
ファイルの表示
@@ -0,0 +1,19 @@
class CreateWikiRevisions < ActiveRecord::Migration[7.0]
def change
create_table :wiki_revisions do |t|
t.references :wiki_page, null: false, foreign_key: true
t.references :base_revision, foreign_key: { to_table: :wiki_revisions }
t.references :created_user, null: false, foreign_key: { to_table: :users }
t.integer :kind, null: false, default: 0 # 0: content, 1: redirect
t.references :redirect_page, foreign_key: { to_table: :wiki_pages }
t.string :message
t.integer :lines_count, null: false, default: 0
t.string :tree_sha256, limit: 64
t.timestamps
end
add_index :wiki_revisions, :tree_sha256
add_index :wiki_revisions, [:wiki_page_id, :id]
add_index :wiki_revisions, :kind
end
end
+12
ファイルの表示
@@ -0,0 +1,12 @@
class CreateWikiRevisionLines < ActiveRecord::Migration[7.0]
def change
create_table :wiki_revision_lines do |t|
t.references :wiki_revision, null: false, foreign_key: true
t.integer :position, null: false
t.references :wiki_line, null: false, foreign_key: true
end
add_index :wiki_revision_lines, [:wiki_revision_id, :position], unique: true
add_index :wiki_revision_lines, [:wiki_revision_id, :wiki_line_id]
end
end
+27
ファイルの表示
@@ -0,0 +1,27 @@
class MakeThumbnailBaseNullableInPosts < ActiveRecord::Migration[7.0]
def up
change_column_null :posts, :thumbnail_base, true
execute <<~SQL
UPDATE
posts
SET
thumbnail_base = NULL
WHERE
thumbnail_base = ''
SQL
end
def down
execute <<~SQL
UPDATE
posts
SET
thumbnail_base = ''
WHERE
thumbnail_base IS NULL
SQL
change_column_null :posts, :thumbnail_base, false
end
end
+28
ファイルの表示
@@ -0,0 +1,28 @@
class MakeTitleNullableInPosts < ActiveRecord::Migration[7.0]
def up
change_column_null :posts, :title, true
execute <<~SQL
UPDATE
posts
SET
title = NULL
WHERE
title = ''
SQL
end
def down
execute <<~SQL
UPDATE
posts
SET
title = ''
WHERE
title IS NULL
SQL
change_column_null :posts, :title, false
end
end
+10
ファイルの表示
@@ -0,0 +1,10 @@
class CreateTagNames < ActiveRecord::Migration[7.0]
def change
create_table :tag_names do |t|
t.string :name, limit: 255, null: false
t.references :canonical, null: true, foreign_key: { to_table: :tag_names }, index: true
t.timestamps
end
add_index :tag_names, :name, unique: true
end
end
+42
ファイルの表示
@@ -0,0 +1,42 @@
class AddTagNameToTags < ActiveRecord::Migration[7.0]
class Tag < ApplicationRecord
self.table_name = 'tags'
end
class TagName < ApplicationRecord
self.table_name = 'tag_names'
end
def up
add_reference :tags, :tag_name, null: true, foreign_key: true, index: false, after: :id
add_index :tags, :tag_name_id, unique: true
Tag.find_each do |tag|
name = tag.read_attribute(:name)
tn = TagName.find_or_create_by!(name:) do |r|
r.canonical_id = nil
end
tag.update_columns(tag_name_id: tn.id)
end
change_column_null :tags, :tag_name_id, false
remove_column :tags, :name
end
def down
add_column :tags, :name, :string, limit: 255, null: true, after: :id
Tag.find_each do |tag|
tag_name_id = tag.read_attribute(:tag_name_id)
name = TagName.find(tag_name_id).read_attribute(:name)
tag.update_columns(name:)
end
change_column_null :tags, :name, false
remove_foreign_key :tags, column: :tag_name_id
remove_index :tags, :tag_name_id
remove_column :tags, :tag_name_id
end
end
+42
ファイルの表示
@@ -0,0 +1,42 @@
class AddTagNameToWikiPages < ActiveRecord::Migration[7.0]
class WikiPage < ApplicationRecord
self.table_name = 'wiki_pages'
end
class TagName < ApplicationRecord
self.table_name = 'tag_names'
end
def up
add_reference :wiki_pages, :tag_name, null: true, foreign_key: true, index: false, after: :id
add_index :wiki_pages, :tag_name_id, unique: true
WikiPage.find_each do |page|
name = page.read_attribute(:title)
tn = TagName.find_or_create_by!(name:) do |r|
r.canonical_id = nil
end
page.update_columns(tag_name_id: tn.id)
end
change_column_null :wiki_pages, :tag_name_id, false
remove_column :wiki_pages, :title
end
def down
add_column :wiki_pages, :title, :string, limit: 255, null: true, after: :id
WikiPage.find_each do |page|
tag_name_id = page.read_attribute(:tag_name_id)
title = TagName.find(tag_name_id).read_attribute(:name)
page.update_columns(title:)
end
change_column_null :wiki_pages, :title, false
remove_foreign_key :wiki_pages, column: :tag_name_id
remove_index :wiki_pages, :tag_name_id
remove_column :wiki_pages, :tag_name_id
end
end
+9
ファイルの表示
@@ -0,0 +1,9 @@
class DropTagAliases < ActiveRecord::Migration[7.0]
def up
drop_table :tag_aliases
end
def down
raise ActiveRecord::IrreversibleMigration, '戻せません.'
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
class AddUniqueIndexToUrlInPosts < ActiveRecord::Migration[7.1]
def change
change_column :posts, :url, :string, limit: 768
add_index :posts, :url, unique: true, name: 'index_posts_on_url'
end
end
+43
ファイルの表示
@@ -0,0 +1,43 @@
class ChangePostSimilaritiesToCompositePk < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
ALTER TABLE
post_similarities
MODIFY COLUMN id BIGINT NOT NULL
;
SQL
execute <<~SQL
ALTER TABLE
post_similarities
DROP PRIMARY KEY
;
SQL
remove_column :post_similarities, :id
execute <<~SQL
ALTER TABLE
post_similarities
ADD PRIMARY KEY (post_id, target_post_id)
;
SQL
end
def down
execute <<~SQL
ALTER TABLE
post_similarities
DROP PRIMARY KEY
;
SQL
execute <<~SQL
ALTER TABLE
post_similarities
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
, ADD PRIMARY KEY (id)
;
SQL
end
end
+43
ファイルの表示
@@ -0,0 +1,43 @@
class ChangeTagSimilaritiesToCompositePk < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
ALTER TABLE
tag_similarities
MODIFY COLUMN id BIGINT NOT NULL
;
SQL
execute <<~SQL
ALTER TABLE
tag_similarities
DROP PRIMARY KEY
;
SQL
remove_column :tag_similarities, :id
execute <<~SQL
ALTER TABLE
tag_similarities
ADD PRIMARY KEY (tag_id, target_tag_id)
;
SQL
end
def down
execute <<~SQL
ALTER TABLE
tag_similarities
DROP PRIMARY KEY
;
SQL
execute <<~SQL
ALTER TABLE
tag_similarities
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
, ADD PRIMARY KEY (id)
;
SQL
end
end
+9
ファイルの表示
@@ -0,0 +1,9 @@
class AddIndexToPostSimilarities < ActiveRecord::Migration[8.0]
def change
remove_index :post_similarities, name: 'index_post_similarities_on_post_id'
add_index :post_similarities, [:post_id, :cos],
order: { cos: :desc },
name: 'index_post_similarities_on_post_id_and_cos'
end
end
+9
ファイルの表示
@@ -0,0 +1,9 @@
class AddIndexToTagSimilarities < ActiveRecord::Migration[8.0]
def change
remove_index :tag_similarities, name: 'index_tag_similarities_on_tag_id'
add_index :tag_similarities, [:tag_id, :cos],
order: { cos: :desc },
name: 'index_tag_similarities_on_tag_id_and_cos'
end
end
+5
ファイルの表示
@@ -0,0 +1,5 @@
class AddUniqueIndexToIpAddresses < ActiveRecord::Migration[8.0]
def change
add_index :ip_addresses, :ip_address, unique: true, name: 'index_ip_addresses_on_ip_address'
end
end
+47
ファイルの表示
@@ -0,0 +1,47 @@
class ChangeUserIpsToCompositePk < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
ALTER TABLE
user_ips
MODIFY COLUMN id BIGINT NOT NULL
;
SQL
execute <<~SQL
ALTER TABLE
user_ips
DROP PRIMARY KEY
;
SQL
remove_column :user_ips, :id
execute <<~SQL
ALTER TABLE
user_ips
ADD PRIMARY KEY (user_id, ip_address_id)
;
SQL
remove_index :user_ips, name: 'index_user_ips_on_user_id'
end
def down
execute <<~SQL
ALTER TABLE
user_ips
DROP PRIMARY KEY
;
SQL
execute <<~SQL
ALTER TABLE
user_ips
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
, ADD PRIMARY KEY (id)
;
SQL
add_index :user_ips, :user_id, name: 'index_user_ips_on_user_id'
end
end
+47
ファイルの表示
@@ -0,0 +1,47 @@
class ChangeUserPostViewsToCompositePk < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
ALTER TABLE
user_post_views
MODIFY COLUMN id BIGINT NOT NULL
;
SQL
execute <<~SQL
ALTER TABLE
user_post_views
DROP PRIMARY KEY
;
SQL
remove_column :user_post_views, :id
execute <<~SQL
ALTER TABLE
user_post_views
ADD PRIMARY KEY (user_id, post_id)
;
SQL
remove_index :user_post_views, name: 'index_user_post_views_on_user_id'
end
def down
execute <<~SQL
ALTER TABLE
user_post_views
DROP PRIMARY KEY
;
SQL
execute <<~SQL
ALTER TABLE
user_post_views
ADD COLUMN id BIGINT NOT NULL AUTO_INCREMENT FIRST
, ADD PRIMARY KEY (id)
;
SQL
add_index :user_post_views, :user_id, name: 'index_user_post_views_on_user_id'
end
end
+10
ファイルの表示
@@ -0,0 +1,10 @@
class CreateDeerjikists < ActiveRecord::Migration[8.0]
def change
create_table :deerjikists, primary_key: [:platform, :code] do |t|
t.string :platform, null: false, limit: 16
t.string :code, null: false
t.references :tag, null: false
t.timestamps
end
end
end
+31
ファイルの表示
@@ -0,0 +1,31 @@
class CreateTagNameSanitisationRules < ActiveRecord::Migration[8.0]
def up
create_table :tag_name_sanitisation_rules, id: :integer, primary_key: :priority do |t|
t.string :source_pattern, null: false
t.string :replacement, null: false
t.timestamps
t.datetime :discarded_at
t.index :source_pattern, unique: true
t.index :discarded_at
end
now = ActiveRecord::Base.connection.quote(Time.current)
execute <<~SQL
INSERT INTO
tag_name_sanitisation_rules(priority, source_pattern, replacement, created_at, updated_at)
VALUES
(10, '\\\\*', '_', #{ now }, #{ now })
, (20, '\\\\?', '_', #{ now }, #{ now })
, (25, '\\\\/', '_', #{ now }, #{ now })
, (30, '_+', '_', #{ now }, #{ now })
, (40, '_$', '', #{ now }, #{ now })
, (45, '^([^:]+\\\\:)?_', '\\\\1', #{ now }, #{ now })
, (50, '^([^:]+\\\\:)?$', '\\\\1null', #{ now }, #{ now })
;
SQL
end
def down
drop_table :tag_name_sanitisation_rules
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
class AddDiscardedAtToTags < ActiveRecord::Migration[8.0]
def change
add_column :tags, :discarded_at, :datetime
add_index :tags, :discarded_at
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
class AddDiscardedAtToTagNames < ActiveRecord::Migration[8.0]
def change
add_column :tag_names, :discarded_at, :datetime
add_index :tag_names, :discarded_at
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
class AddDiscardedAtToWikiPages < ActiveRecord::Migration[8.0]
def change
add_column :wiki_pages, :discarded_at, :datetime
add_index :wiki_pages, :discarded_at
end
end
+17
ファイルの表示
@@ -0,0 +1,17 @@
class CreateTheatres < ActiveRecord::Migration[8.0]
def change
create_table :theatres do |t|
t.string :name
t.datetime :opens_at, null: false, index: true
t.datetime :closes_at, index: true
t.integer :kind, null: false, index: true
t.references :current_post, foreign_key: { to_table: :posts }, index: true
t.datetime :current_post_started_at
t.integer :next_comment_no, null: false, default: 1
t.references :host_user, foreign_key: { to_table: :users }
t.references :created_by_user, null: false, foreign_key: { to_table: :users }, index: true
t.timestamps
t.datetime :discarded_at, index: true
end
end
end
+12
ファイルの表示
@@ -0,0 +1,12 @@
class CreateTheatreComments < ActiveRecord::Migration[8.0]
def change
create_table :theatre_comments, primary_key: [:theatre_id, :no] do |t|
t.references :theatre, null: false, foreign_key: { to_table: :theatres }
t.integer :no, null: false
t.references :user, foreign_key: { to_table: :users }
t.text :content, null: false
t.timestamps
t.datetime :discarded_at, index: true
end
end
end
+12
ファイルの表示
@@ -0,0 +1,12 @@
class CreateTheatreWatchingUsers < ActiveRecord::Migration[8.0]
def change
create_table :theatre_watching_users, primary_key: [:theatre_id, :user_id] do |t|
t.references :theatre, null: false, foreign_key: { to_table: :theatres }
t.references :user, null: false, foreign_key: { to_table: :users }, index: true
t.datetime :expires_at, null: false, index: true
t.timestamps
t.index [:theatre_id, :expires_at]
end
end
end
生成ファイル
+166 -22
ファイルの表示
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
ActiveRecord::Schema[8.0].define(version: 2026_03_17_015000) do
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -39,11 +39,21 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
end
create_table "deerjikists", primary_key: ["platform", "code"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "platform", limit: 16, null: false
t.string "code", null: false
t.bigint "tag_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
end
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.binary "ip_adress", limit: 16, null: false
t.binary "ip_address", limit: 16, null: false
t.boolean "banned", default: false, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["ip_address"], name: "index_ip_addresses_on_ip_address", unique: true
end
create_table "nico_tag_relations", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -55,11 +65,11 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.index ["tag_id"], name: "index_nico_tag_relations_on_tag_id"
end
create_table "post_similarities", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
create_table "post_similarities", primary_key: ["post_id", "target_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "post_id", null: false
t.bigint "target_post_id", null: false
t.float "cos", null: false
t.index ["post_id"], name: "index_post_similarities_on_post_id"
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos", order: { cos: :desc }
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
end
@@ -70,16 +80,23 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.bigint "deleted_user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.virtual "is_active", type: :boolean, as: "(`discarded_at` is null)", stored: true
t.virtual "active_unique_key", type: :string, as: "(case when (`discarded_at` is null) then concat(`post_id`,_utf8mb4':',`tag_id`) else NULL end)", stored: true
t.index ["active_unique_key"], name: "idx_post_tags_active_unique", unique: true
t.index ["created_user_id"], name: "index_post_tags_on_created_user_id"
t.index ["deleted_user_id"], name: "index_post_tags_on_deleted_user_id"
t.index ["discarded_at"], name: "index_post_tags_on_discarded_at"
t.index ["post_id", "discarded_at"], name: "index_post_tags_on_post_id_and_discarded_at"
t.index ["post_id"], name: "index_post_tags_on_post_id"
t.index ["tag_id", "discarded_at"], name: "index_post_tags_on_tag_id_and_discarded_at"
t.index ["tag_id"], name: "index_post_tags_on_tag_id"
end
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "title", null: false
t.string "url", limit: 2000, null: false
t.string "thumbnail_base", limit: 2000, null: false
t.string "title"
t.string "url", limit: 768, null: false
t.string "thumbnail_base", limit: 2000
t.bigint "parent_id"
t.bigint "uploaded_user_id"
t.datetime "created_at", null: false
@@ -88,6 +105,7 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.datetime "updated_at", null: false
t.index ["parent_id"], name: "index_posts_on_parent_id"
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
t.index ["url"], name: "index_posts_on_url", unique: true
end
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -99,46 +117,117 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.index ["user_id"], name: "index_settings_on_user_id"
end
create_table "tag_aliases", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
create_table "tag_implications", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "tag_id", null: false
t.string "name", null: false
t.bigint "parent_tag_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["tag_id"], name: "index_tag_aliases_on_tag_id"
t.index ["parent_tag_id"], name: "index_tag_implications_on_parent_tag_id"
t.index ["tag_id", "parent_tag_id"], name: "index_tag_implications_on_tag_id_and_parent_tag_id", unique: true
t.index ["tag_id"], name: "index_tag_implications_on_tag_id"
end
create_table "tag_similarities", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
create_table "tag_name_sanitisation_rules", primary_key: "priority", id: :integer, charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "source_pattern", null: false
t.string "replacement", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["discarded_at"], name: "index_tag_name_sanitisation_rules_on_discarded_at"
t.index ["source_pattern"], name: "index_tag_name_sanitisation_rules_on_source_pattern", unique: true
end
create_table "tag_names", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false
t.bigint "canonical_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["canonical_id"], name: "index_tag_names_on_canonical_id"
t.index ["discarded_at"], name: "index_tag_names_on_discarded_at"
t.index ["name"], name: "index_tag_names_on_name", unique: true
end
create_table "tag_similarities", primary_key: ["tag_id", "target_tag_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "tag_id", null: false
t.bigint "target_tag_id", null: false
t.float "cos", null: false
t.index ["tag_id"], name: "index_tag_similarities_on_tag_id"
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos", order: { cos: :desc }
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
end
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false
t.bigint "tag_name_id", null: false
t.string "category", default: "general", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "post_count", default: 0, null: false
t.datetime "discarded_at"
t.index ["discarded_at"], name: "index_tags_on_discarded_at"
t.index ["tag_name_id"], name: "index_tags_on_tag_name_id", unique: true
end
create_table "user_ips", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
create_table "theatre_comments", primary_key: ["theatre_id", "no"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "theatre_id", null: false
t.integer "no", null: false
t.bigint "user_id"
t.text "content", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["discarded_at"], name: "index_theatre_comments_on_discarded_at"
t.index ["theatre_id"], name: "index_theatre_comments_on_theatre_id"
t.index ["user_id"], name: "index_theatre_comments_on_user_id"
end
create_table "theatre_watching_users", primary_key: ["theatre_id", "user_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "theatre_id", null: false
t.bigint "user_id", null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["expires_at"], name: "index_theatre_watching_users_on_expires_at"
t.index ["theatre_id", "expires_at"], name: "index_theatre_watching_users_on_theatre_id_and_expires_at"
t.index ["theatre_id"], name: "index_theatre_watching_users_on_theatre_id"
t.index ["user_id"], name: "index_theatre_watching_users_on_user_id"
end
create_table "theatres", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name"
t.datetime "opens_at", null: false
t.datetime "closes_at"
t.integer "kind", null: false
t.bigint "current_post_id"
t.datetime "current_post_started_at"
t.integer "next_comment_no", default: 1, null: false
t.bigint "host_user_id"
t.bigint "created_by_user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["closes_at"], name: "index_theatres_on_closes_at"
t.index ["created_by_user_id"], name: "index_theatres_on_created_by_user_id"
t.index ["current_post_id"], name: "index_theatres_on_current_post_id"
t.index ["discarded_at"], name: "index_theatres_on_discarded_at"
t.index ["host_user_id"], name: "index_theatres_on_host_user_id"
t.index ["kind"], name: "index_theatres_on_kind"
t.index ["opens_at"], name: "index_theatres_on_opens_at"
end
create_table "user_ips", primary_key: ["user_id", "ip_address_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "ip_address_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["ip_address_id"], name: "index_user_ips_on_ip_address_id"
t.index ["user_id"], name: "index_user_ips_on_user_id"
end
create_table "user_post_views", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
create_table "user_post_views", primary_key: ["user_id", "post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "post_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_user_post_views_on_post_id"
t.index ["user_id"], name: "index_user_post_views_on_user_id"
end
create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -150,18 +239,57 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
t.datetime "updated_at", null: false
end
create_table "wiki_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "sha256", limit: 64, null: false
t.text "body", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["sha256"], name: "index_wiki_lines_on_sha256", unique: true
end
create_table "wiki_pages", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "title", null: false
t.bigint "tag_id"
t.bigint "tag_name_id", null: false
t.bigint "created_user_id", null: false
t.bigint "updated_user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.index ["created_user_id"], name: "index_wiki_pages_on_created_user_id"
t.index ["tag_id"], name: "index_wiki_pages_on_tag_id"
t.index ["discarded_at"], name: "index_wiki_pages_on_discarded_at"
t.index ["tag_name_id"], name: "index_wiki_pages_on_tag_name_id", unique: true
t.index ["updated_user_id"], name: "index_wiki_pages_on_updated_user_id"
end
create_table "wiki_revision_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "wiki_revision_id", null: false
t.integer "position", null: false
t.bigint "wiki_line_id", null: false
t.index ["wiki_line_id"], name: "index_wiki_revision_lines_on_wiki_line_id"
t.index ["wiki_revision_id", "position"], name: "index_wiki_revision_lines_on_wiki_revision_id_and_position", unique: true
t.index ["wiki_revision_id", "wiki_line_id"], name: "index_wiki_revision_lines_on_wiki_revision_id_and_wiki_line_id"
t.index ["wiki_revision_id"], name: "index_wiki_revision_lines_on_wiki_revision_id"
end
create_table "wiki_revisions", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "wiki_page_id", null: false
t.bigint "base_revision_id"
t.bigint "created_user_id", null: false
t.integer "kind", default: 0, null: false
t.bigint "redirect_page_id"
t.string "message"
t.integer "lines_count", default: 0, null: false
t.string "tree_sha256", limit: 64
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["base_revision_id"], name: "index_wiki_revisions_on_base_revision_id"
t.index ["created_user_id"], name: "index_wiki_revisions_on_created_user_id"
t.index ["kind"], name: "index_wiki_revisions_on_kind"
t.index ["redirect_page_id"], name: "index_wiki_revisions_on_redirect_page_id"
t.index ["tree_sha256"], name: "index_wiki_revisions_on_tree_sha256"
t.index ["wiki_page_id", "id"], name: "index_wiki_revisions_on_wiki_page_id_and_id"
t.index ["wiki_page_id"], name: "index_wiki_revisions_on_wiki_page_id"
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
add_foreign_key "nico_tag_relations", "tags"
@@ -175,14 +303,30 @@ ActiveRecord::Schema[8.0].define(version: 2025_09_09_075500) do
add_foreign_key "posts", "posts", column: "parent_id"
add_foreign_key "posts", "users", column: "uploaded_user_id"
add_foreign_key "settings", "users"
add_foreign_key "tag_aliases", "tags"
add_foreign_key "tag_implications", "tags"
add_foreign_key "tag_implications", "tags", column: "parent_tag_id"
add_foreign_key "tag_names", "tag_names", column: "canonical_id"
add_foreign_key "tag_similarities", "tags"
add_foreign_key "tag_similarities", "tags", column: "target_tag_id"
add_foreign_key "tags", "tag_names"
add_foreign_key "theatre_comments", "theatres"
add_foreign_key "theatre_comments", "users"
add_foreign_key "theatre_watching_users", "theatres"
add_foreign_key "theatre_watching_users", "users"
add_foreign_key "theatres", "posts", column: "current_post_id"
add_foreign_key "theatres", "users", column: "created_by_user_id"
add_foreign_key "theatres", "users", column: "host_user_id"
add_foreign_key "user_ips", "ip_addresses"
add_foreign_key "user_ips", "users"
add_foreign_key "user_post_views", "posts"
add_foreign_key "user_post_views", "users"
add_foreign_key "wiki_pages", "tags"
add_foreign_key "wiki_pages", "tag_names"
add_foreign_key "wiki_pages", "users", column: "created_user_id"
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
add_foreign_key "wiki_revision_lines", "wiki_lines"
add_foreign_key "wiki_revision_lines", "wiki_revisions"
add_foreign_key "wiki_revisions", "users", column: "created_user_id"
add_foreign_key "wiki_revisions", "wiki_pages"
add_foreign_key "wiki_revisions", "wiki_pages", column: "redirect_page_id"
add_foreign_key "wiki_revisions", "wiki_revisions", column: "base_revision_id"
end
+1 -23
ファイルの表示
@@ -1,28 +1,6 @@
namespace :post_similarity do
desc '関聯投稿テーブル作成'
task calc: :environment do
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
cos = -> a, b do
na = norm.(a)
nb = norm.(b)
if na.zero? || nb.zero?
0.0
else
dot.(a, b) / na / nb
end
end
posts = Post.includes(:tags).to_a
posts.each_with_index do |post, i|
existence_of_tags = post.tags.index_with(1)
((i + 1)...posts.size).each do |j|
target_post = posts[j]
existence_of_target_tags = target_post.tags.index_with(1)
PostSimilarity.find_or_initialize_by(post:, target_post:).tap { |ps|
ps.cos = cos.(existence_of_tags, existence_of_target_tags)
}.save!
end
end
Similarity::Calc.call(Post, :tags)
end
end
+6
ファイルの表示
@@ -0,0 +1,6 @@
namespace :tag_similarity do
desc '関聯タグ・テーブル作成'
task calc: :environment do
Similarity::Calc.call(Tag, :posts)
end
end
-12
ファイルの表示
@@ -1,12 +0,0 @@
namespace :nico do
desc 'ニコタグ連携'
task link: :environment do
Post.find_each do |post|
tags = post.tags.where(category: 'nico')
tags.each do |tag|
post.tags.concat(tag.linked_tags) if tag.linked_tags.present?
end
post.tags = post.tags.to_a.uniq
end
end
end
+74
ファイルの表示
@@ -0,0 +1,74 @@
namespace :wiki do
desc 'Wiki 移行'
task migrate: :environment do
require 'digest'
require 'gollum-lib'
wiki = Gollum::Wiki.new(Rails.root.join('wiki').to_s)
WikiPage.where.missing(:wiki_revisions).find_each do |wiki_page|
page = wiki.page("#{ wiki_page.id }.md")
next unless page
versions = page.versions
next if versions.blank?
base_revision_id = nil
versions.reverse_each do |version|
pg = wiki.page("#{ wiki_page.id }.md", version.id)
raw = pg&.raw_data
next unless raw
lines = raw.force_encoding('UTF-8').split("\n")
line_shas = lines.map { |l| Digest::SHA256.hexdigest(l) }
tree_sha = Digest::SHA256.hexdigest(line_shas.join(','))
at = version.authored_date
line_id_by_sha = WikiLine.where(sha256: line_shas).pluck(:sha256, :id).to_h
missing_rows = []
line_shas.each_with_index do |sha, i|
next if line_id_by_sha.key?(sha)
missing_rows << { sha256: sha,
body: lines[i],
created_at: at,
updated_at: at }
end
if missing_rows.any?
WikiLine.upsert_all(missing_rows)
line_id_by_sha = WikiLine.where(sha256: line_shas).pluck(:sha256, :id).to_h
end
line_ids = line_shas.map { |sha| line_id_by_sha.fetch(sha) }
rev = nil
ActiveRecord::Base.transaction do
wiki_page.lock!
rev = WikiRevision.create!(
wiki_page:,
base_revision_id:,
created_user_id: (Integer(version.author.name) rescue 2),
kind: :content,
redirect_page_id: nil,
message: nil,
lines_count: lines.length,
tree_sha256: tree_sha,
created_at: at,
updated_at: at)
rows = line_ids.each_with_index.map do |line_id, pos|
{ wiki_revision_id: rev.id,
wiki_line_id: line_id,
position: pos }
end
WikiRevisionLine.insert_all!(rows)
end
base_revision_id = rev.id
end
end
end
end
+115 -31
ファイルの表示
@@ -1,16 +1,39 @@
namespace :nico do
desc 'ニコニコ DB 同期'
task sync: :environment do
require 'open3'
require 'open-uri'
require 'json'
require 'nokogiri'
require 'open-uri'
require 'open3'
require 'set'
require 'time'
fetch_thumbnail = -> url {
fetch_thumbnail = -> url do
html = URI.open(url, read_timeout: 60, 'User-Agent' => 'Mozilla/5.0').read
doc = Nokogiri::HTML(html)
doc.at('meta[name="thumbnail"]')&.[]('content').presence
}
end
def sync_post_tags! post, desired_tag_ids, current_tag_ids: nil
current_tag_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
desired_tag_ids = desired_tag_ids.compact.to_set
to_add = desired_tag_ids - current_tag_ids
to_remove = current_tag_ids - desired_tag_ids
Tag.where(id: to_add.to_a).find_each do |tag|
begin
PostTag.create!(post:, tag:)
rescue ActiveRecord::RecordNotUnique
;
end
end
PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
pt.discard_by!(nil)
end
end
mysql_user = ENV['MYSQL_USER']
mysql_pass = ENV['MYSQL_PASS']
@@ -19,43 +42,104 @@ namespace :nico do
{ 'MYSQL_USER' => mysql_user, 'MYSQL_PASS' => mysql_pass },
'python3', "#{ nizika_nico_path }/get_videos.py")
if status.success?
data = JSON.parse(stdout)
data.each do |datum|
post = Post.where('url LIKE ?', '%nicovideo.jp%').find { |post|
post.url =~ %r{#{ Regexp.escape(datum['code']) }(?!\d)}
}
unless post
title = datum['title']
url = "https://www.nicovideo.jp/watch/#{ datum['code'] }"
thumbnail_base = fetch_thumbnail.(url) || '' rescue ''
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil)
unless status.success?
warn stderr
abort
end
data = JSON.parse(stdout)
data.each do |datum|
code = datum['code']
post =
Post
.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
.first
title = datum['title']
original_created_at = datum['uploaded_at'] &&
Time.strptime(datum['uploaded_at'], '%Y-%m-%d %H:%M:%S')
original_created_from = original_created_at&.change(sec: 0)
original_created_before = original_created_from&.+(1.minute)
if post
attrs = { title:, original_created_from:, original_created_before: }
unless post.thumbnail.attached?
thumbnail_base = fetch_thumbnail.(post.url) rescue nil
if thumbnail_base.present?
post.thumbnail.attach(
io: URI.open(thumbnail_base),
filename: File.basename(URI.parse(thumbnail_base).path),
content_type: 'image/jpeg')
attrs[:thumbnail_base] = thumbnail_base
end
post.save!
post.resized_thumbnail!
end
current_tags = post.tags.where(category: 'nico').pluck(:name).sort
new_tags = datum['tags'].map { |tag| "nico:#{ tag }" }.sort
if current_tags != new_tags
post.tags.destroy(post.tags.where(name: current_tags))
tags_to_add = []
new_tags.each do |name|
tag = Tag.find_or_initialize_by(name:) do |t|
t.category = 'nico'
end
tags_to_add.concat([tag] + tag.linked_tags)
end
tags_to_add << Tag.tagme if post.tags.size < 20
tags_to_add << Tag.bot
post.tags = (post.tags + tags_to_add).uniq
post.assign_attributes(attrs)
if post.changed?
post.save!
post.resized_thumbnail! if post.thumbnail.attached?
end
else
url = "https://www.nicovideo.jp/watch/#{ code }"
thumbnail_base = fetch_thumbnail.(url) rescue nil
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil,
original_created_from:, original_created_before:)
if thumbnail_base.present?
post.thumbnail.attach(
io: URI.open(thumbnail_base),
filename: File.basename(URI.parse(thumbnail_base).path),
content_type: 'image/jpeg')
end
post.save!
post.resized_thumbnail!
sync_post_tags!(post, [Tag.tagme.id, Tag.bot.id, Tag.niconico.id, Tag.video.id])
end
tags = post.tags
# 既存のタグ Id. 集合
kept_tag_ids = tags.pluck(:id).to_set
# うち内部タグ Id. 集合
kept_non_nico_tag_ids = tags.not_nico.pluck(:id).to_set
# 記載すべき外部タグ Id. および連携される内部タグ Id. のリスト
desired_nico_tag_based_ids = []
# 記載すべき内部タグ Id. のリスト
desired_non_nico_tag_ids = []
datum['tags'].each do |raw|
name = TagNameSanitisationRule.sanitise("nico:#{ raw }")
tag = Tag.find_or_create_by_tag_name!(name, category: :nico)
desired_nico_tag_based_ids << tag.id
# 新たに記載される外部タグと連携される内部タグを記載
unless tag.id.in?(kept_tag_ids)
linked_ids = tag.linked_tags.pluck(:id)
desired_non_nico_tag_ids.concat(linked_ids)
desired_nico_tag_based_ids.concat(linked_ids)
end
end
deerjikist = Deerjikist.find_by(platform: :nico, code: datum['user'])
if deerjikist
desired_non_nico_tag_ids << deerjikist.tag_id
desired_nico_tag_based_ids << deerjikist.tag_id
elsif !(Tag.where(id: kept_non_nico_tag_ids).where(category: :deerjikist).exists?)
desired_non_nico_tag_ids << Tag.no_deerjikist.id
desired_nico_tag_based_ids << Tag.no_deerjikist.id
end
desired_nico_tag_based_ids.uniq!
desired_all_tag_ids = kept_non_nico_tag_ids.to_a + desired_nico_tag_based_ids
desired_non_nico_tag_ids.concat(kept_non_nico_tag_ids.to_a)
desired_non_nico_tag_ids.uniq!
if kept_non_nico_tag_ids != desired_non_nico_tag_ids.to_set
desired_all_tag_ids << Tag.bot.id
end
desired_all_tag_ids.uniq!
sync_post_tags!(post, desired_all_tag_ids, current_tag_ids: kept_tag_ids)
end
end
end
+5
ファイルの表示
@@ -0,0 +1,5 @@
FactoryBot.define do
factory :tag_name do
name { "tag-#{SecureRandom.hex(4)}" }
end
end
+22
ファイルの表示
@@ -0,0 +1,22 @@
FactoryBot.define do
factory :tag do
transient do
name { nil }
end
category { :general }
post_count { 0 }
association :tag_name
after(:build) do |tag, evaluator|
tag.name = evaluator.name if evaluator.name.present?
end
trait :nico do
category { :nico }
transient do
name { "nico:#{ SecureRandom.hex(4) }" }
end
end
end
end
+8
ファイルの表示
@@ -0,0 +1,8 @@
FactoryBot.define do
factory :theatre_comment do
association :theatre
association :user
sequence (:no) { |n| n }
content { 'test comment' }
end
end
+11
ファイルの表示
@@ -0,0 +1,11 @@
FactoryBot.define do
factory :theatre do
name { 'Test Theatre' }
kind { 1 }
opens_at { Time.current }
closes_at { 1.day.from_now }
next_comment_no { 1 }
association :created_by_user, factory: :user
end
end
+15
ファイルの表示
@@ -0,0 +1,15 @@
FactoryBot.define do
factory :user do
name { "test-user" }
inheritance_code { SecureRandom.uuid }
role { "guest" }
trait :member do
role { "member" }
end
trait :admin do
role { 'admin' }
end
end
end
+7
ファイルの表示
@@ -0,0 +1,7 @@
FactoryBot.define do
factory :wiki_page do
title { "TestPage" }
association :created_user, factory: :user
association :updated_user, factory: :user
end
end
+101
ファイルの表示
@@ -0,0 +1,101 @@
require 'rails_helper'
RSpec.describe TagNameSanitisationRule, type: :model do
describe '.sanitise' do
before do
described_class.create!(priority: 10, source_pattern: '_', replacement: '')
described_class.create!(priority: 20, source_pattern: 'ABC', replacement: 'abc')
end
it 'applies sanitisation rules sequentially in priority order' do
expect(described_class.sanitise('A_B_C')).to eq('abc')
end
it 'does not fail when a rule does not match' do
expect { described_class.sanitise('xyz') }.not_to raise_error
expect(described_class.sanitise('xyz')).to eq('xyz')
end
end
describe 'validations' do
it 'is invalid when source_pattern is not a valid regexp' do
rule = described_class.new(priority: 10, source_pattern: '[', replacement: '')
expect(rule).to be_invalid
expect(rule.errors[:source_pattern]).to be_present
end
end
describe '.apply!' do
before do
described_class.create!(priority: 10, source_pattern: '_', replacement: '')
end
context 'when no conflicting tag_name exists' do
let!(:tag_name) do
TagName.create!(name: 'tmp').tap do |tn|
tn.update_columns(name: 'foo_bar', updated_at: Time.current)
end
end
it 'renames the tag_name' do
described_class.apply!
expect(tag_name.reload.name).to eq('foobar')
end
end
context 'when a conflicting canonical tag_name exists' do
let!(:existing) { TagName.create!(name: 'foobar') }
let!(:source) do
TagName.create!(name: 'tmp').tap do |tn|
tn.update_columns(name: 'foo_bar', updated_at: Time.current)
end
end
it 'deletes the source tag_name' do
described_class.apply!
expect(TagName.exists?(source.id)).to be(false)
expect(existing.reload.name).to eq('foobar')
end
end
context 'when the source tag_name has a tag and the existing one has no tag' do
let!(:existing) { TagName.create!(name: 'foobar') }
let!(:source_tag) { create(:tag, name: 'tmp', category: :general) }
let!(:source_tag_name_id) { source_tag.tag_name_id }
before do
source_tag.tag_name.update_columns(name: 'foo_bar', updated_at: Time.current)
end
it 'moves the tag to the existing tag_name' do
described_class.apply!
expected_tag_name_id = existing.canonical_id || existing.id
expect(source_tag.reload.tag_name_id).to eq(expected_tag_name_id)
expect(TagName.exists?(source_tag_name_id)).to be(false)
end
end
context 'when both source and existing tag_names have tags' do
let!(:existing_tn) { TagName.create!(name: 'foobar') }
let!(:existing_tag) { Tag.create!(tag_name: existing_tn, category: :general) }
let!(:source_tn) { TagName.create!(name: 'tmp') }
let!(:source_tag) { Tag.create!(tag_name: source_tn, category: :general) }
let!(:source_tag_name_id) { source_tn.id }
before do
source_tn.update_columns(name: 'foo_bar', updated_at: Time.current)
end
it 'merges the source tag into the existing tag and deletes the source tag_name' do
expect(TagName.find_by(name: 'foobar')&.tag&.id).to eq(existing_tag.id)
expect(TagName.find_by(name: 'foo_bar')&.tag&.id).to eq(source_tag.id)
described_class.apply!
expect(Tag.exists?(source_tag.id)).to be(false)
expect(TagName.exists?(source_tag.tag_name_id)).to be(false)
end
end
end
end
+149
ファイルの表示
@@ -0,0 +1,149 @@
require 'rails_helper'
RSpec.describe Tag, type: :model do
describe '.merge_tags!' do
let!(:target_tag) { create(:tag, category: :general) }
let!(:source_tag) { create(:tag, category: :general) }
let!(:source_tag_name) { source_tag.tag_name }
let!(:post_record) do
Post.create!(url: 'https://example.com/posts/1', title: 'test post')
end
context 'when merging a simple source tag' do
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
it 'discards the source post_tag, creates an active target post_tag, discards the source tag, and aliases the source tag_name' do
described_class.merge_tags!(target_tag, [source_tag])
source_pt = PostTag.with_discarded.find(source_post_tag.id)
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
expect(source_pt.discarded_at).to be_present
expect(source_pt.tag_id).to eq(source_tag.id)
expect(active_target).to be_present
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
expect(target_tag.reload.post_count).to eq(1)
end
end
context 'when the target already has the same post_tag' do
let!(:target_post_tag) { PostTag.create!(post: post_record, tag: target_tag) }
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
it 'discards the source post_tag, keeps one active target post_tag, discards the source tag, and aliases the source tag_name' do
described_class.merge_tags!(target_tag, [source_tag])
source_pt = PostTag.with_discarded.find(source_post_tag.id)
active = PostTag.kept.where(post_id: post_record.id, tag_id: target_tag.id)
expect(source_pt.discarded_at).to be_present
expect(source_pt.tag_id).to eq(source_tag.id)
expect(active.count).to eq(1)
expect(active.first.id).to eq(target_post_tag.id)
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
expect(target_tag.reload.post_count).to eq(1)
end
end
context 'when source_tags includes the target itself' do
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
it 'ignores the target in source_tags while still merging the source tag' do
described_class.merge_tags!(target_tag, [source_tag, target_tag])
source_pt = PostTag.with_discarded.find(source_post_tag.id)
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
expect(Tag.find(target_tag.id)).to be_present
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
expect(source_pt.discarded_at).to be_present
expect(source_pt.tag_id).to eq(source_tag.id)
expect(active_target).to be_present
expect(source_tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
expect(target_tag.reload.post_count).to eq(1)
end
end
context 'when the source tag_name is invalid under sanitisation rules' do
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
let!(:sanitisation_rule) do
TagNameSanitisationRule.create!(
priority: 99_999,
source_pattern: 'INVALIDTOKEN',
replacement: ''
)
end
before do
source_tag_name.update_columns(
name: "#{ source_tag_name.name }INVALIDTOKEN",
updated_at: Time.current
)
end
it 'still merges, but discards the source tag_name instead of aliasing it' do
described_class.merge_tags!(target_tag, [source_tag])
source_pt = PostTag.with_discarded.find(source_post_tag.id)
active_target = PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)
discarded_source_tag_name = TagName.with_discarded.find(source_tag_name.id)
expect(source_pt.discarded_at).to be_present
expect(source_pt.tag_id).to eq(source_tag.id)
expect(active_target).to be_present
expect(Tag.with_discarded.find(source_tag.id)).to be_discarded
expect(target_tag.reload.post_count).to eq(1)
end
end
context 'when the source tag_name has a wiki_page' do
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
let!(:wiki_page) do
WikiPage.create!(
tag_name: source_tag_name,
created_user: create_admin_user!,
updated_user: create_admin_user!
)
end
it 'rolls back the transaction' do
expect {
described_class.merge_tags!(target_tag, [source_tag])
}.to raise_error(ActiveRecord::RecordInvalid)
expect(Tag.with_discarded.find(source_tag.id)).not_to be_discarded
expect(TagName.with_discarded.find(source_tag_name.id)).not_to be_discarded
expect(PostTag.kept.find(source_post_tag.id).tag_id).to eq(source_tag.id)
expect(PostTag.kept.find_by(post_id: post_record.id, tag_id: target_tag.id)).to be_nil
expect(source_tag_name.reload.canonical_id).to be_nil
expect(target_tag.reload.post_count).to eq(0)
end
end
context 'when merging a nico source tag' do
let!(:target_tag) { create(:tag, category: :nico, name: 'nico:foo') }
let!(:source_tag) { create(:tag, category: :nico, name: 'nico:bar') }
let!(:source_tag_name_id) { source_tag.tag_name_id }
it 'discards the source tag_name instead of aliasing it' do
described_class.merge_tags!(target_tag, [source_tag])
discarded_source_tag = Tag.with_discarded.find(source_tag.id)
discarded_source_tag_name = TagName.with_discarded.find(source_tag_name_id)
expect(discarded_source_tag).to be_discarded
expect(discarded_source_tag_name).to be_discarded
expect(discarded_source_tag_name.canonical_id).to be_nil
expect(target_tag.reload.post_count).to eq(0)
end
end
end
end
+90
ファイルの表示
@@ -0,0 +1,90 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file
# that will avoid rails generators crashing because migrations haven't been run yet
# return unless Rails.env.test?
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each do |f|
require f
end
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }
# Ensures that the test database schema matches the current schema file.
# If there are pending migrations it will invoke `db:test:prepare` to
# recreate the test database by loading the schema.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
abort e.to_s.strip
end
RSpec.configure do |config|
config.before do
I18n.locale = :en
end
config.include TestRecords
config.include RakeTaskHelper
# FactoryBot の create / create_list を使へるやぅにする
config.include FactoryBot::Syntax::Methods
# request spec で helper 使へるやぅにする
config.include AuthHelper, type: :request
config.include JsonHelper, type: :request
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_paths = [
Rails.root.join('spec/fixtures')
]
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails uses metadata to mix in different behaviours to your tests,
# for example enabling you to call `get` and `post` in request specs. e.g.:
#
# RSpec.describe UsersController, type: :request do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://rspec.info/features/8-0/rspec-rails
#
# You can also this infer these behaviours automatically by location, e.g.
# /spec/models would pull in the same behaviour as `type: :model` but this
# behaviour is considered legacy and will be removed in a future version.
#
# To enable this behaviour uncomment the line below.
# config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
+181
ファイルの表示
@@ -0,0 +1,181 @@
require 'rails_helper'
RSpec.describe 'Deerjikists API', type: :request do
let(:platform) { 'nico' }
let(:code) { 'deerjika-bot' }
let!(:tag1) { create(:tag, category: :deerjikist) }
let!(:tag2) { create(:tag, category: :deerjikist) }
let(:member) { create(:user, :member) }
let(:guest) { create(:user, role: :guest) }
describe 'GET /deerjikists/:platform/:code' do
subject(:do_request) do
get "/deerjikists/#{ platform }/#{ code }"
end
context 'when deerjikist exists' do
before do
Deerjikist.create!(platform:, code:, tag: tag1)
end
it 'returns 200 and deerjikist json' do
do_request
expect(response).to have_http_status(:ok)
expect(json).to be_a(Hash)
expect(json['platform']).to eq(platform)
expect(json['code']).to eq(code)
expect(json['tag']).to be_a(Hash)
expect(json['tag']['id']).to eq(tag1.id)
expect(json['tag']['name']).to eq(tag1.name)
end
end
context 'when deerjikist does not exist' do
it 'returns 404' do
do_request
expect(response).to have_http_status(:not_found)
end
end
context 'when platform or code become blank after strip' do
it 'returns 400' do
get '/deerjikists/%20/%20'
expect(response).to have_http_status(:bad_request)
end
end
end
describe 'PUT /deerjikists/:platform/:code' do
subject(:do_request) do
put "/deerjikists/#{ platform }/#{ code }", params: payload
end
let(:payload) { { tag_id: tag1.id } }
context 'when not legged in' do
it 'returns 401' do
sign_out
do_request
expect(response).to have_http_status(:unauthorized)
end
end
context 'when logged in but not member' do
it 'returns 403' do
sign_in_as guest
do_request
expect(response).to have_http_status(:forbidden)
end
end
context 'when member' do
before do
sign_in_as member
end
context 'when params invalid' do
it 'returns 400 when tag_id is missing or invalid' do
put "/deerjikists/#{ platform }/#{ code }", params: { tag_id: 0 }
expect(response).to have_http_status(:bad_request)
end
it 'returns 400 when platform or code blank after strip' do
put '/deerjikists/%20/%20', params: { tag_id: tag1.id }
expect(response).to have_http_status(:bad_request)
end
end
context 'when creating new deerjikist' do
it 'creates and returns 200 with json' do
expect { do_request }.to change { Deerjikist.count }.by(1)
expect(response).to have_http_status(:ok)
d = Deerjikist.find_by(platform:, code:)
expect(d).to be_present
expect(d.tag_id).to eq(tag1.id)
expect(json['platform']).to eq(platform)
expect(json['code']).to eq(code)
end
end
context 'when updating existing deerjikist' do
before do
Deerjikist.create!(platform:, code:, tag: tag1)
end
let(:payload) { { tag_id: tag2.id } }
it 'updates tag_id and returns 200' do
expect { do_request }.not_to change { Deerjikist.count }
expect(response).to have_http_status(:ok)
d = Deerjikist.find_by(platform:, code:)
expect(d.tag_id).to eq(tag2.id)
expect(json['platform']).to eq(platform)
expect(json['code']).to eq(code)
end
end
end
end
describe 'DELETE /deerjikists/:platform/:code' do
subject(:do_request) do
delete "/deerjikists/#{ platform }/#{ code }"
end
context 'when not logged in' do
it 'returns 401' do
sign_out
do_request
expect(response).to have_http_status(:unauthorized)
end
end
context 'when logged in but not member' do
it 'returns 403' do
sign_in_as guest
do_request
expect(response).to have_http_status(:forbidden)
end
end
context 'when member' do
before do
sign_in_as member
end
it 'returns 400 when platform/code blank after strip' do
delete '/deerjikists/%20/%20'
expect(response).to have_http_status(:bad_request)
end
context 'when deerjikist exists' do
before do
Deerjikist.create!(platform: platform, code: code, tag: tag1)
end
it 'destroys and returns 204' do
expect {
do_request
}.to change { Deerjikist.exists?(platform: platform, code: code) }
.from(true).to(false)
expect(response).to have_http_status(:no_content)
end
end
context 'when deerjikist does not exist' do
it 'returns 404' do
do_request
expect(response).to have_http_status(:not_found)
end
end
end
end
end

変更されたファイルが多すぎるため,一部のファイルは表示されません さらに表示