-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathTorrentController.php
818 lines (716 loc) · 35.2 KB
/
TorrentController.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
<?php
declare(strict_types=1);
/**
* NOTICE OF LICENSE.
*
* UNIT3D Community Edition is open-sourced software licensed under the GNU Affero General Public License v3.0
* The details is bundled with this project in the file LICENSE.txt.
*
* @project UNIT3D Community Edition
*
* @author HDVinnie <hdinnovations@protonmail.com>
* @license https://www.gnu.org/licenses/agpl-3.0.en.html/ GNU Affero General Public License v3.0
*/
namespace App\Http\Controllers\API;
use App\DTO\TorrentSearchFiltersDTO;
use App\Helpers\Bencode;
use App\Helpers\TorrentHelper;
use App\Helpers\TorrentTools;
use App\Helpers\UrlHelper;
use App\Http\Resources\TorrentResource;
use App\Http\Resources\TorrentsResource;
use App\Models\Category;
use App\Models\FeaturedTorrent;
use App\Models\Keyword;
use App\Models\Movie;
use App\Models\Torrent;
use App\Models\TorrentFile;
use App\Models\Tv;
use App\Models\User;
use App\Repositories\ChatRepository;
use App\Services\Tmdb\TMDBScraper;
use App\Services\Unit3dAnnounce;
use App\Traits\TorrentMeta;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use MarcReichel\IGDBLaravel\Models\Game;
use Meilisearch\Endpoints\Indexes;
/**
* @see \Tests\Todo\Feature\Http\Controllers\TorrentControllerTest
*/
class TorrentController extends BaseController
{
use TorrentMeta;
public int $perPage = 25;
public string $sortField = 'bumped_at';
public string $sortDirection = 'desc';
/**
* TorrentController Constructor.
*/
public function __construct(private readonly ChatRepository $chatRepository)
{
}
/**
* Display a listing of the resource.
*/
public function index(): TorrentsResource
{
$torrents = cache()->remember('torrent-api-index', 300, function () {
$torrents = Torrent::with(
['user:id,username', 'category', 'type', 'resolution', 'region', 'distributor', 'files']
)
->select('*')
->selectRaw(
"
CASE
WHEN category_id IN (SELECT `id` from `categories` where `movie_meta` = 1) THEN 'movie'
WHEN category_id IN (SELECT `id` from `categories` where `tv_meta` = 1) THEN 'tv'
WHEN category_id IN (SELECT `id` from `categories` where `game_meta` = 1) THEN 'game'
WHEN category_id IN (SELECT `id` from `categories` where `music_meta` = 1) THEN 'music'
WHEN category_id IN (SELECT `id` from `categories` where `no_meta` = 1) THEN 'no'
END as meta
"
)
->latest('sticky')
->latest('bumped_at')
->cursorPaginate(25);
// See app/Traits/TorrentMeta.php
$this->scopeMeta($torrents);
return $torrents;
});
return new TorrentsResource($torrents);
}
// handle cover_url or banner_url
private function handleImage($url, $type, $torrentId)
{
if (UrlHelper::isTrustedExternalHost($url)) {
return $url; // Directly store the URL if it's in Trusted External Hosts
} else {
return $this->downloadAndStoreImage($url, $type, $torrentId);
}
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): \Illuminate\Http\JsonResponse
{
$user = $request->user();
abort_unless($user->can_upload ?? $user->group->can_upload, 403, __('torrent.cant-upload').' '.__('torrent.cant-upload-desc'));
$requestFile = $request->file('torrent');
if (!$request->hasFile('torrent')) {
return $this->sendError('Validation Error.', 'You Must Provide A Torrent File For Upload!');
}
if ($requestFile->getError() !== 0 || $requestFile->getClientOriginalExtension() !== 'torrent') {
return $this->sendError('Validation Error.', 'You Must Provide A Valid Torrent File For Upload!');
}
// Deplace and decode the torrent temporarily
$decodedTorrent = TorrentTools::normalizeTorrent($requestFile);
$infohash = Bencode::get_infohash($decodedTorrent);
try {
$meta = Bencode::get_meta($decodedTorrent);
} catch (Exception) {
return $this->sendError('Validation Error.', 'You Must Provide A Valid Torrent File For Upload!');
}
foreach (TorrentTools::getFilenameArray($decodedTorrent) as $name) {
if (!TorrentTools::isValidFilename($name)) {
return $this->sendError('Validation Error.', 'Invalid Filenames In Torrent Files!');
}
}
$fileName = \sprintf('%s.torrent', uniqid('', true)); // Generate a unique name
Storage::disk('torrents')->put($fileName, Bencode::bencode($decodedTorrent));
// Find the right category
$category = Category::withCount('torrents')->findOrFail($request->integer('category_id'));
// Create the torrent (DB)
$torrent = app()->make(Torrent::class);
$torrent->name = $request->input('name');
$torrent->description = $request->input('description');
$torrent->mediainfo = TorrentTools::anonymizeMediainfo($request->filled('mediainfo') ? $request->string('mediainfo') : null);
$torrent->bdinfo = $request->input('bdinfo');
$torrent->info_hash = $infohash;
$torrent->file_name = $fileName;
$torrent->num_file = $meta['count'];
$torrent->folder = Bencode::get_name($decodedTorrent);
$torrent->size = $meta['size'];
$torrent->nfo = ($request->hasFile('nfo')) ? TorrentTools::getNfo($request->file('nfo')) : '';
$torrent->category_id = $category->id;
$torrent->type_id = $request->input('type_id');
$torrent->resolution_id = $request->input('resolution_id');
$torrent->region_id = $request->input('region_id');
$torrent->distributor_id = $request->input('distributor_id');
$torrent->user_id = $user->id;
$torrent->imdb = $request->input('imdb');
$torrent->tvdb = $request->input('tvdb');
$torrent->tmdb = $request->input('tmdb');
$torrent->mal = $request->input('mal');
$torrent->igdb = $request->input('igdb');
$torrent->season_number = $request->input('season_number');
$torrent->episode_number = $request->input('episode_number');
$torrent->anon = $request->input('anonymous');
$torrent->stream = $request->input('stream');
$torrent->sd = $request->input('sd');
$torrent->personal_release = $request->input('personal_release') ?? 0;
$torrent->internal = $user->group->is_modo || $user->group->is_internal ? ($request->input('internal') ?? 0) : 0;
$torrent->featured = $user->group->is_modo || $user->group->is_internal ? ($request->input('featured') ?? false) : false;
$torrent->doubleup = $user->group->is_modo || $user->group->is_internal ? ($request->input('doubleup') ?? 0) : 0;
$torrent->refundable = $user->group->is_modo || $user->group->is_internal ? ($request->input('refundable') ?? false) : false;
$du_until = $request->input('du_until');
// Check and set if it's in safe external hosts
if ($request->has('cover_url')) {
$coverUrl = $request->input('cover_url');
if (UrlHelper::isTrustedExternalHost($coverUrl)) {
$torrent->cover_url = $coverUrl;
}
// Note: We don't set it here if not safe external host because we need the torrent ID at save
}
// Check and set banner_url if it's safe external hosts
if ($request->has('banner_url')) {
$bannerUrl = $request->input('banner_url');
if (UrlHelper::isTrustedExternalHost($bannerUrl)) {
$torrent->banner_url = $bannerUrl;
}
// Note: We don't set it here if not safe external host because we need the torrent ID at save
}
if (($user->group->is_modo || $user->group->is_internal) && isset($du_until)) {
$torrent->du_until = Carbon::now()->addDays($request->integer('du_until'));
}
$torrent->free = $user->group->is_modo || $user->group->is_internal ? ($request->input('free') ?? 0) : 0;
$fl_until = $request->input('fl_until');
if (($user->group->is_modo || $user->group->is_internal) && isset($fl_until)) {
$torrent->fl_until = Carbon::now()->addDays($request->integer('fl_until'));
}
$torrent->sticky = $user->group->is_modo || $user->group->is_internal ? ($request->input('sticky') ?? 0) : 0;
$torrent->moderated_at = Carbon::now();
$torrent->moderated_by = User::SYSTEM_USER_ID;
// Set freeleech and doubleup if featured
if ($torrent->featured === true) {
$torrent->free = 100;
$torrent->doubleup = true;
}
// Validation
$v = validator($torrent->toArray(), [
'cover_url' => ['nullable', 'url', 'regex:/\.(avif|bmp|eps|heic|heif|jpe?g|png|svg|tiff?|webp)$/i'],
'banner_url' => ['nullable', 'url', 'regex:/\.(avif|bmp|eps|heic|heif|jpe?g|png|svg|tiff?|webp)$/i'],
'name' => [
'required',
Rule::unique('torrents')->whereNull('deleted_at'),
'max:255',
],
'description' => [
'required',
],
'info_hash' => [
'required',
Rule::unique('torrents')->whereNull('deleted_at'),
],
'file_name' => [
'required',
],
'num_file' => [
'required',
'numeric',
],
'size' => [
'required',
],
'category_id' => [
'required',
'exists:categories,id',
],
'type_id' => [
'required',
'exists:types,id',
],
'resolution_id' => [
Rule::when($category->movie_meta || $category->tv_meta, 'required'),
Rule::when(!$category->movie_meta && !$category->tv_meta, 'nullable'),
'exists:resolutions,id',
],
'region_id' => [
'nullable',
'exists:regions,id',
],
'distributor_id' => [
'nullable',
'exists:distributors,id',
],
'user_id' => [
'required',
'exists:users,id',
],
'imdb' => [
'required',
'numeric',
],
'tvdb' => [
'required',
'numeric',
],
'tmdb' => [
'required',
'numeric',
],
'mal' => [
'required',
'numeric',
],
'igdb' => [
'required',
'numeric',
],
'season_number' => [
Rule::when($category->tv_meta, [
'required',
'numeric',
'integer',
]),
Rule::prohibitedIf(!$category->tv_meta),
],
'episode_number' => [
Rule::when($category->tv_meta, [
'required',
'numeric',
'integer',
]),
Rule::prohibitedIf(!$category->tv_meta),
],
'anon' => [
'required',
],
'stream' => [
'required',
],
'sd' => [
'required',
],
'personal_release' => [
'nullable',
],
'internal' => [
'required',
],
'featured' => [
'required',
],
'free' => [
'required',
'between:0,100',
],
'doubleup' => [
'required',
],
'refundable' => [
'required',
],
'sticky' => [
'required',
],
]);
if ($v->fails()) {
if (Storage::disk('torrents')->exists($fileName)) {
Storage::disk('torrents')->delete($fileName);
}
return $this->sendError('Validation Error.', $v->errors());
}
// Save The Torrent
$torrent->save();
// Set cover and/or banner _ if not safe2host externally
if ($request->has('cover_url') && !$torrent->cover_url) {
$torrent->cover_url = $this->handleImage($request->input('cover_url'), 'cover', $torrent->id);
}
if ($request->has('banner_url') && !$torrent->banner_url) {
$torrent->banner_url = $this->handleImage($request->input('banner_url'), 'banner', $torrent->id);
}
// Populate the status/seeders/leechers/times_completed fields for the external tracker
$torrent->refresh();
// Backup the files contained in the torrent
$files = TorrentTools::getTorrentFiles($decodedTorrent);
foreach ($files as &$file) {
$file['torrent_id'] = $torrent->id;
}
// Can't insert them all at once since some torrents have more files than mysql supports placeholders.
// Divide by 3 since we're inserting 3 fields: name, size and torrent_id
foreach (collect($files)->chunk(intdiv(65_000, 3)) as $files) {
TorrentFile::insert($files->toArray());
}
// Set torrent to featured
if ($torrent->getAttribute('featured')) {
$featuredTorrent = new FeaturedTorrent();
$featuredTorrent->user_id = $user->id;
$featuredTorrent->torrent_id = $torrent->id;
$featuredTorrent->save();
}
// Tracker updates come after database updates in case tracker's offline
Unit3dAnnounce::addTorrent($torrent);
if ($torrent->getAttribute('featured')) {
Unit3dAnnounce::addFeaturedTorrent($torrent->id);
}
// TMDB updates come after tracker updates in case TMDB's offline
$tmdbScraper = new TMDBScraper();
if ($torrent->category->tv_meta && $torrent->tmdb) {
$tmdbScraper->tv($torrent->tmdb);
}
if ($torrent->category->movie_meta && $torrent->tmdb) {
$tmdbScraper->movie($torrent->tmdb);
}
// Torrent Keywords System
$keywords = [];
foreach (TorrentTools::parseKeywords($request->string('keywords')) as $keyword) {
$keywords[] = ['torrent_id' => $torrent->id, 'name' => $keyword];
}
foreach (collect($keywords)->chunk(intdiv(65_000, 2)) as $keywords) {
Keyword::upsert($keywords->toArray(), ['torrent_id', 'name']);
}
// check for trusted user and update torrent
if ($user->group->is_trusted) {
$appurl = config('app.url');
$user = $torrent->user;
$username = $user->username;
$anon = $torrent->anon;
$featured = $torrent->getAttribute('featured');
$free = $torrent->free;
$doubleup = $torrent->doubleup;
// Announce To Shoutbox
if ($anon == 0) {
$this->chatRepository->systemMessage(
\sprintf('User [url=%s/users/', $appurl).$username.']'.$username.\sprintf('[/url] has uploaded a new '.$torrent->category->name.'. [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url], grab it now!'
);
} else {
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has uploaded a new '.$torrent->category->name.'. [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url], grab it now!'
);
}
if ($anon == 1 && $featured == 1) {
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been added to the Featured Torrents Slider by an anonymous user! Grab It While You Can!'
);
} elseif ($anon == 0 && $featured == 1) {
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.\sprintf('[/url] has been added to the Featured Torrents Slider by [url=%s/users/', $appurl).$username.']'.$username.'[/url]! Grab It While You Can!'
);
}
if ($free >= 1 && $featured == 0) {
if ($torrent->fl_until === null) {
$this->chatRepository->systemMessage(
\sprintf(
'Ladies and Gents, [url=%s/torrents/',
$appurl
).$torrent->id.']'.$torrent->name.'[/url] has been granted '.$free.'% FreeLeech! Grab It While You Can!'
);
} else {
$this->chatRepository->systemMessage(
\sprintf(
'Ladies and Gents, [url=%s/torrents/',
$appurl
).$torrent->id.']'.$torrent->name.'[/url] has been granted '.$free.'% FreeLeech for '.$request->input('fl_until').' days.'
);
}
}
if ($doubleup == 1 && $featured == 0) {
if ($torrent->du_until === null) {
$this->chatRepository->systemMessage(
\sprintf(
'Ladies and Gents, [url=%s/torrents/',
$appurl
).$torrent->id.']'.$torrent->name.'[/url] has been granted Double Upload! Grab It While You Can!'
);
} else {
$this->chatRepository->systemMessage(
\sprintf(
'Ladies and Gents, [url=%s/torrents/',
$appurl
).$torrent->id.']'.$torrent->name.'[/url] has been granted Double Upload for '.$request->input('du_until').' days.'
);
}
}
TorrentHelper::approveHelper($torrent->id);
}
return $this->sendResponse(route('torrent.download.rsskey', ['id' => $torrent->id, 'rsskey' => auth('api')->user()->rsskey]), 'Torrent uploaded successfully.');
}
/**
* Download image from URL and store it locally, returning the URL to stored image.
* If size cannot be checked beforehand, temporarily download, check size (discard if oversized) else compress then rename.
*
* @param string $url
* @param string $type ('cover' or 'banner')
* @param int $torrentId
* @return string|null
*/
private function downloadAndStoreImage($url, $type, int $torrentId)
{
try {
$headers = get_headers($url, true);
$contentLength = isset($headers['Content-Length']) ? (int)$headers['Content-Length'] : null;
$prefix = ($type === 'cover') ? 'torrent-cover' : 'torrent-banner';
$tempName = "{$prefix}_{$torrentId}_temp";
$finalName = "{$prefix}_{$torrentId}.webp";
$tempPath = public_path('/files/img/') . $tempName;
$finalPath = public_path('/files/img/') . $finalName;
// Skip if over 12MB -- should be easily configurable. Note: 10MB PNG can be crunched to 200-400Kb in WebP
if ($contentLength !== null && $contentLength > 12 * 1024 * 1024) {
\Log::warning("Image from URL {$url} exceeds the 12MB size limit. Skipping download.");
return null;
}
$contents = file_get_contents($url);
if ($contents === false) {
throw new \Exception("Failed to fetch image from URL");
}
if (!file_put_contents($tempPath, $contents)) {
throw new \Exception("Failed to save temporary image");
}
$imageInfo = getimagesize($tempPath);
$mimeType = $imageInfo['mime'];
if ($mimeType === 'image/webp') { // No need to convert if already webP
rename($tempPath, $finalPath);
return asset('files/img/' . $finalName);
}
// Convert and compress based on size
$actualSize = $contentLength ?? filesize($tempPath);
$image = new \Imagick($tempPath);
// Preserve Alpha Channels (Transparency)
if ($image->getImageAlphaChannel() !== \Imagick::ALPHACHANNEL_ACTIVATE) {
$image->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
}
// Strip all metadata
$image->stripImage();
// Ensure alpha channel remains active after stripping
$image->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
// Convert to WebP with appropriate quality
$quality = $actualSize <= 2 * 1024 * 1024 ? 100 : 80;
$image->setImageFormat('webp');
$image->setImageCompressionQuality($quality);
$image->setOption('webp:lossless', 'false');
$image->writeImage($finalPath);
unlink($tempPath); // Remove the temporary file
return asset('files/img/' . $finalName);
} catch (\Exception $e) {
\Log::error("Failed to download and store image: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
if (isset($tempPath) && file_exists($tempPath)) {
unlink($tempPath);
}
return null;
}
}
/**
* Display the specified resource.
*/
public function show(int $id): TorrentResource
{
$torrent = Torrent::with(['user:id,username', 'category', 'type', 'resolution', 'region', 'distributor', 'files'])
->select('*')
->selectRaw("
CASE
WHEN category_id IN (SELECT `id` from `categories` where `movie_meta` = 1) THEN 'movie'
WHEN category_id IN (SELECT `id` from `categories` where `tv_meta` = 1) THEN 'tv'
WHEN category_id IN (SELECT `id` from `categories` where `game_meta` = 1) THEN 'game'
WHEN category_id IN (SELECT `id` from `categories` where `music_meta` = 1) THEN 'music'
WHEN category_id IN (SELECT `id` from `categories` where `no_meta` = 1) THEN 'no'
END as meta
")
->findOrFail($id);
$torrent->setAttribute('meta', null);
if ($torrent->category->tv_meta && $torrent->tmdb) {
$torrent->setAttribute('meta', Tv::with(['genres'])->find($torrent->tmdb));
}
if ($torrent->category->movie_meta && $torrent->tmdb) {
$torrent->setAttribute('meta', Movie::with(['genres'])->find($torrent->tmdb));
}
if ($torrent->category->game_meta && $torrent->igdb) {
$torrent->setAttribute('meta', Game::with(['genres' => ['name']])->find($torrent->igdb));
}
TorrentResource::withoutWrapping();
return new TorrentResource($torrent);
}
/**
* Uses Input's To Put Together A Search.
*/
public function filter(Request $request): TorrentsResource|\Illuminate\Http\JsonResponse
{
$user = auth()->user()->load('group');
$isRegexAllowed = $user->group->is_modo;
$isSqlAllowed = ($user->group->is_modo || $user->group->is_editor) && $request->driver === 'sql';
$request->validate([
'sortField' => [
'nullable',
'sometimes',
'in:name,size,seeders,leechers,times_completed,created_at,bumped_at',
],
'sortDirection' => [
'nullable',
'sometimes',
'in:asc,desc'
]
]);
// Caching
$url = $request->url();
$queryParams = $request->query();
// Don't cache the api_token so that multiple users can share the cache
unset($queryParams['api_token']);
$queryParams['isRegexAllowed'] = $isRegexAllowed;
$queryParams['isSqlAllowed'] = $isSqlAllowed;
// Sorting query params by key (acts by reference)
ksort($queryParams);
// Transforming the query array to query string
$queryString = http_build_query($queryParams);
$cacheKey = $url.'?'.$queryString;
/** @phpstan-ignore method.unresolvableReturnType (phpstan is unable to resolve type because it's returning a phpstan-ignored line) */
[$torrents, $hasMore] = cache()->remember($cacheKey, 300, function () use ($request, $isSqlAllowed) {
$eagerLoads = fn (Builder $query) => $query
->with(['user:id,username', 'category', 'type', 'resolution', 'distributor', 'region', 'files'])
->select('*')
->selectRaw("
CASE
WHEN category_id IN (SELECT `id` from `categories` where `movie_meta` = 1) THEN 'movie'
WHEN category_id IN (SELECT `id` from `categories` where `tv_meta` = 1) THEN 'tv'
WHEN category_id IN (SELECT `id` from `categories` where `game_meta` = 1) THEN 'game'
WHEN category_id IN (SELECT `id` from `categories` where `music_meta` = 1) THEN 'music'
WHEN category_id IN (SELECT `id` from `categories` where `no_meta` = 1) THEN 'no'
END as meta
");
$filters = new TorrentSearchFiltersDTO(
name: $request->filled('name') ? $request->string('name')->toString() : '',
description: $request->filled('description') ? $request->string('description')->toString() : '',
mediainfo: $request->filled('mediainfo') ? $request->string('mediainfo')->toString() : '',
uploader: $request->filled('uploader') ? $request->string('uploader')->toString() : '',
keywords: $request->filled('keywords') ? array_map('trim', explode(',', $request->string('keywords')->toString())) : [],
startYear: $request->filled('startYear') ? $request->integer('startYear') : null,
endYear: $request->filled('endYear') ? $request->integer('endYear') : null,
categoryIds: $request->filled('categories') ? array_map('intval', $request->categories) : [],
typeIds: $request->filled('types') ? array_map('intval', $request->types) : [],
resolutionIds: $request->filled('resolutions') ? array_map('intval', $request->resolutions) : [],
genreIds: $request->filled('genres') ? array_map('intval', $request->genres) : [],
tmdbId: $request->filled('tmdbId') ? $request->integer('tmdbId') : null,
imdbId: $request->filled('imdbId') ? $request->integer('imdbId') : null,
tvdbId: $request->filled('tvdbId') ? $request->integer('tvdbId') : null,
malId: $request->filled('malId') ? $request->integer('malId') : null,
playlistId: $request->filled('playlistId') ? $request->integer('playlistId') : null,
collectionId: $request->filled('collectionId') ? $request->integer('collectionId') : null,
primaryLanguageNames: $request->filled('primaryLanguages') ? array_map('str', $request->primaryLanguages) : [],
adult: $request->filled('adult') ? $request->boolean('adult') : null,
free: $request->filled('free') ? array_map('intval', (array) $request->free) : [],
doubleup: $request->filled('doubleup'),
refundable: $request->filled('refundable'),
featured: $request->filled('featured'),
stream: $request->filled('stream'),
sd: $request->filled('sd'),
highspeed: $request->filled('highspeed'),
internal: $request->filled('internal'),
personalRelease: $request->filled('personalRelease'),
alive: $request->filled('alive'),
dying: $request->filled('dying'),
dead: $request->filled('dead'),
filename: $request->filled('file_name') ? $request->string('file_name')->toString() : '',
seasonNumber: $request->filled('seasonNumber') ? $request->integer('seasonNumber') : null,
episodeNumber: $request->filled('episodeNumber') ? $request->integer('episodeNumber') : null,
);
if ($isSqlAllowed) {
$torrents = Torrent::query()
->where($filters->toSqlQueryBuilder())
->latest('sticky')
->orderBy($request->input('sortField') ?? $this->sortField, $request->input('sortDirection') ?? $this->sortDirection)
->cursorPaginate(min($request->input('perPage') ?? $this->perPage, 100));
// See app/Traits/TorrentMeta.php
$this->scopeMeta($torrents);
$hasMore = $torrents->nextCursor() !== null;
} else {
$paginator = Torrent::search(
$request->filled('name') ? $request->string('name')->toString() : '',
function (Indexes $meilisearch, string $query, array $options) use ($request, $filters) {
$options['sort'] = [
($request->input('sortField') ?: $this->sortField).':'.($request->input('sortDirection') ?? $this->sortDirection),
];
$options['filter'] = $filters->toMeilisearchFilter();
$options['matchingStrategy'] = 'all';
$results = $meilisearch->search($query, $options);
return $results;
}
)
->query($eagerLoads)
->simplePaginateRaw(min($request->input('perPage') ?? $this->perPage, 100));
$hasMore = $paginator->hasMorePages();
/** @phpstan-ignore method.notFound (this method exists at time of writing) */
$results = $paginator->getCollection();
$torrents = collect();
foreach ($results['hits'] ?? [] as $hit) {
$meta = $hit['movie'] ?? $hit['tv'] ?? [];
/** @see TorrentResource */
$torrents->push([
'type' => 'torrent',
'id' => (string) $hit['id'],
'attributes' => [
'meta' => [
'poster' => \array_key_exists('poster', $meta) ? tmdb_image('poster_small', $meta['poster']) : null,
'genres' => \array_key_exists('genres', $meta) ? implode(', ', array_column($meta['genres'], 'name')) : '',
],
'name' => $hit['name'],
'release_year' => $meta['year'] ?? null,
'category' => $hit['category']['name'] ?? null,
'type' => $hit['type']['name'] ?? null,
'resolution' => $hit['resolution']['name'] ?? null,
'media_info' => $hit['mediainfo'],
'bd_info' => $hit['bdinfo'],
'description' => $hit['description'],
'info_hash' => $hit['info_hash'],
'size' => $hit['size'],
'num_file' => $hit['num_file'],
'files' => $hit['files'],
'freeleech' => $hit['free'].'%',
'double_upload' => $hit['doubleup'],
'refundable' => $hit['refundable'],
'internal' => $hit['internal'],
'featured' => $hit['featured'],
'personal_release' => $hit['personal_release'],
'uploader' => $hit['anon'] ? 'Anonymous' : $hit['user']['username'],
'seeders' => $hit['seeders'],
'leechers' => $hit['leechers'],
'times_completed' => $hit['times_completed'],
'tmdb_id' => $hit['tmdb'],
'imdb_id' => $hit['imdb'],
'tvdb_id' => $hit['tvdb'],
'mal_id' => $hit['mal'],
'igdb_id' => $hit['igdb'],
'category_id' => $hit['category']['id'] ?? null,
'type_id' => $hit['type']['id'] ?? null,
'resolution_id' => $hit['resolution']['id'] ?? null,
'created_at' => date('Y-m-d\TH:i:s', $hit['created_at']).'.000000Z',
'details_link' => route('torrents.show', ['id' => $hit['id']]),
]
]);
}
/** @phpstan-ignore method.notFound (this method exists at time of writing) */
$torrents = $paginator->setCollection(collect($torrents));
}
return [$torrents, $hasMore];
});
if ($isSqlAllowed) {
return new TorrentsResource($torrents);
}
$page = $request->integer('page') ?: 1;
$perPage = min(100, $request->integer('perPage') ?: 25);
// Auth keys must not be cached
$torrents->through(function ($torrent) {
$torrent['attributes']['download_link'] = route('torrent.download.rsskey', ['id' => $torrent['id'], 'rsskey' => auth('api')->user()->rsskey]);
$torrent['attributes']['magnet_link'] = config('torrent.magnet') ? 'magnet:?dn='.$torrent['attributes']['name'].'&xt=urn:btih:'.$torrent['attributes']['info_hash'].'&as='.route('torrent.download.rsskey', ['id' => $torrent['id'], 'rsskey' => auth('api')->user()->rsskey]).'&tr='.route('announce', ['passkey' => auth('api')->user()->passkey]).'&xl='.$torrent['attributes']['size'] : null;
return $torrent;
});
return response()->json([
'data' => $torrents->items(),
'links' => [
'first' => $request->fullUrlWithoutQuery(['page' => 1]),
'last' => null,
'prev' => $page === 1 ? null : $request->fullUrlWithQuery(['page' => $page - 1]),
'next' => $hasMore ? $request->fullUrlWithQuery(['page' => $page + 1]) : null,
'self' => $request->fullUrl(),
],
'meta' => [
'current_page' => $page,
'per_page' => $perPage,
'from' => ($page - 1) * $perPage + 1,
'to' => ($page - 1) * $perPage + \count($torrents->items()),
]
]);
}
}