Passed
Pull Request — master (#1628)
by Darko
10:58 queued 04:02
created

Tmux::getMonitorSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 58
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 53
dl 0
loc 58
rs 9.0254
c 0
b 0
f 0
cc 1
nc 1
nop 0

How to fix   Long Method   

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 Blacklight;
4
5
use App\Models\Category;
6
use App\Models\Settings;
7
use Illuminate\Support\Carbon;
8
use Illuminate\Support\Facades\DB;
9
10
/**
11
 * Class Tmux.
12
 */
13
class Tmux
14
{
15
    /**
16
     * @var \PDO
17
     */
18
    public \Closure|\PDO $pdo;
19
20
    public $tmux_session;
21
22
    protected ColorCLI $colorCli;
23
24
    /**
25
     * Tmux constructor.
26
     */
27
    public function __construct()
28
    {
29
        $this->pdo = DB::connection()->getPdo();
30
        $this->colorCli = new ColorCLI;
31
    }
32
33
    /**
34
     * @return mixed
35
     */
36
    public function getConnectionsInfo($constants)
37
    {
38
        $runVar['connections']['port_a'] = $runVar['connections']['host_a'] = $runVar['connections']['ip_a'] = false;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$runVar was never initialized. Although not strictly required by PHP, it is generally a good practice to add $runVar = array(); before regardless.
Loading history...
39
        $runVar['connections']['port'] = config('nntmux_nntp.port');
40
        $runVar['connections']['host'] = config('nntmux_nntp.server');
41
        $runVar['connections']['ip'] = gethostbyname($runVar['connections']['host']);
42
        if ($constants['alternate_nntp'] === '1') {
43
            $runVar['connections']['port_a'] = config('nntmux_nntp.alternate_server_port');
44
            $runVar['connections']['host_a'] = config('nntmux_nntp.alternate_server');
45
            $runVar['connections']['ip_a'] = gethostbyname($runVar['connections']['host_a']);
46
        }
47
48
        return $runVar['connections'];
49
    }
50
51
    public function getUSPConnections(string $which, $connections): mixed
52
    {
53
        switch ($which) {
54
            case 'alternate':
55
                $ip = 'ip_a';
56
                $port = 'port_a';
57
                break;
58
            case 'primary':
59
            default:
60
                $ip = 'ip';
61
                $port = 'port';
62
                break;
63
        }
64
65
        $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].':'.$connections[$port].' | grep -c ESTAB'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
$runVar was never initialized. Although not strictly required by PHP, it is generally a good practice to add $runVar = array(); before regardless.
Loading history...
66
        $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip].':'.$connections[$port]));
67
68
        if ((int) $runVar['conncounts'][$which]['active'] === 0 && (int) $runVar['conncounts'][$which]['total'] === 0) {
69
            $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].':https | grep -c ESTAB'));
70
            $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip].':https'));
71
        }
72
        if ((int) $runVar['conncounts'][$which]['active'] === 0 && (int) $runVar['conncounts'][$which]['total'] === 0) {
73
            $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$port].' | grep -c ESTAB'));
74
            $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$port]));
75
        }
76
        if ((int) $runVar['conncounts'][$which]['active'] === 0 && (int) $runVar['conncounts'][$which]['total'] === 0) {
77
            $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].' | grep -c ESTAB'));
78
            $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip]));
79
        }
80
81
        return $runVar['conncounts'];
82
    }
83
84
    public function getListOfPanes($constants): array
