ApiV2Controller::movie()   F
last analyzed

Complexity

Conditions 14
Paths 1025

Size

Total Lines 47
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 37
c 1
b 0
f 0
dl 0
loc 47
rs 2.1
cc 14
nc 1025
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers\Api;
4
5
use App\Events\UserAccessedApi;
6
use App\Http\Controllers\BasePageController;
7
use App\Models\Category;
8
use App\Models\Release;
9
use App\Models\Settings;
10
use App\Models\User;
11
use App\Models\UserDownload;
12
use App\Models\UserRequest;
13
use App\Transformers\ApiTransformer;
14
use App\Transformers\CategoryTransformer;
15
use App\Transformers\DetailsTransformer;
16
use Blacklight\Releases;
17
use Illuminate\Http\JsonResponse;
18
use Illuminate\Http\RedirectResponse;
19
use Illuminate\Http\Request;
20
use Illuminate\Support\Carbon;
21
22
class ApiV2Controller extends BasePageController
23
{
24
    private ApiController $api;
25
26
    public function __construct()
27
    {
28
        $this->api = new ApiController;
29
    }
30
31
    public function capabilities(): JsonResponse
32
    {
33
        $category = Category::getForApi();
34
35
        $capabilities = [
36
            'server' => [
37
                'title' => config('app.name'),
38
                'strapline' => Settings::settingValue('strapline'),
39
                'email' => config('mail.from.address'),
40
                'url' => url('/'),
41
            ],
42
            'limits' => [
43
                'max' => 100,
44
                'default' => 100,
45
            ],
46
            'registration' => [
47
                'available' => 'no',
48
                'open' => (int) Settings::settingValue('registerstatus') === 0 ? 'yes' : 'no',
49
            ],
50
            'searching' => [
51
                'search' => ['available' => 'yes', 'supportedParams' => 'id'],
52
                'tv-search' => ['available' => 'yes', 'supportedParams' => 'id,vid,tvdbid,traktid,rid,tvmazeid,imdbid,tmdbid,season,ep'],
53
                'movie-search' => ['available' => 'yes', 'supportedParams' => 'id, imdbid, tmdbid, traktid'],
54
                'audio-search' => ['available' => 'no',  'supportedParams' => ''],
55
            ],
56
            'categories' => fractal($category, new CategoryTransformer),
57
        ];
58
59
        return response()->json($capabilities);
60
    }
61
62
    /**
63
     * @throws \Throwable
64
     */
65
    public function movie(Request $request): JsonResponse
66
    {
67
        if ($request->missing('api_token') || ($request->has('api_token') && $request->isNotFilled('api_token'))) {
68
            return response()->json(['error' => 'Missing parameter (apikey)'], 403);
69
        }
70
        $releases = new Releases;
71
        $user = User::query()->where('api_token', $request->input('api_token'))->first();
72
        $minSize = $request->has('minsize') && $request->input('minsize') > 0 ? $request->input('minsize') : 0;
73
        $maxAge = $this->api->maxAge($request);
74
        $catExclusions = User::getCategoryExclusionForApi($request);
75
        UserRequest::addApiRequest($request->input('api_token'), $request->getRequestUri());
76
        event(new UserAccessedApi($user));
77
78
        $imdbId = $request->has('imdbid') && $request->filled('imdbid') ? $request->input('imdbid') : -1;
79
        $tmdbId = $request->has('tmdbid') && $request->filled('tmdbid') ? $request->input('tmdbid') : -1;
80
        $traktId = $request->has('traktid') && $request->filled('traktid') ? $request->input('traktid') : -1;
81
82
        $relData = $releases->moviesSearch(
83
            $imdbId,
84
            $tmdbId,
85
            $traktId,
86
            $this->api->offset($request),
87
            $this->api->limit($request),
88
            $request->input('id') ?? '',
89
            $this->api->categoryID($request),
90
            $maxAge,
0 ignored issues
show
Bug introduced by
It seems like $maxAge can also be of type Illuminate\Http\Response; however, parameter $maxAge of Blacklight\Releases::moviesSearch() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

90
            /** @scrutinizer ignore-type */ $maxAge,
Loading history...
91
            $minSize,
92
            $catExclusions
93
        );
94
95
        $time = UserRequest::whereUsersId($user->id)->min('timestamp');
96
        $apiOldestTime = $time !== null ? Carbon::createFromTimeString($time)->toRfc2822String() : '';
97
        $grabTime = UserDownload::whereUsersId($user->id)->min('timestamp');
98
        $oldestGrabTime = $grabTime !== null ? Carbon::createFromTimeString($grabTime)->toRfc2822String() : '';
99
100
        $response = [
101
            'Total' => $relData[0]->_totalrows ?? 0,
102
            'apiCurrent' => UserRequest::getApiRequests($user->id),
103
            'apiMax' => $user->role->apirequests,
0 ignored issues
show
Bug introduced by
The property apirequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
104
            'grabCurrent' => UserDownload::getDownloadRequests($user->id),
105
            'grabMax' => $user->role->downloadrequests,
0 ignored issues
show
Bug introduced by
The property downloadrequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
106
            'apiOldestTime' => $apiOldestTime,
107
            'grabOldestTime' => $oldestGrabTime,
108
            'Results' => fractal($relData, new ApiTransformer($user)),
109
        ];
110
111
        return response()->json($response);
112
    }
113
114
    /**
115
     * @throws \Exception
116
     * @throws \Throwable
117
     */
118
    public function apiSearch(Request $request): JsonResponse
119
    {
120
        if ($request->missing('api_token') || $request->isNotFilled('api_token')) {
121
            return response()->json(['error' => 'Missing parameter (api_token)'], 403);
122
        }
123
        $releases = new Releases;
124
        $user = User::query()->where('api_token', $request->input('api_token'))->first();
125
        $offset = $this->api->offset($request);
126
        $catExclusions = User::getCategoryExclusionForApi($request);
127
        $minSize = $request->has('minsize') && $request->input('minsize') > 0 ? $request->input('minsize') : 0;
128
        $maxAge = $this->api->maxAge($request);
129
        $groupName = $this->api->group($request);
130
        UserRequest::addApiRequest($request->input('api_token'), $request->getRequestUri());
131
        event(new UserAccessedApi($user));
132
        $categoryID = $this->api->categoryID($request);
133
        $limit = $this->api->limit($request);
134
135
        if ($request->has('id')) {
136
            $relData = $releases->apiSearch(
137
                $request->input('id'),
138
                $groupName,
139
                $offset,
140
                $limit,
141
                $maxAge,
0 ignored issues
show
Bug introduced by
It seems like $maxAge can also be of type Illuminate\Http\Response; however, parameter $maxAge of Blacklight\Releases::apiSearch() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

141
                /** @scrutinizer ignore-type */ $maxAge,
Loading history...
142
                $catExclusions,
143
                $categoryID,
144
                $minSize
145
            );
146
        } else {
147
            $relData = $releases->getBrowseRange(
148
                1,
149
                $categoryID,
150
                $offset,
151
                $limit,
152
                '',
153
                $maxAge,
0 ignored issues
show
Bug introduced by
It seems like $maxAge can also be of type Illuminate\Http\Response; however, parameter $maxAge of Blacklight\Releases::getBrowseRange() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

153
                /** @scrutinizer ignore-type */ $maxAge,
Loading history...
154
                $catExclusions,
155
                $groupName,
156
                $minSize
157
            );
158
        }
159
160
        $time = UserRequest::whereUsersId($user->id)->min('timestamp');
161
        $apiOldestTime = $time !== null ? Carbon::createFromTimeString($time)->toRfc2822String() : '';
162
        $grabTime = UserDownload::whereUsersId($user->id)->min('timestamp');
163
        $oldestGrabTime = $grabTime !== null ? Carbon::createFromTimeString($grabTime)->toRfc2822String() : '';
164
165
        $response = [
166
            'Total' => $relData[0]->_totalrows ?? 0,
167
            'apiCurrent' => UserRequest::getApiRequests($user->id),
168
            'apiMax' => $user->role->apirequests,
0 ignored issues
show
Bug introduced by
The property apirequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
169
            'grabCurrent' => UserDownload::getDownloadRequests($user->id),
170
            'grabMax' => $user->role->downloadrequests,
0 ignored issues
show
Bug introduced by
The property downloadrequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
171
            'apiOldestTime' => $apiOldestTime,
172
            'grabOldestTime' => $oldestGrabTime,
173
            'Results' => fractal($relData, new ApiTransformer($user)),
174
        ];
175
176
        return response()->json($response);
177
    }
178
179
    /**
180
     * @throws \Exception
181
     * @throws \Throwable
182
     */
183
    public function tv(Request $request): JsonResponse
184
    {
185
        if ($request->missing('api_token') || $request->isNotFilled('api_token')) {
186
            return response()->json(['error' => 'Missing parameter (api_token)'], 403);
187
        }
188
        $releases = new Releases;
189
        $user = User::query()->where('api_token', $request->input('api_token'))->first();
190
        if ($user === null) {
191
            return response()->json(['error' => 'Invalid API Token'], 403);
192
        }
193
        $catExclusions = User::getCategoryExclusionForApi($request);
194
        $minSize = $request->has('minsize') && $request->input('minsize') > 0 ? $request->input('minsize') : 0;
195
        $this->api->verifyEmptyParameter($request, 'id');
196
        $this->api->verifyEmptyParameter($request, 'vid');
197
        $this->api->verifyEmptyParameter($request, 'tvdbid');
198
        $this->api->verifyEmptyParameter($request, 'traktid');
199
        $this->api->verifyEmptyParameter($request, 'rid');
200
        $this->api->verifyEmptyParameter($request, 'tvmazeid');
201
        $this->api->verifyEmptyParameter($request, 'imdbid');
202
        $this->api->verifyEmptyParameter($request, 'tmdbid');
203
        $this->api->verifyEmptyParameter($request, 'season');
204
        $this->api->verifyEmptyParameter($request, 'ep');
205
        $maxAge = $this->api->maxAge($request);
206
        UserRequest::addApiRequest($request->input('api_token'), $request->getRequestUri());
207
        event(new UserAccessedApi($user));
208
209
        $siteIdArr = [
210
            'id' => $request->input('vid') ?? null,
211
            'tvdb' => $request->input('tvdbid') ?? null,
212
            'trakt' => $request->input('traktid') ?? null,
213
            'tvrage' => $request->input('rid') ?? null,
214
            'tvmaze' => $request->input('tvmazeid') ?? null,
215
            'imdb' => $request->input('imdbid') ?? null,
216
            'tmdb' => $request->input('tmdbid') ?? null,
217
        ];
218
219
        // Process season only queries or Season and Episode/Airdate queries
220
221
        $series = $request->input('season') ?? '';
222
        $episode = $request->input('ep') ?? '';
223
224
        if (preg_match('#^(19|20)\d{2}$#', $series, $year) && str_contains($episode, '/')) {
225
            $airDate = str_replace('/', '-', $year[0].'-'.$episode);
226
        }
227
228
        $relData = $releases->apiTvSearch(
229
            $siteIdArr,
230
            $series,
231
            $episode,
232
            $airDate ?? '',
233
            $this->api->offset($request),
234
            $this->api->limit($request),
235
            $request->input('id') ?? '',
236
            $this->api->categoryID($request),
237
            $maxAge,
0 ignored issues
show
Bug introduced by
It seems like $maxAge can also be of type Illuminate\Http\Response; however, parameter $maxAge of Blacklight\Releases::apiTvSearch() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

237
            /** @scrutinizer ignore-type */ $maxAge,
Loading history...
238
            $minSize,
239
            $catExclusions
240
        );
241
242
        $time = UserRequest::whereUsersId($user->id)->min('timestamp');
243
        $apiOldestTime = $time !== null ? Carbon::createFromTimeString($time)->toRfc2822String() : '';
244
        $grabTime = UserDownload::whereUsersId($user->id)->min('timestamp');
245
        $oldestGrabTime = $grabTime !== null ? Carbon::createFromTimeString($grabTime)->toRfc2822String() : '';
246
247
        $response = [
248
            'Total' => $relData[0]->_totalrows ?? 0,
249
            'apiCurrent' => UserRequest::getApiRequests($user->id),
250
            'apiMax' => $user->role->apirequests,
0 ignored issues
show
Bug introduced by
The property apirequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
251
            'grabCurrent' => UserDownload::getDownloadRequests($user->id),
252
            'grabMax' => $user->role->downloadrequests,
0 ignored issues
show
Bug introduced by
The property downloadrequests does not seem to exist on Spatie\Permission\Models\Role.
Loading history...
253
            'apiOldestTime' => $apiOldestTime,
254
            'grabOldestTime' => $oldestGrabTime,
255
            'Results' => fractal($relData, new ApiTransformer($user)),
256
        ];
257
258
        return response()->json($response);
259
    }
260
261
    public function getNzb(Request $request): \Illuminate\Foundation\Application|JsonResponse|\Illuminate\Routing\Redirector|RedirectResponse|\Illuminate\Contracts\Foundation\Application
262
    {
263
        if ($request->missing('api_token') || $request->isNotFilled('api_token')) {
264
            return response()->json(['error' => 'Missing parameter (api_token)'], 403);
265
        }
266
        $user = User::query()->where('api_token', $request->input('api_token'))->first();
267
        if ($user === null) {
268
            return response()->json(['error' => 'Invalid API Token'], 403);
269
        }
270
        event(new UserAccessedApi($user));
271
        UserRequest::addApiRequest($request->input('api_token'), $request->getRequestUri());
272
        $relData = Release::checkGuidForApi($request->input('id'));
273
        if ($relData) {
274
            return redirect('/getnzb?r='.$request->input('api_token').'&id='.$request->input('id').(($request->has('del') && $request->input('del') === '1') ? '&del=1' : ''));
275
        }
276
277
        return response()->json(['data' => 'No such item (the guid you provided has no release in our database)'], 404);
278
    }
279
280
    public function details(Request $request): JsonResponse
281
    {
282
        if ($request->missing('api_token') || $request->isNotFilled('api_token')) {
283
            return response()->json(['error' => 'Missing parameter (api_token)'], 403);
284
        }
285
        if ($request->missing('id')) {
286
            return response()->json(['error' => 'Missing parameter (guid is required for single release details)'], 400);
287
        }
288
289
        UserRequest::addApiRequest($request->input('api_token'), $request->getRequestUri());
290
        $user = User::query()->where('api_token', $request->input('api_token'))->first();
291
        if ($user === null) {
292
            return response()->json(['error' => 'Invalid API Token'], 403);
293
        }
294
        event(new UserAccessedApi($user));
295
        $relData = Release::getByGuid($request->input('id'));
296
297
        $relData = fractal($relData, new DetailsTransformer($user));
298
299
        return response()->json($relData);
300
    }
301
}
302