Completed
Push — dev ( 8486bf...fdc38b )
by Darko
08:23
created

Music::getMusicInfoByName()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 3
nop 2
dl 0
loc 18
ccs 0
cts 13
cp 0
crap 20
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Blacklight;
4
5
use App\Models\Genre;
6
use App\Models\Release;
7
use App\Models\Category;
8
use App\Models\Settings;
9
use App\Models\MusicInfo;
10
use DariusIII\ItunesApi\iTunes;
11
use Illuminate\Support\Facades\DB;
12
use Illuminate\Support\Facades\Cache;
13
use DariusIII\ItunesApi\Exceptions\AlbumNotFoundException;
14
use DariusIII\ItunesApi\Exceptions\TrackNotFoundException;
15
use DariusIII\ItunesApi\Exceptions\ArtistNotFoundException;
16
use DariusIII\ItunesApi\Exceptions\SearchNoResultsException;
17
18
/**
19
 * Class Music.
20
 */
21
class Music
22
{
23
    protected const MATCH_PERCENT = 85;
24
25
    /**
26
     * @var bool
27
     */
28
    public $echooutput;
29
30
    /**
31
     * @var null|string
32
     */
33
    public $pubkey;
34
35
    /**
36
     * @var null|string
37
     */
38
    public $privkey;
39
40
    /**
41
     * @var null|string
42
     */
43
    public $asstag;
44
45
    /**
46
     * @var int
47
     */
48
    public $musicqty;
49
50
    /**
51
     * @var int
52
     */
53
    public $sleeptime;
54
55
    /**
56
     * @var string
57
     */
58
    public $imgSavePath;
59
60
    /**
61
     * @var bool
62
     */
63
    public $renamed;
64
65
    /**
66
     * Store names of failed Amazon lookup items.
67
     * @var array
68
     */
69
    public $failCache;
70
71
    /**
72
     * @var \Blacklight\ColorCLI
73
     */
74
    protected $colorCli;
75
76
    /**
77
     * @param array $options Class instances/ echo to CLI.
78
     * @throws \Exception
79
     */
80
    public function __construct(array $options = [])
81
    {
82
        $defaults = [
83
            'Echo'     => false,
84
            'Settings' => null,
85
        ];
86
        $options += $defaults;
87
88
        $this->echooutput = ($options['Echo'] && config('nntmux.echocli'));
89
90
        $this->colorCli = new ColorCLI();
91
92
        $this->pubkey = Settings::settingValue('APIs..amazonpubkey');
93
        $this->privkey = Settings::settingValue('APIs..amazonprivkey');
94
        $this->asstag = Settings::settingValue('APIs..amazonassociatetag');
95
        $this->musicqty = Settings::settingValue('..maxmusicprocessed') !== '' ? (int) Settings::settingValue('..maxmusicprocessed') : 150;
0 ignored issues
show
introduced by
The condition App\Models\Settings::set...musicprocessed') !== '' is always true.
Loading history...
96
        $this->sleeptime = Settings::settingValue('..amazonsleep') !== '' ? (int) Settings::settingValue('..amazonsleep') : 1000;
0 ignored issues
show
introduced by
The condition App\Models\Settings::set...'..amazonsleep') !== '' is always true.
Loading history...
97
        $this->imgSavePath = NN_COVERS.'music'.DS;
98
        $this->renamed = (int) Settings::settingValue('..lookupmusic') === 2 ? 'AND isrenamed = 1' : '';
0 ignored issues
show
Documentation Bug introduced by
The property $renamed was declared of type boolean, but (int)App\Models\Settings...AND isrenamed = 1' : '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
99
100
        $this->failCache = [];
101
    }
102
103
    /**
104
     * @param $id
105
     * @return \Illuminate\Database\Eloquent\Model|null|static
106
     */
107
    public function getMusicInfo($id)
108
    {
109
        return MusicInfo::query()->with('genre')->where('id', $id)->first();
110
    }
111
112
    /**
113
     * @param $artist
114
     * @param $album
115
     * @return \Illuminate\Database\Eloquent\Model|null|static
116
     */
117
    public function getMusicInfoByName($artist, $album)
0 ignored issues
show
Unused Code introduced by
The parameter $artist 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

