forked from OPSnet/Gazelle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Torrent.php
616 lines (568 loc) · 23.6 KB
/
Torrent.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<?php
namespace Gazelle;
class Torrent extends TorrentAbstract {
use Pg;
final const tableName = 'torrents';
final const CACHE_KEY = 't2_%d';
final const CACHE_FOLDERNAME = 'foldername_%s';
final const CACHE_KEY_PEERLIST_PAGE = 'peerlist_page_%d_%d';
final const USER_RECENT_UPLOAD = 'u_recent_up_%d';
protected array $tokenCache;
public function location(): string { return "torrents.php?id={$this->groupId()}&torrentid={$this->id}#torrent{$this->id}"; }
public function infoRow(): ?array {
return self::$db->rowAssoc("
SELECT t.GroupID,
t.UserID,
t.Media,
t.Format,
t.Encoding,
t.Remastered,
t.RemasterYear,
t.RemasterTitle,
t.RemasterCatalogueNumber,
t.RemasterRecordLabel,
t.Scene,
t.HasLog,
t.HasCue,
t.HasLogDB,
t.LogScore,
t.LogChecksum,
hex(t.info_hash) AS info_hash,
t.info_hash AS info_hash_raw,
t.FileCount,
t.FileList,
t.FilePath,
t.Size,
t.FreeTorrent,
t.FreeLeechType,
t.created,
t.Description,
t.LastReseedRequest,
tls.Seeders,
tls.Leechers,
tls.Snatched,
tls.last_action,
tbt.TorrentID AS BadTags,
tbf.TorrentID AS BadFolders,
tfi.TorrentID AS BadFiles,
mli.TorrentID AS MissingLineage,
cas.TorrentID AS CassetteApproved,
lma.TorrentID AS LossymasterApproved,
lwa.TorrentID AS LossywebApproved,
group_concat(tl.LogID) AS ripLogIds
FROM torrents t
INNER JOIN torrents_leech_stats tls ON (tls.TorrentID = t.ID)
LEFT JOIN torrents_bad_tags AS tbt ON (tbt.TorrentID = t.ID)
LEFT JOIN torrents_bad_folders AS tbf ON (tbf.TorrentID = t.ID)
LEFT JOIN torrents_bad_files AS tfi ON (tfi.TorrentID = t.ID)
LEFT JOIN torrents_missing_lineage AS mli ON (mli.TorrentID = t.ID)
LEFT JOIN torrents_cassette_approved AS cas ON (cas.TorrentID = t.ID)
LEFT JOIN torrents_lossymaster_approved AS lma ON (lma.TorrentID = t.ID)
LEFT JOIN torrents_lossyweb_approved AS lwa ON (lwa.TorrentID = t.ID)
LEFT JOIN torrents_logs AS tl ON (tl.TorrentID = t.ID)
WHERE t.ID = ?
GROUP BY t.ID
", $this->id
);
}
/**
* Check if the viewer has an active freeleech token on this torrent
*/
public function hasToken(int $userId): bool {
if (!isset($this->tokenCache)) {
$key = "users_tokens_" . $userId;
$tokenCache = self::$cache->get_value($key);
if ($tokenCache === false) {
$qid = self::$db->get_query_id();
self::$db->prepared_query("
SELECT TorrentID FROM users_freeleeches WHERE Expired = 0 AND UserID = ?
", $userId
);
$tokenCache = array_fill_keys(self::$db->collect(0, false), true);
self::$db->set_query_id($qid);
self::$cache->cache_value($key, $tokenCache, 3600);
}
$this->tokenCache = $tokenCache;
}
return isset($this->tokenCache[$this->id]);
}
/**
* Combine torrent media into a standardized file name
*/
public function torrentFilename(bool $asText, int $maxLength): string {
$tgroup = $this->group();
$filename = implode('.',
match ($tgroup->categoryName()) {
'Music' => [
$tgroup->artistRole()->text(), $tgroup->year(), $tgroup->name(),
'(' . implode('-', [$this->media(), $this->format(), $this->encoding()]) . ')'
],
'Audiobooks',
'Comedy' => [$tgroup->year(), $tgroup->name()],
default => [$tgroup->name()],
}
);
$maxLength -= strlen((string)$this->id) + 1 + ($asText ? 4 : 8);
$filename = safeFilename(shortenString($filename, $maxLength, true, false))
. "-" . $this->id;
return $asText ? "$filename.txt" : "$filename.torrent";
}
/**
* Convert a stored torrent into a binary file that can be loaded in a torrent client
*/
public function torrentBody(string $announceUrl): string {
$filer = new \Gazelle\File\Torrent;
$contents = $filer->get($this->id);
if ($contents == false) {
return '';
}
$tor = new \OrpheusNET\BencodeTorrent\BencodeTorrent;
try {
$tor->decodeString($contents);
} catch (\RuntimeException $e) {
return '';
}
$tor->cleanDataDictionary();
$tor->setValue([
'announce' => $announceUrl,
'comment' => SITE_URL . "/torrents.php?torrentid=" . $this->id,
]);
return $tor->getEncode();
}
public function addLogDb(Logfile $logfile, string $version): int {
self::$db->prepared_query('
INSERT INTO torrents_logs
(TorrentID, Score, `Checksum`, `FileName`, Ripper, RipperVersion, `Language`, ChecksumState, LogcheckerVersion, Details)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
', $this->id, $logfile->score(), $logfile->checksumStatus(), $logfile->filename(), $logfile->ripper(),
$logfile->ripperVersion(), $logfile->language(), $logfile->checksumState(),
\OrpheusNET\Logchecker\Logchecker::getLogcheckerVersion(), $logfile->detailsAsString()
);
return self::$db->inserted_id();
}
public function adjustLogscore(int $logId, bool $adjusted, int $adjScore, bool $adjChecksum, int $adjBy, $adjReason, array $adjDetails): int {
self::$db->prepared_query("
UPDATE torrents_logs SET
Adjusted = ?, AdjustedScore = ?, AdjustedChecksum = ?, AdjustedBy = ?, AdjustmentReason = ?, AdjustmentDetails = ?
WHERE TorrentID = ? AND LogID = ?
", $adjusted ? '1' : '0', $adjScore, $adjChecksum ? '1' : '0', $adjBy, $adjReason, serialize($adjDetails),
$this->id, $logId
);
if (self::$db->affected_rows() > 0) {
return $this->modifyLogscore();
}
return 0;
}
public function clearLog(int $logId): int {
self::$db->prepared_query("
DELETE FROM torrents_logs WHERE TorrentID = ? AND LogID = ?
", $this->id, $logId
);
if (self::$db->affected_rows() > 0) {
return $this->modifyLogscore();
}
return 0;
}
public function modifyLogscore(): int {
$count = self::$db->scalar("
SELECT count(*) FROM torrents_logs WHERE TorrentID = ?
", $this->id
);
if (!$count) {
self::$db->prepared_query("
UPDATE torrents SET
HasLogDB = '0',
LogChecksum = '0',
LogScore = 0
WHERE ID = ?
", $this->id
);
} else {
self::$db->prepared_query("
UPDATE torrents AS t
LEFT JOIN (
SELECT TorrentID,
min(CASE WHEN Adjusted = '1' AND AdjustedScore != Score THEN AdjustedScore ELSE Score END) AS Score,
min(CASE WHEN Adjusted = '1' AND AdjustedChecksum != Checksum THEN AdjustedChecksum ELSE Checksum END) AS Checksum
FROM torrents_logs
WHERE TorrentID = ?
GROUP BY TorrentID
) AS tl ON (t.ID = tl.TorrentID)
SET
t.HasLogDB = '1',
t.LogScore = tl.Score,
t.LogChecksum = tl.Checksum
WHERE t.ID = ?
", $this->id, $this->id
);
}
$affected = self::$db->affected_rows();
$this->flush();
return $affected;
}
public function rescoreLog(int $logId, \Gazelle\Logfile $logfile, string $version): int {
self::$db->prepared_query("
UPDATE torrents_logs SET
Score = ?, `Checksum` = ?, ChecksumState = ?, Ripper = ?, RipperVersion = ?,
`Language` = ?, Details = ?, LogcheckerVersion = ?,
Adjusted = '0'
WHERE TorrentID = ? AND LogID = ?
", $logfile->score(), $logfile->checksumStatus(), $logfile->checksumState(), $logfile->ripper(), $logfile->ripperVersion(),
$logfile->language(), $logfile->detailsAsString(), $version,
$this->id, $logId
);
if (self::$db->affected_rows() > 0) {
return $this->modifyLogscore();
}
return 0;
}
/**
* Remove all logfiles attached to this upload
*
* @return int number of logfiles removed
*/
public function removeAllLogs(User $user, File\RipLog $ripLog, File\RipLogHTML $ripLogHtml, Log $logger): int {
self::$db->begin_transaction();
self::$db->prepared_query("
DELETE FROM torrents_logs WHERE TorrentID = ?
", $this->id
);
$affected = self::$db->affected_rows();
self::$db->prepared_query("
UPDATE torrents SET
HasLog = '1',
HasLogDB = '0',
LogChecksum = '0',
LogScore = 0
WHERE ID = ?
", $this->id
);
$logger->torrent($this->groupId(), $this->id, $user->id(), "All logs removed from torrent");
self::$db->commit();
$this->flush();
$ripLog->remove([$this->id, null]);
$ripLogHtml->remove([$this->id, null]);
return $affected;
}
public function removeLogDb(): int {
self::$db->prepared_query('
DELETE FROM torrents_logs WHERE TorrentID = ?
', $this->id
);
return self::$db->affected_rows();
}
/**
* Issue a reseed request (via PM) to the uploader and 100
* most recent enabled snatchers
*
* @return int number of people messaged
*/
public function issueReseedRequest(User $viewer): int {
self::$db->prepared_query('
UPDATE torrents SET
LastReseedRequest = now()
WHERE ID = ?
', $this->id
);
self::$db->prepared_query("
SELECT s.uid AS id,
'snatched' AS action,
from_unixtime(max(s.tstamp)) AS tdate
FROM xbt_snatched AS s
INNER JOIN users_main AS u ON (s.uid = u.ID)
WHERE s.fid = ?
AND u.Enabled = ?
GROUP BY s.uid
ORDER BY s.tstamp DESC
LIMIT 100
", $this->id, '1'
);
$notify = self::$db->to_array('id', MYSQLI_ASSOC, false);
$notify[$this->uploaderId()] = [
'action' => 'uploaded',
'tdate' => $this->created(),
];
$userMan = new Manager\User;
$groupId = $this->groupId();
$name = $this->group()->text();
$torrentId = $this->id;
foreach ($notify as $userId => $info) {
$userMan->sendPM($userId, 0,
"Re-seed request for torrent $name",
self::$twig->render('torrent/reseed-pm.twig', [
'action' => $info['action'],
'date' => $info['tdate'],
'group_id' => $groupId,
'torrent_id' => $torrentId,
'name' => $name,
'user' => new User($userId),
'viewer' => $viewer,
])
);
}
$this->flush();
return count($notify);
}
public function hasFlag(TorrentFlag $flag): bool {
return (bool)self::$db->scalar("
SELECT 1 FROM {$flag->value} WHERE TorrentID = ?
", $this->id
);
}
public function addFlag(TorrentFlag $flag, User $user): int {
self::$db->prepared_query("
INSERT IGNORE INTO {$flag->value} (TorrentID, UserID) VALUES (?, ?)
", $this->id, $user->id()
);
return self::$db->affected_rows();
}
public function removeFlag(TorrentFlag $flag): int {
self::$db->prepared_query("
DELETE FROM {$flag->value} WHERE TorrentID = ?
", $this->id
);
return self::$db->affected_rows();
}
/**
* Remove a torrent.
*/
public function remove(?User $user, string $reason, int $trackerReason = -1): array {
$qid = self::$db->get_query_id();
$this->info();
if ($this->id > MAX_PREV_TORRENT_ID) {
(new \Gazelle\User\Bonus($this->uploader()))->removePointsForUpload($this);
}
$edition = $this->edition();
$groupId = $this->group()->id();
$infohash = $this->infohash();
$sizeMB = number_format($this->size() / (1024 * 1024), 2) . ' MiB';
$name = $this->name();
(new \Gazelle\Tracker)->update_tracker('delete_torrent', [
'id' => $this->id,
'info_hash' => $this->infohashEncoded(),
'reason' => $trackerReason,
]);
$manager = new \Gazelle\DB;
$manager->relaxConstraints(true);
[$ok, $message] = $manager->softDelete(SQLDB, 'torrents_leech_stats', [['TorrentID', $this->id]], false);
if (!$ok) {
return [false, $message];
}
[$ok, $message] = $manager->softDelete(SQLDB, 'torrents', [['ID', $this->id]]);
$manager->relaxConstraints(false);
$manager->softDelete(SQLDB, 'torrents_files', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_bad_files', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_bad_folders', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_bad_tags', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_cassette_approved', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_lossymaster_approved', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_lossyweb_approved', [['TorrentID', $this->id]]);
$manager->softDelete(SQLDB, 'torrents_missing_lineage', [['TorrentID', $this->id]]);
self::$db->prepared_query("
DELETE FROM torrent_unseeded WHERE torrent_id = ?
", $this->id
);
self::$db->prepared_query("
DELETE FROM torrent_unseeded_claim WHERE torrent_id = ?
", $this->id
);
// Tells Sphinx that the group is removed
self::$db->prepared_query("
REPLACE INTO sphinx_delta
(ID, Time)
VALUES (?, now())
", $this->id
);
self::$db->prepared_query("
UPDATE reportsv2 SET
Status = 'Resolved',
LastChangeTime = now(),
ModComment = 'Report already dealt with (torrent deleted)'
WHERE Status != 'Resolved'
AND TorrentID = ?
", $this->id
);
$count = self::$db->affected_rows();
if ($count) {
self::$cache->decrement('num_torrent_reportsv2', $count);
}
// Torrent notifications
$this->pg()->prepared_query("
DELETE FROM notification_ticket WHERE id_torrent = ?
", $this->id
);
self::$db->prepared_query("
SELECT concat('user_notify_upload_', UserID) as ck
FROM users_notify_torrents
WHERE TorrentID = ?
", $this->id
);
$deleteKeys = self::$db->collect('ck', false);
$manager->softDelete(SQLDB, 'users_notify_torrents', [['TorrentID', $this->id]]);
if (!is_null($user)) {
$key = sprintf(self::USER_RECENT_UPLOAD, $user->id());
$recent = self::$cache->get_value($key);
if (is_array($recent) && in_array($groupId, $recent)) {
$deleteKeys[] = $key;
}
self::$db->prepared_query("
INSERT INTO user_torrent_remove
(user_id, torrent_id)
VALUES (?, ?)
", $user->id(), $this->id
);
}
array_push($deleteKeys, "zz_t_" . $this->id, sprintf(self::CACHE_KEY, $this->id), "torrent_group_" . $groupId);
self::$cache->delete_multi($deleteKeys);
self::$cache->decrement('stats_torrent_count');
$this->group()->refresh();
$this->flush();
$userInfo = $user ? " by " . $user->username() : '';
(new Log)->general(
"Torrent {$this->id} ($name) [$edition] ($sizeMB $infohash) was deleted$userInfo for reason: $reason")
->torrent(
$groupId, $this->id, $user?->id(),
"deleted torrent ($sizeMB $infohash) for reason: $reason"
);
self::$db->set_query_id($qid);
return [true, "torrent " . $this->id . " removed"];
}
public function expireToken(int $userId): bool {
$hash = (string)self::$db->scalar("
SELECT info_hash FROM torrents WHERE ID = ?
", $this->id
);
if (!$hash) {
return false;
}
self::$db->prepared_query("
UPDATE users_freeleeches SET
Expired = true
WHERE UserID = ?
AND TorrentID = ?
", $userId, $this->id
);
self::$cache->delete_value("users_tokens_{$userId}");
(new \Gazelle\Tracker)->update_tracker('remove_token', ['info_hash' => rawurlencode($hash), 'userid' => $userId]);
return true;
}
/**
* Get the requests filled by this torrent.
*/
public function requestFills(): array {
self::$db->prepared_query("
SELECT r.ID, r.FillerID, r.TimeFilled FROM requests AS r WHERE r.TorrentID = ?
", $this->id
);
return self::$db->to_array(false, MYSQLI_NUM, false);
}
public function seederList(int $userId, int $limit, int $offset): array {
$key = sprintf(self::CACHE_KEY_PEERLIST_PAGE, $this->id, $offset);
$list = self::$cache->get_value($key);
if ($list === false) {
// force flush the next page of results
self::$cache->delete_value(sprintf(self::CACHE_KEY_PEERLIST_PAGE, $this->id, $offset + $limit));
self::$db->prepared_query("
SELECT
xfu.active,
xfu.connectable,
xfu.remaining,
xfu.uploaded,
xfu.useragent,
xfu.ip AS ipv4addr,
xfu.uid AS user_id,
t.Size AS size,
sx.name AS seedbox,
EXISTS(SELECT 1 FROM users_downloads ud WHERE ud.UserID = xfu.uid AND ud.TorrentID = xfu.fid) AS is_download,
EXISTS(SELECT 1 FROM xbt_snatched xs WHERE xs.uid = xfu.uid AND xs.fid = xfu.fid) AS is_snatched
FROM xbt_files_users AS xfu
INNER JOIN users_main AS um ON (um.ID = xfu.uid)
INNER JOIN torrents AS t ON (t.ID = xfu.fid)
LEFT JOIN user_seedbox sx ON (xfu.ip = inet_ntoa(sx.ipaddr) AND xfu.useragent = sx.useragent AND xfu.uid = ?)
WHERE um.Visible = '1'
AND xfu.fid = ?
ORDER BY xfu.uid = ? DESC, xfu.uploaded DESC
LIMIT ? OFFSET ?
", $userId, $this->id, $userId, $limit, $offset
);
$list = self::$db->to_array(false, MYSQLI_ASSOC, false);
self::$cache->cache_value($key, $list, 300);
}
return $list;
}
public function downloadTotal(): int {
return (int)self::$db->scalar("
SELECT count(DISTINCT UserID) FROM users_downloads WHERE TorrentID = ?
", $this->id
);
}
public function downloadList(int $limit, int $offset): array {
self::$db->prepared_query("
SELECT ud.UserID AS user_id,
min(ud.Time) AS timestamp,
count(*) AS total,
EXISTS(SELECT 1 FROM xbt_snatched xs WHERE xs.uid = ud.UserID AND xs.fid = ud.TorrentID) AS is_snatched,
EXISTS(SELECT 1 FROM xbt_files_users xfu WHERE xfu.uid = ud.UserID AND xfu.fid = ud.TorrentID) AS is_seeding
FROM users_downloads ud
WHERE ud.TorrentID = ?
GROUP BY user_id, is_snatched, is_seeding
ORDER BY ud.Time DESC, ud.UserID
LIMIT ? OFFSET ?
", $this->id, $limit, $offset
);
return self::$db->to_array(false, MYSQLI_ASSOC, false);
}
public function snatchList(int $limit, int $offset): array {
self::$db->prepared_query("
SELECT xs.uid AS user_id,
from_unixtime(xs.tstamp) AS timestamp,
EXISTS(SELECT 1 FROM users_downloads ud WHERE ud.UserID = xs.uid AND ud.TorrentID = xs.fid) AS is_download,
EXISTS(SELECT 1 FROM xbt_files_users xfu WHERE xfu.uid = xs.uid AND xfu.fid = xs.fid) AS is_seeding
FROM xbt_snatched xs
WHERE xs.fid = ?
ORDER BY xs.tstamp DESC
LIMIT ? OFFSET ?
", $this->id, $limit, $offset
);
return self::$db->to_array(false, MYSQLI_ASSOC, false);
}
/**
* Create a string that contains file info in a format that's easy to use for Sphinx
*
* @return string with the format .EXT sSIZEs NAME DELIMITER
*/
public function metaFilename(string $name, int $size): string {
$name = make_utf8(strtr($name, "\n\r\t", ' '));
$extPos = mb_strrpos($name, '.');
$ext = $extPos === false ? '' : trim(mb_substr($name, $extPos + 1));
return sprintf(".%s s%ds %s %s", $ext, $size, $name, FILELIST_DELIM);
}
public function flushFoldernameCache(): void {
self::$cache->delete_value(sprintf(self::CACHE_FOLDERNAME, md5($this->path())));
}
/**
* Regenerate a torrent's file list from its meta data.
*
* @return int number of files regenned
*/
public function regenerateFilelist(\Gazelle\File\Torrent $filer, \OrpheusNET\BencodeTorrent\BencodeTorrent $encoder): int {
$torrentFile = $filer->get($this->id);
if ($torrentFile === false) {
return 0;
}
$encoder->decodeString($torrentFile);
$data = $encoder->getData();
[
'total_size' => $totalSize,
'files' => $fileList
] = $encoder->getFileList();
$this->setField('Size', $totalSize)
->setField('FilePath', isset($data['info']['files']) ? make_utf8($encoder->getName()) : '')
->setField('FileList', implode("\n",
array_map(fn($f) => $this->metaFilename($f['path'], $f['size']), $fileList)
))
->modify();
$this->flushFoldernameCache();
return count($fileList);
}
}