SeriesController::index()   F
last analyzed

Complexity

Conditions 31
Paths 3552

Size

Total Lines 160
Code Lines 110

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 110
c 1
b 1
f 0
dl 0
loc 160
rs 0
cc 31
nc 3552
nop 2

How to fix   Long Method    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;
4
5
use App\Models\UserSerie;
6
use App\Models\Video;
7
use Blacklight\Releases;
8
use Illuminate\Http\Request;
9
use Illuminate\Support\Arr;
10
11
class SeriesController extends BasePageController
12
{
13
    /**
14
     * @throws \Exception
15
     */
16
    public function index(Request $request, string $id = '')
17
    {
18
        $releases = new Releases;
19
20
        if ($id && ctype_digit($id)) {
21
            $category = -1;
22
            if ($request->has('t') && ctype_digit($request->input('t'))) {
23
                $category = $request->input('t');
24
            }
25
26
            $catarray = [];
27
            $catarray[] = $category;
28
29
            $page = $request->has('page') && is_numeric($request->input('page')) ? $request->input('page') : 1;
30
            $offset = ($page - 1) * config('nntmux.items_per_page');
31
32
            $rel = $releases->tvSearch(['id' => $id], '', '', '', $offset, 1000, '', $catarray, -1);
33
34
            $show = Video::getByVideoID($id);
35
36
            $nodata = '';
37
            $seasons = [];
38
            $myshows = null;
39
            $seriestitles = '';
40
            $seriessummary = '';
41
            $seriescountry = '';
42
43
            if (! $show) {
44
                $nodata = 'No video information for this series.';
45
            } elseif (! $rel) {
46
                $nodata = 'No releases for this series.';
47
            } else {
48
                $myshows = UserSerie::getShow($this->userdata->id, $show['id']);
49
50
                // Sort releases by season, episode, date posted.
51
                $series = $episode = $posted = [];
52
                foreach ($rel as $rlk => $rlv) {
53
                    $series[$rlk] = $rlv->series;
54
                    $episode[$rlk] = $rlv->episode;
55
                    $posted[$rlk] = $rlv->postdate;
56
                }
57
                Arr::sort($series, [[$episode, false], [$posted, false], $rel]);
58
59
                $series = [];
60
                foreach ($rel as $r) {
61
                    $series[$r->series][$r->episode][] = $r;
62
                }
63
64
                $seasons = Arr::sortRecursive($series);
65
66
                // get series name(s), description, country and genre
67
                $seriestitlesArray = $seriessummaryArray = $seriescountryArray = [];
68
                $seriestitlesArray[] = $show['title'];
69
70
                if (! empty($show['summary'])) {
71
                    $seriessummaryArray[] = $show['summary'];
72
                }
73
74
                if (! empty($show['countries_id'])) {
75
                    $seriescountryArray[] = $show['countries_id'];
76
                }
77
78
                $seriestitles = implode('/', array_map('trim', $seriestitlesArray));
79
                $seriessummary = $seriessummaryArray ? array_shift($seriessummaryArray) : '';
80
                $seriescountry = $seriescountryArray ? array_shift($seriescountryArray) : '';
81
            }
82
83
            // Calculate statistics
84
            $episodeCount = 0;
85
            $seasonCount = count($seasons);
86
            $totalSeasonsAvailable = $seasonCount;
87
88
            // Get first and last aired dates from TV episodes
89
            $firstEpisodeAired = null;
90
            $lastEpisodeAired = null;
91
            $totalSeasonsAired = 0;
92
            $totalEpisodesAired = 0;
93
94
            if (! empty($show['id'])) {
95
                $episodeStats = \App\Models\TvEpisode::query()
96
                    ->where('videos_id', $show['id'])
97
                    ->whereNotNull('firstaired')
98
                    ->where('firstaired', '!=', '')
99
                    ->selectRaw('MIN(firstaired) as first_aired, MAX(firstaired) as last_aired, COUNT(DISTINCT series) as total_seasons, COUNT(*) as total_episodes')
100
                    ->first();
101
102
                if ($episodeStats) {
103
                    if (! empty($episodeStats->first_aired) && $episodeStats->first_aired != '0000-00-00') {
0 ignored issues
show
Bug introduced by
The property first_aired does not exist on App\Models\TvEpisode. Did you mean firstaired?
Loading history...
104
                        $firstEpisodeAired = \Carbon\Carbon::parse($episodeStats->first_aired);
105
                    }
106
                    if (! empty($episodeStats->last_aired) && $episodeStats->last_aired != '0000-00-00') {
0 ignored issues
show
Bug introduced by
The property last_aired does not seem to exist on App\Models\TvEpisode. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
107
                        $lastEpisodeAired = \Carbon\Carbon::parse($episodeStats->last_aired);
108
                    }
109
                    $totalSeasonsAired = $episodeStats->total_seasons ?? 0;
0 ignored issues
show
Bug introduced by
The property total_seasons does not seem to exist on App\Models\TvEpisode. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
110
                    $totalEpisodesAired = $episodeStats->total_episodes ?? 0;
0 ignored issues
show
Bug introduced by
The property total_episodes does not exist on App\Models\TvEpisode. Did you mean episode?
Loading history...
111
                }
112
            }
113
114
            foreach ($seasons as $seasonNum => $episodes) {
115
                $episodeCount += count($episodes);
116
            }
117
118
            $catid = $category !== -1 ? $category : '';
119
120
            $this->viewData = array_merge($this->viewData, [
121
                'seasons' => $seasons,
122
                'show' => $show,
123
                'myshows' => $myshows,
124
                'seriestitles' => $seriestitles,
125
                'seriessummary' => $seriessummary,
126
                'seriescountry' => $seriescountry,
127
                'category' => $catid,
128
                'nodata' => $nodata,
129
                'episodeCount' => $episodeCount,
130
                'seasonCount' => $seasonCount,
131
                'firstEpisodeAired' => $firstEpisodeAired,
132
                'lastEpisodeAired' => $lastEpisodeAired,
133
                'totalSeasonsAvailable' => $totalSeasonsAvailable,
134
                'totalSeasonsAired' => $totalSeasonsAired,
135
                'totalEpisodesAired' => $totalEpisodesAired,
136
                'meta_title' => 'View TV Series',
137
                'meta_keywords' => 'view,series,tv,show,description,details',
138
                'meta_description' => 'View TV Series',
139
            ]);
140
141
            return view('series.viewseries', $this->viewData);
142
        } else {
143
            $letter = ($id && preg_match('/^(0\-9|[A-Z])$/i', $id)) ? $id : '0-9';
144
145
            $showname = ($request->has('title') && ! empty($request->input('title'))) ? $request->input('title') : '';
146
147
            if ($showname !== '' && ! $id) {
148
                $letter = '';
149
            }
150
151
            $masterserieslist = Video::getSeriesList($this->userdata->id, $letter, $showname);
152
153
            $serieslist = [];
154
            foreach ($masterserieslist as $s) {
155
                if (preg_match('/^[0-9]/', $s['title'])) {
156
                    $thisrange = '0-9';
157
                } else {
158
                    preg_match('/([A-Z]).*/i', $s['title'], $hits);
159
                    $thisrange = strtoupper($hits[1]);
160
                }
161
                $serieslist[$thisrange][] = $s;
162
            }
163
            ksort($serieslist);
164
165
            $this->viewData = array_merge($this->viewData, [
166
                'serieslist' => $serieslist,
167
                'seriesrange' => range('A', 'Z'),
168
                'seriesletter' => $letter,
169
                'showname' => $showname,
170
                'meta_title' => 'View Series List',
171
                'meta_keywords' => 'view,series,tv,show,description,details',
172
                'meta_description' => 'View Series List',
173
            ]);
174
175
            return view('series.viewserieslist', $this->viewData);
176
        }
177
    }
178
179
    /**
180
     * Show trending TV shows (top 15 most downloaded in last 48 hours)
181
     *
182
     * @throws \Exception
183
     */
184
    public function showTrending(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

184
    public function showTrending(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
185
    {
186
        // Cache key for trending TV shows (48 hours)
187
        $cacheKey = 'trending_tv_top_15_48h';
188
189
        // Get trending TV shows from cache or calculate (refresh every hour)
190
        $trendingShows = \Illuminate\Support\Facades\Cache::remember($cacheKey, 3600, function () {
191
            // Calculate timestamp for 48 hours ago
192
            $fortyEightHoursAgo = \Illuminate\Support\Carbon::now()->subHours(48);
193
194
            // Get TV shows with their download counts from last 48 hours
195
            // Join with user_downloads to get actual download timestamps
196
            $query = \Illuminate\Support\Facades\DB::table('videos as v')
197
                ->join('tv_info as ti', 'v.id', '=', 'ti.videos_id')
198
                ->join('releases as r', 'v.id', '=', 'r.videos_id')
199
                ->leftJoin('user_downloads as ud', 'r.id', '=', 'ud.releases_id')
200
                ->select([
201
                    'v.id',
202
                    'v.title',
203
                    'v.started',
204
                    'v.tvdb',
205
                    'v.tvmaze',
206
                    'v.trakt',
207
                    'v.tmdb',
208
                    'v.countries_id',
209
                    'ti.summary',
210
                    'ti.image',
211
                    \Illuminate\Support\Facades\DB::raw('COUNT(DISTINCT ud.id) as total_downloads'),
212
                    \Illuminate\Support\Facades\DB::raw('COUNT(DISTINCT r.id) as release_count'),
213
                ])
214
                ->where('v.type', 0) // 0 = TV
215
                ->where('v.title', '!=', '')
216
                ->where('ud.timestamp', '>=', $fortyEightHoursAgo)
217
                ->groupBy('v.id', 'v.title', 'v.started', 'v.tvdb', 'v.tvmaze', 'v.trakt', 'v.tmdb', 'v.countries_id', 'ti.summary', 'ti.image')
218
                ->havingRaw('COUNT(DISTINCT ud.id) > 0')
219
                ->orderByDesc('total_downloads')
0 ignored issues
show
Bug introduced by
'total_downloads' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderByDesc(). ( Ignorable by Annotation )

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

219
                ->orderByDesc(/** @scrutinizer ignore-type */ 'total_downloads')
Loading history...
220
                ->limit(15)
221
                ->get();
222
223
            return $query;
224
        });
225
226
        $this->viewData = array_merge($this->viewData, [
227
            'trendingShows' => $trendingShows,
228
            'meta_title' => 'Trending TV Shows - Last 48 Hours',
229
            'meta_keywords' => 'trending,tv,shows,series,popular,downloads,recent',
230
            'meta_description' => 'Browse the most popular and downloaded TV shows in the last 48 hours',
231
        ]);
232
233
        return view('series.trending', $this->viewData);
234
    }
235
}
236