117
    public function getMusicInfoByName(/** @scrutinizer ignore-unused */ $artist, $album)

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...
118
    {
119
        //only used to get a count of words
120
        $searchwords = '';
121
        $album = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $album);
122
        $album = preg_replace('/[^\w ]+/', '', $album);
123
        $album = preg_replace('/(WEB|FLAC|CD)/', '', $album);
124
        $album = trim(trim(preg_replace('/\s\s+/i', ' ', $album)));
125
        foreach (explode(' ', $album) as $word) {
126
            $word = trim(rtrim(trim($word), '-'));
127
            if ($word !== '' && $word !== '-') {
128
                $word = '+'.$word;
129
                $searchwords .= sprintf('%s ', $word);
130
            }
131
        }
132
        $searchwords = trim($searchwords);
133
134
        return MusicInfo::search($searchwords)->first();
135
    }
136
137
    /**
138
     * @param $page
139
     * @param       $cat
140
     * @param       $start
141
     * @param       $num
142
     * @param       $orderBy
143
     * @param array $excludedCats
144
     *
145
     * @return array
146
     * @throws \Exception
147
     */
148
    public function getMusicRange($page, $cat, $start, $num, $orderBy, array $excludedCats = [])
149
    {
150
        $browseby = $this->getBrowseBy();
151
        $catsrch = '';
152
        if (\count($cat) > 0 && (int) $cat[0] !== -1) {
153
            $catsrch = Category::getCategorySearch($cat);
154
        }
155
        $exccatlist = '';
156
        if (\count($excludedCats) > 0) {
157
            $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')';
158
        }
159
        $order = $this->getMusicOrder($orderBy);
160
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_medium'));
161
        $musicSql =
162
            sprintf(
163
                "
164
				SELECT SQL_CALC_FOUND_ROWS
165
					m.id,
166
					GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id
167
				FROM musicinfo m
168
				LEFT JOIN releases r ON r.musicinfo_id = m.id
169
				WHERE r.nzbstatus = 1
170
				AND m.title != ''
171
				AND m.cover = 1
172
				AND r.passwordstatus %s
173
				%s %s %s
174
				GROUP BY m.id
175
				ORDER BY %s %s %s",
176
                (new Releases())->showPasswords(),
177
                $browseby,
178
                $catsrch,
179
                $exccatlist,
180
                $order[0],
181
                $order[1],
182
                ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start)
183
            );
184
        $musicCache = Cache::get(md5($musicSql.$page));
185
        if ($musicCache !== null) {
186
            $music = $musicCache;
187
        } else {
188
            $data = DB::select($musicSql);
189
            $music = ['total' => DB::select('SELECT FOUND_ROWS() AS total'), 'result' => $data];
190
            Cache::put(md5($musicSql.$page), $music, $expiresAt);
191
        }
192
        $musicIDs = $releaseIDs = false;
193
        if (\is_array($music['result'])) {
194
            foreach ($music['result'] as $mus => $id) {
195
                $musicIDs[] = $id->id;
196
                $releaseIDs[] = $id->grp_release_id;
197
            }
198
        }
199
        $sql = sprintf(
200
            '
201
			SELECT
202
				r.id, r.rarinnerfilecount, r.grabs, r.comments, r.totalpart, r.size, r.postdate, r.searchname, r.haspreview, r.passwordstatus, r.guid, df.failed AS failed,
203
				m.*,
204
				r.musicinfo_id, r.haspreview,
205
				g.name AS group_name,
206
				rn.releases_id AS nfoid
207
			FROM releases r
208
			LEFT OUTER JOIN groups g ON g.id = r.groups_id
209
			LEFT OUTER JOIN release_nfos rn ON rn.releases_id = r.id
210
			LEFT OUTER JOIN dnzb_failures df ON df.release_id = r.id
211
			INNER JOIN musicinfo m ON m.id = r.musicinfo_id
212
			WHERE m.id IN (%s)
213
			AND r.id IN (%s)
214
			%s
215
			GROUP BY m.id
216
			ORDER BY %s %s',
217
            (\is_array($musicIDs) ? implode(',', $musicIDs) : -1),
0 ignored issues
show
introduced by
The condition is_array($musicIDs) is always false.
Loading history...
218
            (\is_array($releaseIDs) ? implode(',', $releaseIDs) : -1),
0 ignored issues
show
introduced by
The condition is_array($releaseIDs) is always false.
Loading history...
219
            $catsrch,
220
            $order[0],
221
            $order[1]
222
        );