85
    {
86
        $panes = ['zero' => '', 'one' => '', 'two' => ''];
87
        switch ($constants['sequential']) {
88
            case 0:
89
            case 1:
90
                $panes_win_1 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:0 -F '#{pane_title}'`");
91
                $panes['zero'] = str_replace("\n", '', explode(' ', $panes_win_1));
92
                $panes_win_2 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:1 -F '#{pane_title}'`");
93
                $panes['one'] = str_replace("\n", '', explode(' ', $panes_win_2));
94
                $panes_win_3 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:2 -F '#{pane_title}'`");
95
                $panes['two'] = str_replace("\n", '', explode(' ', $panes_win_3));
96
                break;
97
            case 2:
98
                $panes_win_1 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:0 -F '#{pane_title}'`");
99
                $panes['zero'] = str_replace("\n", '', explode(' ', $panes_win_1));
100
                $panes_win_2 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:1 -F '#{pane_title}'`");
101
                $panes['one'] = str_replace("\n", '', explode(' ', $panes_win_2));
102
                break;
103
        }
104
105
        return $panes;
106
    }
107
108
    public function getConstantSettings(): string
109
    {
110
        $settstr = 'SELECT value FROM settings WHERE setting =';
111
112
        $sql = sprintf(
113
            "SELECT
114
					(%1\$s 'sequential') AS sequential,
115
					(%1\$s 'tmux_session') AS tmux_session,
116
					(%1\$s 'run_ircscraper') AS run_ircscraper,
117
					(%1\$s 'alternate_nntp') AS alternate_nntp,
118
					(%1\$s 'delaytime') AS delaytime",
119
            $settstr
120
        );
121
122
        return $sql;
123
    }
124
125
    public function getMonitorSettings(): string
126
    {
127
        $settstr = 'SELECT value FROM settings WHERE name =';
128
129
        $sql = sprintf(
130
            "SELECT
131
					(%1\$s 'monitor_delay') AS monitor,
132
					(%1\$s 'binaries') AS binaries_run,
133
					(%1\$s 'backfill') AS backfill,
134
					(%1\$s 'backfill_qty') AS backfill_qty,
135
					(%1\$s 'nzbs') AS nzbs,
136
					(%1\$s 'post') AS post,
137
					(%1\$s 'releases') AS releases_run,
138
					(%1\$s 'fix_names') AS fix_names,
139
					(%1\$s 'seq_timer') AS seq_timer,
140
					(%1\$s 'bins_timer') AS bins_timer,
141
					(%1\$s 'back_timer') AS back_timer,
142
					(%1\$s 'rel_timer') AS rel_timer,
143
					(%1\$s 'fix_timer') AS fix_timer,
144
					(%1\$s 'post_timer') AS post_timer,
145
					(%1\$s 'collections_kill') AS collections_kill,
146
					(%1\$s 'postprocess_kill') AS postprocess_kill,
147
					(%1\$s 'crap_timer') AS crap_timer,
148
					(%1\$s 'fix_crap') AS fix_crap,
149
					(%1\$s 'fix_crap_opt') AS fix_crap_opt,
150
					(%1\$s 'post_kill_timer') AS post_kill_timer,
151
					(%1\$s 'monitor_path') AS monitor_path,
152
					(%1\$s 'monitor_path_a') AS monitor_path_a,
153
					(%1\$s 'monitor_path_b') AS monitor_path_b,
154
					(%1\$s 'progressive') AS progressive,
155
					(%1\$s 'dehash') AS dehash,
156
					(%1\$s 'dehash_timer') AS dehash_timer,
157
					(%1\$s 'backfill_days') AS backfilldays,
158
					(%1\$s 'post_amazon') AS post_amazon,
159
					(%1\$s 'post_timer_amazon') AS post_timer_amazon,
160
					(%1\$s 'post_non') AS post_non,
161
					(%1\$s 'post_timer_non') AS post_timer_non,
162
					(%1\$s 'colors_start') AS colors_start,
163
					(%1\$s 'colors_end') AS colors_end,
164
					(%1\$s 'colors_exc') AS colors_exc,
165
					(%1\$s 'showquery') AS show_query,
166
					(%1\$s 'running') AS is_running,
167
					(%1\$s 'lookupbooks') AS processbooks,
168
					(%1\$s 'lookupmusic') AS processmusic,
169
					(%1\$s 'lookupgames') AS processgames,
170
					(%1\$s 'lookupxxx') AS processxxx,
171
					(%1\$s 'lookupimdb') AS processmovies,
172
					(%1\$s 'lookuptv') AS processtvrage,
173
					(%1\$s 'lookupanidb') AS processanime,
174
					(%1\$s 'lookupnfo') AS processnfo,
175
					(%1\$s 'lookuppar2') AS processpar2,
176
					(%1\$s 'nzbthreads') AS nzbthreads,
177
					(%1\$s 'maxsizetopostprocess') AS maxsize_pp,
178
					(%1\$s 'minsizetopostprocess') AS minsize_pp",
179
            $settstr
180
        );
181
182
        return $sql;
183
    }
184
185
    public function updateItem($setting, $value): int
186
    {
187
        return Settings::query()->where('setting', '=', $setting)->update(['value' => $value]);
188
    }
189
190
    public function microtime_float(): float
191
    {
192
        [$usec, $sec] = explode(' ', microtime());
193
194
        return (float) $usec + (float) $sec;
195
    }
196
197
    public function decodeSize(float $bytes): string
198
    {
199
        $types = ['B', 'KB', 'MB', 'GB', 'TB'];
200
        $suffix = 'B';
201
        foreach ($types as $type) {
202
            if ($bytes < 1024.0) {
203
                $suffix = $type;
204
                break;
205
            }
206
            $bytes /= 1024;
207
        }
208
209
        return round($bytes, 2).' '.$suffix;
210
    }
211
212
    public function writelog($pane): ?string
213
    {
214
        $path = storage_path('logs');
215
        $getDate = now()->format('Y_m_d');
216
        $logs = Settings::settingValue('write_logs') ?? 0;
217
        if ($logs === 1) {
218
            return "2>&1 | tee -a $path/$pane-$getDate.log";
219
        }
220
221
        return '';
222
    }
223
224
    /**
225
     * @throws \Exception
226
     */
227
    public function get_color($colors_start, $colors_end, $colors_exc): int
228
    {
229
        $exception = str_replace('.', '.', $colors_exc);
230
        $exceptions = explode(',', $exception);
231
        sort($exceptions);
232
        $number = random_int($colors_start, $colors_end - \count($exceptions));
233
        foreach ($exceptions as $exception) {
234
            if ($number >= $exception) {
235
                $number++;
236
            } else {
237
                break;
238
            }
239
        }
240
241
        return $number;
242
    }
243
244
    /**
245
     * Returns random bool, weighted by $chance.
246
     *
247
     *
248
     *
249
     * @throws \Exception
250
     */
251
    public function rand_bool($loop, int $chance = 60): bool
252
    {
253
        $usecache = Settings::settingValue('usecache') ?? 0;
254
        if ($loop === 1 || $usecache === 0) {
255
            return false;
256
        }
257
258
        return random_int(1, 100) <= $chance;
259
    }
260
261
    public function relativeTime($_time): string
262
    {
263
        return Carbon::createFromTimestamp($_time, date_default_timezone_get())->ago();
264
    }
265
266
    public function command_exist($cmd): bool
267
    {
268
        $returnVal = shell_exec("which $cmd 2>/dev/null");
269
270
        return ! empty($returnVal);
271
    }
272
273
    /**
274
     * @throws \Exception
275
     */
276
    public function proc_query($qry, $bookreqids, string $db_name, string $ppmax = '', string $ppmin = ''): bool|string
277
    {
278
        switch ((int) $qry) {
279
            case 1:
280
                return sprintf(
281
                    '
282
					SELECT
283
					SUM(IF(nzbstatus = %d AND categories_id BETWEEN %d AND %d AND categories_id != %d AND videos_id = 0 AND tv_episodes_id BETWEEN -3 AND 0 AND size > 1048576,1,0)) AS processtv,
284
					SUM(IF(nzbstatus = %1$d AND categories_id = %d AND anidbid IS NULL,1,0)) AS processanime,
285
					SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND imdbid IS NULL,1,0)) AS processmovies,
286
					SUM(IF(nzbstatus = %1$d AND categories_id IN (%d, %d, %d) AND musicinfo_id IS NULL,1,0)) AS processmusic,
287
					SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND consoleinfo_id IS NULL,1,0)) AS processconsole,
288
					SUM(IF(nzbstatus = %1$d AND categories_id IN (%s) AND bookinfo_id IS NULL,1,0)) AS processbooks,
289
					SUM(IF(nzbstatus = %1$d AND categories_id = %d AND gamesinfo_id = 0,1,0)) AS processgames,
290
					SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND xxxinfo_id = 0,1,0)) AS processxxx,
291
					SUM(IF(1=1 %s,1,0)) AS processnfo,
292
					SUM(IF(nzbstatus = %1$d AND isrenamed = %d AND predb_id = 0 AND passwordstatus >= 0 AND nfostatus > %d
293
						AND ((nfostatus = %d AND proc_nfo = %d) OR proc_files = %d OR proc_par2 = %d
294
							OR (ishashed = 1 AND dehashstatus BETWEEN -6 AND 0)) AND categories_id IN (%s),1,0)) AS processrenames,
295
					SUM(IF(isrenamed = %d,1,0)) AS renamed,
296
					SUM(IF(nzbstatus = %1$d AND nfostatus = %20$d,1,0)) AS nfo,
297
					SUM(IF(predb_id > 0,1,0)) AS predb_matched,
298
					COUNT(DISTINCT(predb_id)) AS distinct_predb_matched
299
					FROM releases r',
300
                    NZB::NZB_ADDED,
301
                    Category::TV_ROOT,
302
                    Category::TV_OTHER,
303
                    Category::TV_ANIME,
304
                    Category::TV_ANIME,
305
                    Category::MOVIE_ROOT,
306
                    Category::MOVIE_OTHER,
307
                    Category::MUSIC_MP3,
308
                    Category::MUSIC_LOSSLESS,
309
                    Category::MUSIC_OTHER,
310
                    Category::GAME_ROOT,
311
                    Category::GAME_OTHER,
312
                    $bookreqids,
313
                    Category::PC_GAMES,
314
                    Category::XXX_ROOT,
315
                    Category::XXX_X264,
316
                    Nfo::NfoQueryString(),
317
                    NameFixer::IS_RENAMED_NONE,
318
                    Nfo::NFO_UNPROC,
319
                    Nfo::NFO_FOUND,
320
                    NameFixer::PROC_NFO_NONE,
321
                    NameFixer::PROC_FILES_NONE,
322
                    NameFixer::PROC_PAR2_NONE,
323
                    Category::getCategoryOthersGroup(),
324
                    NameFixer::IS_RENAMED_DONE
325
                );
326
327
            case 2:
328
                $ppminString = $ppmaxString = '';
329
                if (is_numeric($ppmax) && ! empty($ppmax)) {
330
                    $ppmax *= 1073741824;
331
                    $ppmaxString = "AND r.size < {$ppmax}";
332
                }
333
                if (is_numeric($ppmin) && ! empty($ppmin)) {
334
                    $ppmin *= 1048576;
335
                    $ppminString = "AND r.size > {$ppmin}";
336
                }
337
338
                return "SELECT
339
					(SELECT COUNT(r.id) FROM releases r
340
						LEFT JOIN categories c ON c.id = r.categories_id
341
						WHERE r.nzbstatus = 1
342
						AND r.passwordstatus = -1
343
						AND r.haspreview = -1
344
						{$ppminString}
345
						{$ppmaxString}
346
						AND c.disablepreview = 0
347
					) AS work,
348
					(SELECT COUNT(id) FROM usenet_groups WHERE active = 1) AS active_groups,
349
					(SELECT COUNT(id) FROM usenet_groups WHERE name IS NOT NULL) AS all_groups";
350
351
            case 4:
352
                return sprintf(
353
                    "
354
					SELECT
355
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'predb' AND TABLE_SCHEMA = %1\$s) AS predb,
356
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'missed_parts' AND TABLE_SCHEMA = %1\$s) AS missed_parts_table,
357
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'parts' AND TABLE_SCHEMA = %1\$s) AS parts_table,
358
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'binaries' AND TABLE_SCHEMA = %1\$s) AS binaries_table,
359
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'collections' AND TABLE_SCHEMA = %1\$s) AS collections_table,
360
					(SELECT TABLE_ROWS FROM information_schema.TABLES WHERE table_name = 'releases' AND TABLE_SCHEMA = %1\$s) AS releases,
361
					(SELECT COUNT(id) FROM usenet_groups WHERE first_record IS NOT NULL AND backfill = 1
362
						AND (now() - INTERVAL backfill_target DAY) < first_record_postdate
363
					) AS backfill_groups_days,
364
					(SELECT COUNT(id) FROM usenet_groups WHERE first_record IS NOT NULL AND backfill = 1 AND (now() - INTERVAL datediff(curdate(),
365
					(SELECT VALUE FROM settings WHERE setting = 'safebackfilldate')) DAY) < first_record_postdate) AS backfill_groups_date",
366
                    escapeString($db_name)
367
                );
368
            case 6:
369
                return 'SELECT
370
					(SELECT searchname FROM releases ORDER BY id DESC LIMIT 1) AS newestrelname,
371
					(SELECT UNIX_TIMESTAMP(MIN(dateadded)) FROM collections) AS oldestcollection,
372
					(SELECT UNIX_TIMESTAMP(MAX(predate)) FROM predb) AS newestpre,
373
					(SELECT UNIX_TIMESTAMP(adddate) FROM releases ORDER BY id DESC LIMIT 1) AS newestrelease';
374
            default:
375
                return false;
376
        }
377
    }
378
379
    /**
380
     * @return bool true if tmux is running, false otherwise.
381
     *
382
     * @throws \RuntimeException
383
     */
384
    public function isRunning(): bool
385
    {
386
        $running = Settings::query()->where(['name' => 'running'])->first(['value']);
387
        if ($running === null) {
388
            throw new \RuntimeException('Tmux\\\'s running flag was not found in the database.'.PHP_EOL.'Please check the tables are correctly setup.'.PHP_EOL);
389
        }
390
391
        return ! ((int) $running->value === 0);
392
    }
393
394
    /**
395
     * @throws \Exception
396
     */
397
    public function stopIfRunning(): bool
398
    {
399
        if ($this->isRunning()) {
400
            Settings::query()->where(['name' => 'running'])->update(['value' => 0]);
401
            $sleep = Settings::settingValue('monitor_delay');
402
            $this->colorCli->header('Stopping tmux scripts and waiting '.$sleep.' seconds for all panes to shutdown');
403
            sleep($sleep);
404
405
            return true;
406
        }
407
        $this->colorCli->info('Tmux scripts are not running!');
408
409
        return false;
410
    }
411
412
    /**
413
     * @throws \RuntimeException
414
     */
415
    public function startRunning(): void
416
    {
417
        if (! $this->isRunning()) {
418
            Settings::query()->where(['section' => 'site', 'subsection' => 'tmux', 'setting' => 'running'])->update(['value' => 1]);
419
        }
420
    }
421
422
    public function cbpmTableQuery(): array
423
    {
424
        return DB::select(
425
            "
426
			SELECT TABLE_NAME AS name
427
      		FROM information_schema.TABLES
428
      		WHERE TABLE_SCHEMA = (SELECT DATABASE())
429
			AND TABLE_NAME REGEXP {escapeString('^(multigroup_)?(collections|binaries|parts|missed_parts)(_[0-9]+)?$')}
430
			ORDER BY TABLE_NAME ASC"
431
        );
432
    }
433
}
434