| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib\Fedi; |
| 39 | |
| 40 | /** |
| 41 | * タイムライン(data/ap/timeline.jsonl に1行1件の索引) |
| 42 | * |
| 43 | * 各行:t(時刻)、type(note/boost)、object(投稿のID)、actor(投稿者又はブーストした人)、 |
| 44 | * author(投稿者)、vis(公開範囲)、aud(to+cc)、local(ローカルの投稿か)、reply(返信先)、tags |
| 45 | */ |
| 46 | final class Timeline { |
| 47 | /** 1ページの件数 */ |
| 48 | public const PAGE = 20; |
| 49 | |
| 50 | private static function file(): string { |
| 51 | return Fedi::path('timeline.jsonl'); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * 全部の行(古い順) |
| 56 | */ |
| 57 | public static function entries(): array { |
| 58 | $file = self::file(); |
| 59 | if (!is_file($file)) return []; |
| 60 | $out = []; |
| 61 | foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) { |
| 62 | $e = json_decode($line, true); |
| 63 | if (is_array($e)) $out[] = $e; |
| 64 | } |
| 65 | return $out; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * 投稿・ブーストを追加する |
| 70 | * |
| 71 | * @param array $obj Note(ローカルならtoObject()の結果) |
| 72 | * @param string|null $booster ブーストした人(ブーストの場合) |
| 73 | * @param int|float|null $t 時刻 |
| 74 | */ |
| 75 | public static function add(array $obj, ?string $booster = null, int|float|null $t = null): void { |
| 76 | $id = Fedi::id($obj['id'] ?? null); |
| 77 | $author = Fedi::id($obj['attributedTo'] ?? null); |
| 78 | if ($id === null || $author === null) return; |
| 79 | $to = Fedi::ids($obj['to'] ?? []); |
| 80 | $cc = Fedi::ids($obj['cc'] ?? []); |
| 81 | $tags = []; |
| 82 | foreach ($obj['tag'] ?? [] as $tag) { |
| 83 | if (is_array($tag) && ($tag['type'] ?? '') === 'Hashtag') $tags[] = mb_strtolower(ltrim((string)($tag['name'] ?? ''), '#')); |
| 84 | } |
| 85 | $e = [ |
| 86 | 't' => $t ?? (strtotime((string)($obj['published'] ?? '')) ?: time()), |
| 87 | 'type' => $booster ? 'boost' : 'note', |
| 88 | 'object' => $id, |
| 89 | 'actor' => $booster ?? $author, |
| 90 | 'author' => $author, |
| 91 | 'vis' => Fedi::visibility($to, $cc, Fedi::id(self::followersOf($author))), |
| 92 | 'aud' => array_values(array_unique(array_merge($to, $cc))), |
| 93 | 'local' => Fedi::isLocal($id), |
| 94 | 'reply' => Fedi::id($obj['inReplyTo'] ?? null), |
| 95 | 'tags' => $tags, |
| 96 | ]; |
| 97 | if ($booster) $e['t'] = $t ?? time(); |
| 98 | |
| 99 | self::rewrite(function(array $list) use ($e): array { |
| 100 | // 同じ投稿(又は同じ人の同じブースト)は1回だけ |
| 101 | foreach ($list as $x) { |
| 102 | if ($x['type'] === $e['type'] && $x['object'] === $e['object'] && $x['actor'] === $e['actor']) return $list; |
| 103 | } |
| 104 | $list[] = $e; |
| 105 | return $list; |
| 106 | }); |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * 編集された投稿のタグと宛先を更新する |
| 111 | */ |
| 112 | public static function refresh(array $obj): void { |
| 113 | $id = Fedi::id($obj['id'] ?? null); |
| 114 | if ($id === null) return; |
| 115 | $tags = []; |
| 116 | foreach ($obj['tag'] ?? [] as $tag) { |
| 117 | if (is_array($tag) && ($tag['type'] ?? '') === 'Hashtag') $tags[] = mb_strtolower(ltrim((string)($tag['name'] ?? ''), '#')); |
| 118 | } |
| 119 | $aud = array_values(array_unique(array_merge(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? [])))); |
| 120 | self::rewrite(fn(array $list) => array_map(fn($x) => $x['object'] === $id ? ['tags' => $tags, 'aud' => $aud] + $x : $x, $list)); |
| 121 | } |
| 122 | |
| 123 | /** |
| 124 | * 投稿(とそのブースト)を消す |
| 125 | */ |
| 126 | public static function remove(string $objectId, ?string $booster = null): void { |
| 127 | self::rewrite(fn(array $list) => array_values(array_filter($list, function($x) use ($objectId, $booster) { |
| 128 | if ($x['object'] !== $objectId) return true; |
| 129 | return $booster !== null && !($x['type'] === 'boost' && $x['actor'] === $booster); |
| 130 | }))); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * アクターの投稿を全部消す(アカウントの削除・ブロック) |
| 135 | */ |
| 136 | public static function removeActor(string $actor): void { |
| 137 | self::rewrite(fn(array $list) => array_values(array_filter($list, fn($x) => $x['actor'] !== $actor && $x['author'] !== $actor))); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * 古い行を消す(cronのapcleanup)。ローカルの投稿は消さない |
| 142 | * |
| 143 | * @param int $days この日数より古いリモートの行を消す |
| 144 | * @return array 消したリモートのオブジェクトのID |
| 145 | */ |
| 146 | public static function prune(int $days): array { |
| 147 | $limit = time() - $days * 86400; |
| 148 | $removed = []; |
| 149 | self::rewrite(function(array $list) use ($limit, &$removed): array { |
| 150 | $keep = []; |
| 151 | foreach ($list as $x) { |
| 152 | if (!$x['local'] && $x['t'] < $limit) $removed[] = $x['object']; |
| 153 | else $keep[] = $x; |
| 154 | } |
| 155 | return $keep; |
| 156 | }); |
| 157 | return array_values(array_unique($removed)); |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * 古いリモートのデータを消す(cronのapcleanup) |
| 162 | * |
| 163 | * @param int $days この日数より古いリモートの投稿とキャッシュを消す |
| 164 | * @return \Result |
| 165 | */ |
| 166 | public static function cleanup(int $days = 90): \Result { |
| 167 | $removed = self::prune($days); |
| 168 | // 他の行(ブースト等)から使われていなければ、保存したオブジェクトも消す |
| 169 | $used = []; |
| 170 | foreach (self::entries() as $e) $used[$e['object']] = true; |
| 171 | $n = 0; |
| 172 | foreach ($removed as $id) { |
| 173 | if (!isset($used[$id])) { |
| 174 | Remote::forget($id); |
| 175 | $n++; |
| 176 | } |
| 177 | } |
| 178 | // タイムラインに無い古いオブジェクト(検索やプロフィールで取得した物) |
| 179 | $limit = time() - $days * 86400; |
| 180 | foreach (glob(Fedi::path('remote/objects/').'*.json') ?: [] as $f) { |
| 181 | if (filemtime($f) < $limit) { |
| 182 | $obj = Fedi::read($f, null); |
| 183 | if (!$obj || !isset($used[$obj['id'] ?? ''])) { |
| 184 | @unlink($f); |
| 185 | $n++; |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | // 古いキャッシュ |
| 190 | foreach (['remote/actors/', 'remote/webfinger/'] as $dir) { |
| 191 | foreach (glob(Fedi::path($dir).'*.json') ?: [] as $f) if (filemtime($f) < $limit) @unlink($f); |
| 192 | } |
| 193 | // 画像のキャッシュ(期限切れ) |
| 194 | $old = time() - Remote::IMAGE_TTL; |
| 195 | foreach (glob(Fedi::path('remote/media/').'*') ?: [] as $f) if (filemtime($f) < $old) @unlink($f); |
| 196 | return \Result::Success("古い投稿{$n}件を削除しました。", ['removed' => $n]); |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * タイムラインを読む |
| 201 | * |
| 202 | * @param string $scope home, local, federated, user, actor, tag |
| 203 | * @param string|null $viewer 見ているローカルのユーザー(未ログインならnull) |
| 204 | * @param array $opt user/actor/tag:対象、before:この時刻より前、limit |
| 205 | * @return array [項目の配列, 次のページのbefore(無ければnull)] |
| 206 | * 項目:['entry' => 行, 'object' => Note] |
| 207 | */ |
| 208 | public static function query(string $scope, ?string $viewer, array $opt = []): array { |
| 209 | $before = (int)($opt['before'] ?? PHP_INT_MAX); |
| 210 | $limit = (int)($opt['limit'] ?? self::PAGE); |
| 211 | $me = $viewer !== null ? Fedi::actorUrl($viewer) : null; |
| 212 | $target = $opt['user'] ?? $opt['actor'] ?? null; |
| 213 | if (isset($opt['user'])) $target = Fedi::actorUrl($opt['user']); |
| 214 | |
| 215 | $entries = self::entries(); |
| 216 | usort($entries, fn($a, $b) => $b['t'] <=> $a['t']); |
| 217 | |
| 218 | $out = []; |
| 219 | $next = null; |
| 220 | $seen = []; |
| 221 | foreach ($entries as $e) { |
| 222 | if ($e['t'] >= $before) continue; |
| 223 | $ok = match ($scope) { |
| 224 | 'home' => $me !== null && ($e['actor'] === $me || $e['author'] === $me || in_array($me, $e['aud'], true) |
| 225 | || Actor::isFollowing($viewer, $e['actor'])), |
| 226 | 'local' => $e['local'] && $e['type'] === 'note' && $e['vis'] === 'public', |
| 227 | 'federated' => $e['type'] === 'note' && $e['vis'] === 'public', |
| 228 | 'user', 'actor' => $e['actor'] === $target && in_array($e['vis'], ['public', 'unlisted', 'followers', 'direct'], true), |
| 229 | 'tag' => $e['type'] === 'note' && in_array(mb_strtolower((string)($opt['tag'] ?? '')), $e['tags'] ?? [], true) |
| 230 | && in_array($e['vis'], ['public', 'unlisted'], true), |
| 231 | default => false, |
| 232 | }; |
| 233 | if (!$ok || !self::canSee($viewer, $e)) continue; |
| 234 | if ($viewer !== null && (Actor::isBlocked($viewer, $e['actor']) || Actor::isBlocked($viewer, $e['author']))) continue; |
| 235 | if (Actor::isDomainBlocked($e['author'])) continue; |
| 236 | |
| 237 | // 同じ投稿は1回だけ(ブーストと元の投稿等) |
| 238 | if (isset($seen[$e['object']])) continue; |
| 239 | $obj = self::object($e['object']); |
| 240 | if ($obj === null) continue; |
| 241 | $seen[$e['object']] = true; |
| 242 | |
| 243 | if (count($out) >= $limit) { |
| 244 | $next = $out[count($out) - 1]['entry']['t']; |
| 245 | break; |
| 246 | } |
| 247 | $out[] = ['entry' => $e, 'object' => $obj]; |
| 248 | } |
| 249 | return [$out, $next]; |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * 見ているユーザーがこの投稿を見られるか |
| 254 | */ |
| 255 | public static function canSee(?string $viewer, array $e): bool { |
| 256 | if (in_array($e['vis'], ['public', 'unlisted'], true)) return true; |
| 257 | if ($viewer === null) return false; |
| 258 | $me = Fedi::actorUrl($viewer); |
| 259 | if ($e['author'] === $me || in_array($me, $e['aud'], true)) return true; |
| 260 | if ($e['vis'] !== 'followers') return false; |
| 261 | // フォロワー限定:作者をフォローしている事 |
| 262 | $author = $e['author']; |
| 263 | $local = Fedi::localUsername($author); |
| 264 | return $local !== null ? Actor::isFollowedBy($local, $me) : Actor::isFollowing($viewer, $author); |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * 投稿のオブジェクト(ローカル又は保存しているリモート) |
| 269 | */ |
| 270 | public static function object(string $id): ?array { |
| 271 | if (Fedi::isLocal($id)) { |
| 272 | $ids = Fedi::localNoteId($id); |
| 273 | $note = $ids ? Notes::get($ids[1]) : null; |
| 274 | return $note ? Notes::toObject($note) : null; |
| 275 | } |
| 276 | return Remote::stored($id); |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * ある投稿への返信(保存しているもの) |
| 281 | */ |
| 282 | public static function replies(string $id): array { |
| 283 | $out = []; |
| 284 | foreach (self::entries() as $e) { |
| 285 | if ($e['type'] === 'note' && $e['reply'] === $id) $out[] = $e; |
| 286 | } |
| 287 | usort($out, fn($a, $b) => $a['t'] <=> $b['t']); |
| 288 | return $out; |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * 文字で検索する(ローカルと保存しているリモートの、公開・未収載の投稿) |
| 293 | */ |
| 294 | public static function search(string $q, ?string $viewer, int $limit = 40): array { |
| 295 | $q = mb_strtolower(trim($q)); |
| 296 | if ($q === '') return []; |
| 297 | $entries = self::entries(); |
| 298 | usort($entries, fn($a, $b) => $b['t'] <=> $a['t']); |
| 299 | $out = []; |
| 300 | foreach ($entries as $e) { |
| 301 | if ($e['type'] !== 'note' || !self::canSee($viewer, $e)) continue; |
| 302 | if ($viewer !== null && Actor::isBlocked($viewer, $e['author'])) continue; |
| 303 | $obj = self::object($e['object']); |
| 304 | if (!$obj) continue; |
| 305 | $text = mb_strtolower(Html::text((string)($obj['content'] ?? '')).' '.($obj['summary'] ?? '')); |
| 306 | if (!str_contains($text, $q)) continue; |
| 307 | $out[] = ['entry' => $e, 'object' => $obj]; |
| 308 | if (count($out) >= $limit) break; |
| 309 | } |
| 310 | return $out; |
| 311 | } |
| 312 | |
| 313 | /////// |
| 314 | |
| 315 | private static function rewrite(callable $fn): void { |
| 316 | $file = self::file(); |
| 317 | $lock = fopen($file.'.lock', 'c'); |
| 318 | if ($lock) flock($lock, LOCK_EX); |
| 319 | try { |
| 320 | $list = $fn(self::entries()); |
| 321 | $tmp = $file.'.'.bin2hex(random_bytes(4)).'.tmp'; |
| 322 | $data = ''; |
| 323 | foreach ($list as $e) $data .= json_encode($e, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n"; |
| 324 | file_put_contents($tmp, $data); |
| 325 | rename($tmp, $file); |
| 326 | } finally { |
| 327 | if ($lock) { |
| 328 | flock($lock, LOCK_UN); |
| 329 | fclose($lock); |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | /** 投稿者のフォロワーのコレクション(分かれば) */ |
| 335 | private static function followersOf(string $author): ?string { |
| 336 | if (Fedi::isLocal($author)) return $author.'/followers'; |
| 337 | $file = Fedi::path('remote/actors/'.sha1($author).'.json'); |
| 338 | $cached = Fedi::read($file, null); |
| 339 | return $cached['doc']['followers'] ?? null; |
| 340 | } |
| 341 | } |