223
        $return = Cache::get(md5($sql.$page));
224
        if ($return !== null) {
225
            return $return;
226
        }
227
        $return = DB::select($sql);
228
        if (! empty($return)) {
229
            $return[0]->_totalcount = $music['total'][0]->total ?? 0;
230
        }
231
        Cache::put(md5($sql.$page), $return, $expiresAt);
232
233
        return $return;
234
    }
235
236
    /**
237
     * @param $orderBy
238
     *
239
     * @return array
240
     */
241
    public function getMusicOrder($orderBy): array
242
    {
243
        $order = ($orderBy === '') ? 'r.postdate' : $orderBy;
244
        $orderArr = explode('_', $order);
245
        switch ($orderArr[0]) {
246
            case 'artist':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
247
                $orderfield = 'm.artist';
248
                break;
249
            case 'size':
250
                $orderfield = 'r.size';
251
                break;
252
            case 'files':
253
                $orderfield = 'r.totalpart';
254
                break;
255
            case 'stats':
256
                $orderfield = 'r.grabs';
257
                break;
258
            case 'year':
259
                $orderfield = 'm.year';
260
                break;
261
            case 'genre':
262
                $orderfield = 'm.genres_id';
263
                break;
264
            case 'posted':
265
            default:
266
                $orderfield = 'r.postdate';
267
                break;
268
        }
269
        $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
270
271
        return [$orderfield, $ordersort];
272
    }
273
274
    /**
275
     * @return array
276
     */
277
    public function getMusicOrdering(): array
278
    {
279
        return ['artist_asc', 'artist_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'year_asc', 'year_desc', 'genre_asc', 'genre_desc'];
280
    }
281
282
    /**
283
     * @return array
284
     */
285
    public function getBrowseByOptions(): array
286
    {
287
        return ['artist' => 'artist', 'title' => 'title', 'genre' => 'genres_id', 'year' => 'year'];
288
    }
289
290
    /**
291
     * @return string
292
     */
293
    public function getBrowseBy(): string
294
    {
295
        $browseby = ' ';
296
        foreach ($this->getBrowseByOptions() as $bbk => $bbv) {
297
            if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) {
298
                $bbs = stripslashes($_REQUEST[$bbk]);
299
                if (stripos($bbv, 'id') !== false) {
300
                    $browseby .= 'AND m.'.$bbv.' = '.$bbs;
301
                } else {
302
                    $browseby .= 'AND m.'.$bbv.' '.'LIKE '.escapeString('%'.$bbs.'%');
303
                }
304
            }
305
        }
306
307
        return $browseby;
308
    }
309
310
    /**
311
     * @param $id
312
     * @param $title
313
     * @param $asin
314
     * @param $url
315
     * @param $salesrank
316
     * @param $artist
317
     * @param $publisher
318
     * @param $releasedate
319
     * @param $year
320
     * @param $tracks
321
     * @param $cover
322
     * @param $genres_id
323
     */
324
    public function update($id, $title, $asin, $url, $salesrank, $artist, $publisher, $releasedate, $year, $tracks, $cover, $genres_id): void
325
    {
326
        MusicInfo::query()->where('id', $id)->update(
327
            [
328
                'title' => $title,
329
                'asin' => $asin,
330
                'url' => $url,
331
                'salesrank' => $salesrank,
332
                'artist' => $artist,
333
                'publisher' => $publisher,
334
                'releasedate' => $releasedate,
335
                'year' => $year,
336
                'tracks' => $tracks,
337
                'cover' => $cover,
338
                'genres_id' => $genres_id,
339
            ]
340
        );
341
    }
342
343
    /**
344
     * @param      $title
345
     * @param      $year
346
     * @param null $amazdata
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $amazdata is correct as it would always require null to be passed?
Loading history...
347
     *
348
     * @return int|mixed
349
     * @throws \Exception
350
     */
351
    public function updateMusicInfo($title, $year, $amazdata = null)
352
    {
353
        $ri = new ReleaseImage();
354
355
        $mus = [];
356
        if ($amazdata !== null) {
0 ignored issues
show
introduced by
The condition $amazdata !== null is always false.
Loading history...
357
            $mus = $amazdata;
358
        } elseif ($title !== '') {
359
            $mus = $this->fetchItunesMusicProperties($title);
360
        }
361
362
        if ($mus === false) {
0 ignored issues
show
introduced by
The condition $mus === false is always false.
Loading history...
363
            return false;
364
        }
365
366
        $check = MusicInfo::query()->where('asin', $mus['asin'])->first(['id']);
367
        if ($check === null) {
368
            $musicId = MusicInfo::query()->insertGetId(
369
                [
370
                    'title' => $mus['title'],
371
                    'asin' =>$mus['asin'],
372
                    'url' => $mus['url'],
373
                    'salesrank' => $mus['salesrank'],
374
                    'artist' => $mus['artist'],
375
                    'publisher' => $mus['publisher'],
376
                    'releasedate' => $mus['releasedate'],
377
                    'review' => $mus['review'],
378
                    'year' => $year,
379
                    'genres_id' => (int) $mus['musicgenres_id'] === -1 ? 'null' : $mus['musicgenres_id'],
380
                    'tracks' => $mus['tracks'],
381
                    'created_at' => now(),
382
                    'updated_at' => now(),
383
                ]
384
            );
385
            $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
0 ignored issues
show
Bug introduced by
It seems like $musicId can also be of type Illuminate\Database\Eloquent\Builder; however, parameter $imgName of Blacklight\ReleaseImage::saveImage() does only seem to accept string, 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

385
            $mus['cover'] = $ri->saveImage(/** @scrutinizer ignore-type */ $musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
Loading history...
386
            MusicInfo::query()->where('id', $musicId)->update(['cover' => $mus['cover']]);
387
        } else {
388
            $musicId = $check['id'];
389
            $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
0 ignored issues
show
Bug introduced by
It seems like $musicId can also be of type Illuminate\Database\Eloq...uent\Relations\Relation and Illuminate\Database\Eloquent\Relations\Relation; however, parameter $imgName of Blacklight\ReleaseImage::saveImage() does only seem to accept string, 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

389
            $mus['cover'] = $ri->saveImage(/** @scrutinizer ignore-type */ $musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
Loading history...
390
            MusicInfo::query()->where('id', $musicId)->update(
391
                [
392
                    'title' => $mus['title'],
393
                    'asin' => $mus['asin'],
394
                    'url' => $mus['url'],
395
                    'salesrank' => $mus['salesrank'],
396
                    'artist' => $mus['artist'],
397
                    'publisher' => $mus['publisher'],
398
                    'releasedate' => $mus['releasedate'],
399
                    'review' => $mus['review'],
400
                    'year' => $year,
401
                    'genres_id' => (int) $mus['musicgenres_id'] === -1 ? 'null' : $mus['musicgenres_id'],
402
                    'tracks' => $mus['tracks'],
403
                    'cover' => $mus['cover'],
404
                ]
405
            );
406
        }
407
408
        if ($musicId) {
409
            if ($this->echooutput) {
410
                $this->colorCli->header(
411
                    PHP_EOL.'Added/updated album: '.PHP_EOL.
412
                    '   Artist: '.
413
                    $mus['artist'].PHP_EOL.
414
                    '   Title:  '.
415
                    $mus['title'].PHP_EOL.
416
                    '   Year:   '.
417
                    $year
418
                );
419
            }
420
            $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
421
        } elseif ($this->echooutput) {
422
            if ($mus['artist'] === '') {
423
                $artist = '';
424
            } else {
425
                $artist = 'Artist: '.$mus['artist'].', Album: ';
426
            }
427
428
            $this->colorCli->headerOver(
429
                'Nothing to update: '.
430
                    $artist.
431
                    $mus['title'].
432
                    ' ('.
433
                    $year.
434
                    ')'
435
            );
436
        }
437
438
        return $musicId;
439
    }
440
441
    /**
442
     * @param bool $local
443
     * @throws \Exception
444
     */
445
    public function processMusicReleases($local = false)
446
    {
447
        $res = DB::select(
448
            sprintf(
449
                '
450
					SELECT searchname, id
451
					FROM releases
452
					WHERE musicinfo_id IS NULL
453
					AND nzbstatus = %d %s
454
					AND categories_id IN (%s, %s, %s)
455
					ORDER BY postdate DESC
456
					LIMIT %d',
457
                NZB::NZB_ADDED,
458
                $this->renamed,
459
                Category::MUSIC_MP3,
460
                Category::MUSIC_LOSSLESS,
461
                Category::MUSIC_OTHER,
462
                $this->musicqty
463
        )
464
        );
465
466
        if (! empty($res)) {
467
            foreach ($res as $arr) {
468
                $startTime = now();
469
                $usedAmazon = false;
470
                $album = $this->parseArtist($arr->searchname);
471
                if ($album !== false) {
472
                    $newname = $album['name'].' ('.$album['year'].')';
473
474
                    if ($this->echooutput) {
475
                        $this->colorCli->header('Looking up: '.$newname);
476
                    }
477
478
                    // Do a local lookup first
479
                    $musicCheck = $this->getMusicInfoByName('', $album['name']);
480
481
                    if ($musicCheck === null && \in_array($album['name'].$album['year'], $this->failCache, false)) {
482
                        // Lookup recently failed, no point trying again
483
                        if ($this->echooutput) {
484
                            $this->colorCli->headerOver('Cached previous failure. Skipping.');
485
                        }
486
                        $albumId = -2;
487
                    } elseif ($musicCheck === null && $local === false) {
488
                        $albumId = $this->updateMusicInfo($album['name'], $album['year']);
489
                        $usedAmazon = true;
490
                        if ($albumId === false) {
491
                            $albumId = -2;
492
                            $this->failCache[] = $album['name'].$album['year'];
493
                        }
494
                    } else {
495
                        $albumId = $musicCheck['id'];
496
                    }
497
                    Release::query()->where('id', $arr->id)->update(['musicinfo_id' => $albumId]);
498
                } // No album found.
499
                else {
500
                    Release::query()->where('id', $arr->id)->update(['musicinfo_id' => -2]);
501
                    echo '.';
502
                }
503
504
                // Sleep to not flood amazon.
505
                $sleeptime = $this->sleeptime / 1000;
506
                $diff = now()->diffInSeconds($startTime);
507
                if ($sleeptime - $diff > 0 && $usedAmazon === true) {
508
                    sleep($sleeptime - $diff);
509
                }
510
            }
511
512
            if ($this->echooutput) {
513
                echo PHP_EOL;
514
            }
515
        } elseif ($this->echooutput) {
516
            $this->colorCli->header('No music releases to process.');
517
        }
518
    }
519
520
    /**
521
     * @param string $releaseName
522
     *
523
     * @return array|false
524
     */
525
    public function parseArtist($releaseName)
526
    {
527
        if (preg_match('/(.+?)(\d{1,2} \d{1,2} )?\(?(19\d{2}|20[0-1][\d])\b/', $releaseName, $name)) {
528
            $result = [];
529
            $result['year'] = $name[3];
530
531
            $a = preg_replace('/([ |-])(\d{1,2} \d{1,2} )?(Bootleg|Boxset|Clean.+Version|Compiled by.+|\dCD|Digipak|DIRFIX|DVBS|FLAC|(Ltd )?(Deluxe|Limited|Special).+Edition|Promo|PROOF|Reissue|Remastered|REPACK|RETAIL(.+UK)?|SACD|Sampler|SAT|Summer.+Mag|UK.+Import|Deluxe.+Version|VINYL|WEB)/i', ' ', $name[1]);
532
            $b = preg_replace('/([ |-])([a-z]+[\d]+[a-z]+[\d]+.+|[a-z]{2,}[\d]{2,}?.+|3FM|B00[a-z0-9]+|BRC482012|H056|UXM1DW086|(4WCD|ATL|bigFM|CDP|DST|ERE|FIM|MBZZ|MSOne|MVRD|QEDCD|RNB|SBD|SFT|ZYX)([ |-])\d.+)/i', ' ', $a);
533
            $c = preg_replace('/([ |-])(\d{1,2} \d{1,2} )?([A-Z])( ?$)|\(?[\d]{8,}\)?|([ |-])(CABLE|FREEWEB|LINE|MAG|MCD|YMRSMILES)|\(([a-z]{2,}[\d]{2,}|ost)\)|-web-/i', ' ', $b);
534
            $d = preg_replace('/VA([ |-])/', 'Various Artists ', $c);
535
            $e = preg_replace('/([ |-])(\d{1,2} \d{1,2} )?(DAB|DE|DVBC|EP|FIX|IT|Jap|NL|PL|(Pure )?FM|SSL|VLS)([ |-])/i', ' ', $d);
536
            $f = preg_replace('/([ |-])(\d{1,2} \d{1,2} )?(CABLE|CD(A|EP|M|R|S)?|QEDCD|SAT|SBD)([ |-])/i', ' ', $e);
537
            $g = str_replace(['_', '-'], ' ', $f);
538
            $h = trim(preg_replace('/\s\s+/', ' ', $g));
539
            $newname = trim(preg_replace('/ [a-z]{2}$| [a-z]{3} \d{2,}$|\d{5,} \d{5,}$|-WEB$/i', '', $h));
540
541
            if (! preg_match('/^[a-z0-9]+$/i', $newname) && strlen($newname) > 10) {
542
                $result['name'] = $newname;
543
544
                return $result;
545
            }
546
547
            return false;
548
        }
549
550
        return false;
551
    }
552
553
    /**
554
     * @param $nodeId
555
     *
556
     * @return bool|string
557
     */
558
    public function matchBrowseNode($nodeId)
559
    {
560
        $str = '';
561
562
        //music nodes above mp3 download nodes
563
        switch ($nodeId) {
564
            case '163420':
565
                $str = 'Music Video & Concerts';
566
                break;
567
            case '30':
568
            case '624869011':
569
                $str = 'Alternative Rock';
570
                break;
571
            case '31':
572
            case '624881011':
573
                $str = 'Blues';
574
                break;
575
            case '265640':
576
            case '624894011':
577
                $str = 'Broadway & Vocalists';
578
                break;
579
            case '173425':
580
            case '624899011':
581
                $str = "Children's Music";
582
                break;
583
            case '173429': //christian
584
            case '2231705011': //gospel
585
            case '624905011': //christian & gospel
586
                $str = 'Christian & Gospel';
587
                break;
588
            case '67204':
589
            case '624916011':
590
                $str = 'Classic Rock';
591
                break;
592
            case '85':
593
            case '624926011':
594
                $str = 'Classical';
595
                break;
596
            case '16':
597
            case '624976011':
598
                $str = 'Country';
599
                break;
600
            case '7': //dance & electronic
601
            case '624988011': //dance & dj
602
                $str = 'Dance & Electronic';
603
                break;
604
            case '32':
605
            case '625003011':
606
                $str = 'Folk';
607
                break;
608
            case '67207':
609
            case '625011011':
610
                $str = 'Hard Rock & Metal';
611
                break;
612
            case '33': //world music
613
            case '625021011': //international
614
                $str = 'World Music';
615
                break;
616
            case '34':
617
            case '625036011':
618
                $str = 'Jazz';
619
                break;
620
            case '289122':
621
            case '625054011':
622
                $str = 'Latin Music';
623
                break;
624
            case '36':
625
            case '625070011':
626
                $str = 'New Age';
627
                break;
628
            case '625075011':
629
                $str = 'Opera & Vocal';
630
                break;
631
            case '37':
632
            case '625092011':
633
                $str = 'Pop';
634
                break;
635
            case '39':
636
            case '625105011':
637
                $str = 'R&B';
638
                break;
639
            case '38':
640
            case '625117011':
641
                $str = 'Rap & Hip-Hop';
642
                break;
643
            case '40':
644
            case '625129011':
645
                $str = 'Rock';
646
                break;
647
            case '42':
648
            case '625144011':
649
                $str = 'Soundtracks';
650
                break;
651
            case '35':
652
            case '625061011':
653
                $str = 'Miscellaneous';
654
                break;
655
        }
656
657
        return ($str !== '') ? $str : false;
658
    }
659
660
    /**
661
     * @param string $title
662
     *
663
     * @return array|bool
664
     * @throws \DariusIII\ItunesApi\Exceptions\InvalidProviderException
665
     * @throws \Exception
666
     */
667
    protected function fetchItunesMusicProperties($title)
668
    {
669
        $mus = true;
670
        // Load genres.
671
        $defaultGenres = (new Genres())->loadGenres(Genres::MUSIC_TYPE);
672
673
        try {
674
            $album = iTunes::load('album')->fetchOneByName($title);
675
            $track = iTunes::load('track')->fetchOneByName($title);
676
            $artist = iTunes::load('artist')->fetchById($track->getArtistId());
0 ignored issues
show
Bug introduced by
The method getArtistId() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in DariusIII\ItunesApi\Entities\Artist. Are you sure you never get one of those? ( Ignorable by Annotation )

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

676
            $artist = iTunes::load('artist')->fetchById($track->/** @scrutinizer ignore-call */ getArtistId());
Loading history...
677
            $genreName = $album->getGenre();
0 ignored issues
show
Bug introduced by
The method getGenre() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in DariusIII\ItunesApi\Entities\Artist. Are you sure you never get one of those? ( Ignorable by Annotation )

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

677
            /** @scrutinizer ignore-call */ 
678
            $genreName = $album->getGenre();
Loading history...
678
        } catch (AlbumNotFoundException $e) {
679
            try {
680
                $track = iTunes::load('track')->fetchOneByName($title);
681
                $album = iTunes::load('album')->fetchById($track->getAlbumId());
0 ignored issues
show
Bug introduced by
The method getAlbumId() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of DariusIII\ItunesApi\Entities\EntityInterface such as DariusIII\ItunesApi\Entities\Track. ( Ignorable by Annotation )

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

681
                $album = iTunes::load('album')->fetchById($track->/** @scrutinizer ignore-call */ getAlbumId());
Loading history...
682
                $artist = iTunes::load('artist')->fetchById($track->getArtistId());
683
                $genreName = $album->getGenre();
684
            } catch (TrackNotFoundException $e) {
685
                $mus = false;
686
            } catch (SearchNoResultsException $e) {
687
                $mus = false;
688
            } catch (ArtistNotFoundException $e) {
689
                $mus = false;
690
            }
691
        } catch (SearchNoResultsException $e) {
692
            $mus = false;
693
        } catch (ArtistNotFoundException $e) {
694
            $mus = false;
695
        }
696
        if ($mus !== false) {
697
            if (\in_array(strtolower($genreName), $defaultGenres, false)) {
698
                $genreKey = array_search(strtolower($genreName), $defaultGenres, false);
699
            } else {
700
                $genreKey = Genre::query()->insertGetId(['title' => $genreName, 'type' => Genres::MUSIC_TYPE]);
701
            }
702
            $mus = [
703
                'title' => $album->getName(),
704
                'asin' => $album->getItunesId(),
705
                'url' => $album->getStoreUrl(),
0 ignored issues
show
Bug introduced by
The method getStoreUrl() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in DariusIII\ItunesApi\Entities\Track or DariusIII\ItunesApi\Entities\Artist. Are you sure you never get one of those? ( Ignorable by Annotation )

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

705
                'url' => $album->/** @scrutinizer ignore-call */ getStoreUrl(),
Loading history...
706
                'salesrank' => '',
707
                'artist' => $artist->getName(),
708
                'publisher' => $album->getPublisher(),
0 ignored issues
show
Bug introduced by
The method getPublisher() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of DariusIII\ItunesApi\Entities\EntityInterface such as DariusIII\ItunesApi\Entities\Album. ( Ignorable by Annotation )

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

708
                'publisher' => $album->/** @scrutinizer ignore-call */ getPublisher(),
Loading history...
709
                'releasedate' => $album->getReleaseDate(),
0 ignored issues
show
Bug introduced by
The method getReleaseDate() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in DariusIII\ItunesApi\Entities\Track or DariusIII\ItunesApi\Entities\Artist. Are you sure you never get one of those? ( Ignorable by Annotation )

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

709
                'releasedate' => $album->/** @scrutinizer ignore-call */ getReleaseDate(),
Loading history...
710
                'review' => '',
711
                'coverurl' => str_replace('100x100', '800x800', $album->getCover()),
0 ignored issues
show
Bug introduced by
The method getCover() does not exist on DariusIII\ItunesApi\Entities\EntityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in DariusIII\ItunesApi\Entities\Track or DariusIII\ItunesApi\Entities\Artist. Are you sure you never get one of those? ( Ignorable by Annotation )

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

711
                'coverurl' => str_replace('100x100', '800x800', $album->/** @scrutinizer ignore-call */ getCover()),
Loading history...
712
                'tracks' => '',
713
                'musicgenre' => $genreName,
714
                'musicgenres_id' => $genreKey,
715
            ];
716
        }
717
718
        return $mus;
719
    }
720
}
721