Test Setup Failed
Pull Request — master (#590)
by
unknown
11:30
created

Song::getGcpObjectStoragePublicUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
3
namespace App\Models;
4
5
use App\Events\LibraryChanged;
6
use App\Traits\SupportsDeleteWhereIDsNotIn;
7
use AWS;
8
use Aws\AwsClient;
9
use Cache;
10
use Illuminate\Database\Eloquent\Model;
11
use Lastfm;
12
use YouTube;
13
use Google\Cloud\Storage\StorageClient;
14
use Carbon\Carbon;
15
16
/**
17
 * @property string path
18
 * @property string title
19
 * @property Album  album
20
 * @property Artist artist
21
 * @property string s3_params
22
 * @property float  length
23
 * @property string lyrics
24
 * @property int    track
25
 * @property int    album_id
26
 * @property int    id
27
 * @property int    artist_id
28
 */
29
class Song extends Model
30
{
31
    use SupportsDeleteWhereIDsNotIn;
32
33
    protected $guarded = [];
34
35
    /**
36
     * Attributes to be hidden from JSON outputs.
37
     * Here we specify to hide lyrics as well to save some bandwidth (actually, lots of it).
38
     * Lyrics can then be queried on demand.
39
     *
40
     * @var array
41
     */
42
    protected $hidden = ['lyrics', 'updated_at', 'path', 'mtime'];
43
44
    /**
45
     * @var array
46
     */
47
    protected $casts = [
48
        'length' => 'float',
49
        'mtime' => 'int',
50
        'track' => 'int',
51
    ];
52
53
    /**
54
     * Indicates if the IDs are auto-incrementing.
55
     *
56
     * @var bool
57
     */
58
    public $incrementing = false;
59
60
    public function artist()
61
    {
62
        return $this->belongsTo(Artist::class);
63
    }
64
65
    public function album()
66
    {
67
        return $this->belongsTo(Album::class);
68
    }
69
70
    public function playlists()
71
    {
72
        return $this->belongsToMany(Playlist::class);
73
    }
74
75
    /**
76
     * Scrobble the song using Last.fm service.
77
     *
78
     * @param User   $user
79
     * @param string $timestamp The UNIX timestamp in which the song started playing.
80
     *
81
     * @return mixed
82
     */
83
    public function scrobble(User $user, $timestamp)
84
    {
85
        // Don't scrobble the unknown guys. No one knows them.
86
        if ($this->artist->is_unknown) {
87
            return false;
88
        }
89
90
        // If the current user hasn't connected to Last.fm, don't do shit.
91
        if (!$user->connectedToLastfm()) {
92
            return false;
93
        }
94
95
        return Lastfm::scrobble(
96
            $this->artist->name,
97
            $this->title,
98
            $timestamp,
99
            $this->album->name === Album::UNKNOWN_NAME ? '' : $this->album->name,
100
            $user->lastfm_session_key
101
        );
102
    }
103
104
    /**
105
     * Get a Song record using its path.
106
     *
107
     * @param string $path
108
     *
109
     * @return Song|null
110
     */
111
    public static function byPath($path)
112
    {
113
        return self::find(File::getHash($path));
114
    }
115
116
    /**
117
     * Update song info.
118
     *
119
     * @param array $ids
120
     * @param array $data The data array, with these supported fields:
121
     *                    - title
122
     *                    - artistName
123
     *                    - albumName
124
     *                    - lyrics
125
     *                    All of these are optional, in which case the info will not be changed
126
     *                    (except for lyrics, which will be emptied).
127
     *
128
     * @return array
129
     */
130
    public static function updateInfo($ids, $data)
131
    {
132
        /*
133
         * A collection of the updated songs.
134
         *
135
         * @var \Illuminate\Support\Collection
136
         */
137
        $updatedSongs = collect();
138
139
        $ids = (array) $ids;
140
        // If we're updating only one song, take into account the title, lyrics, and track number.
141
        $single = count($ids) === 1;
142
143
        foreach ($ids as $id) {
144
            if (!$song = self::with('album', 'album.artist')->find($id)) {
0 ignored issues
show
Bug introduced by
The method find does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
145
                continue;
146
            }
147
148
            $updatedSongs->push($song->updateSingle(
149
                $single ? trim($data['title']) : $song->title,
150
                trim($data['albumName'] ?: $song->album->name),
151
                trim($data['artistName']) ?: $song->artist->name,
152
                $single ? trim($data['lyrics']) : $song->lyrics,
153
                $single ? (int) $data['track'] : $song->track,
154
                (int) $data['compilationState']
155
            ));
156
        }
157
158
        // Our library may have been changed. Broadcast an event to tidy it up if need be.
159
        if ($updatedSongs->count()) {
160
            event(new LibraryChanged());
161
        }
162
163
        return [
164
            'artists' => Artist::whereIn('id', $updatedSongs->pluck('artist_id'))->get(),
165
            'albums' => Album::whereIn('id', $updatedSongs->pluck('album_id'))->get(),
166
            'songs' => $updatedSongs,
167
        ];
168
    }
169
170
    /**
171
     * Update a single song's info.
172
     *
173
     * @param string $title
174
     * @param string $albumName
175
     * @param string $artistName
176
     * @param string $lyrics
177
     * @param int    $track
178
     * @param int    $compilationState
179
     *
180
     * @return self
181
     */
182
    public function updateSingle($title, $albumName, $artistName, $lyrics, $track, $compilationState)
183
    {
184
        if ($artistName === Artist::VARIOUS_NAME) {
185
            // If the artist name is "Various Artists", it's a compilation song no matter what.
186
            $compilationState = 1;
187
            // and since we can't determine the real contributing artist, it's "Unknown"
188
            $artistName = Artist::UNKNOWN_NAME;
189
        }
190
191
        $artist = Artist::get($artistName);
192
193
        switch ($compilationState) {
194
            case 1: // ALL, or forcing compilation status to be Yes
195
                $isCompilation = true;
196
                break;
197
            case 2: // Keep current compilation status
198
                $isCompilation = $this->album->artist_id === Artist::VARIOUS_ID;
199
                break;
200
            default:
201
                $isCompilation = false;
202
                break;
203
        }
204
205
        $album = Album::get($artist, $albumName, $isCompilation);
206
207
        $this->artist_id = $artist->id;
208
        $this->album_id = $album->id;
209
        $this->title = $title;
210
        $this->lyrics = $lyrics;
211
        $this->track = $track;
212
213
        $this->save();
214
215
        // Clean up unnecessary data from the object
216
        unset($this->album);
217
        unset($this->artist);
218
        // and make sure the lyrics is shown
219
        $this->makeVisible('lyrics');
220
221
        return $this;
222
    }
223
224
    /**
225
     * Scope a query to only include songs in a given directory.
226
     *
227
     * @param \Illuminate\Database\Eloquent\Builder $query
228
     * @param string                                $path  Full path of the directory
229
     *
230
     * @return \Illuminate\Database\Eloquent\Builder
231
     */
232
    public function scopeInDirectory($query, $path)
233
    {
234
        // Make sure the path ends with a directory separator.
235
        $path = rtrim(trim($path), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
236
237
        return $query->where('path', 'LIKE', "$path%");
238
    }
239
240
    /**
241
     * Get all songs favored by a user.
242
     *
243
     * @param User $user
244
     * @param bool $toArray
245
     *
246
     * @return \Illuminate\Database\Eloquent\Collection|array
247
     */
248
    public static function getFavorites(User $user, $toArray = false)
249
    {
250
        $songs = Interaction::whereUserIdAndLike($user->id, true)
251
            ->with('song')
252
            ->get()
253
            ->pluck('song');
254
255
        return $toArray ? $songs->toArray() : $songs;
256
    }
257
258
    /**
259
     * Get the song's Object Storage url for streaming or downloading.
260
     *
261
     * @param AwsClient $s3
262
     *
263
     * @return string
264
     */
265
    public function getObjectStoragePublicUrl(AwsClient $s3 = null)
266
    {
267
        // If we have a cached version, just return it.
268
        if ($cached = Cache::get("OSUrl/{$this->id}")) {
269
            return $cached;
270
        }
271
272
        // Otherwise, we query S3 for the presigned request.
273
        if (!$s3) {
274
            $s3 = AWS::createClient('s3');
275
        }
276
277
        $cmd = $s3->getCommand('GetObject', [
278
            'Bucket' => $this->s3_params['bucket'],
279
            'Key' => $this->s3_params['key'],
280
        ]);
281
282
        // Here we specify that the request is valid for 1 hour.
283
        // We'll also cache the public URL for future reuse.
284
        $request = $s3->createPresignedRequest($cmd, '+1 hour');
285
        $url = (string) $request->getUri();
286
        Cache::put("OSUrl/{$this->id}", $url, 60);
287
288
        return $url;
289
    }
290
291
    public function getGcpObjectStoragePublicUrl(StorageClient $gcs = null)
292
    {
293
        // If we have a cached version, just return it.
294
        if ($cached = Cache::get("OSUrl/{$this->id}")) {
295
            return $cached;
296
        }
297
        if (!$gcs) {
298
            $gcs = new StorageClient([]);
299
        }
300
        $bucket = $gcs->bucket($this->gcp_params['bucket']);
0 ignored issues
show
Documentation introduced by
The property gcp_params does not exist on object<App\Models\Song>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
301
        $object = $bucket->object($this->gcp_params['key']);
0 ignored issues
show
Documentation introduced by
The property gcp_params does not exist on object<App\Models\Song>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
302
        $options = array();
303
        $options['keyFilePath'] = env('GCS_KEY_FILE_PATH');
304
        $url = $object->signedUrl(Carbon::now()->addHours(24)->timestamp, $options);
305
        Cache::put("OSUrl/{$this->id}", $url, 60);
306
        return $url;
307
    }
308
309
310
311
    /**
312
     * Get the YouTube videos related to this song.
313
     *
314
     * @param string $youTubePageToken The YouTube page token, for pagination purpose.
315
     *
316
     * @return @return object|false
0 ignored issues
show
Documentation introduced by
The doc-type @return could not be parsed: Unknown type name "@return" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
317
     */
318
    public function getRelatedYouTubeVideos($youTubePageToken = '')
319
    {
320
        return YouTube::searchVideosRelatedToSong($this, $youTubePageToken);
321
    }
322
323
    /**
324
     * Sometimes the tags extracted from getID3 are HTML entity encoded.
325
     * This makes sure they are always sane.
326
     *
327
     * @param $value
328
     */
329
    public function setTitleAttribute($value)
330
    {
331
        $this->attributes['title'] = html_entity_decode($value);
332
    }
333
334
    /**
335
     * Some songs don't have a title.
336
     * Fall back to the file name (without extension) for such.
337
     *
338
     * @param  $value
339
     *
340
     * @return string
341
     */
342
    public function getTitleAttribute($value)
343
    {
344
        return $value ?: pathinfo($this->path, PATHINFO_FILENAME);
345
    }
346
347
    /**
348
     * Prepare the lyrics for displaying.
349
     *
350
     * @param $value
351
     *
352
     * @return string
353
     */
354
    public function getLyricsAttribute($value)
355
    {
356
        // We don't use nl2br() here, because the function actually preserves line breaks -
357
        // it just _appends_ a "<br />" after each of them. This would cause our client
358
        // implementation of br2nl to fail with duplicated line breaks.
359
        return str_replace(["\r\n", "\r", "\n"], '<br />', $value);
360
    }
361
362
    /**
363
     * Determine if the song is an AWS S3 Object.
364
     *
365
     * @return bool
366
     */
367
    public function isS3ObjectAttribute()
368
    {
369
        return starts_with($this->path, 's3://');
370
    }
371
372
    /**
373
     * Get the bucket and key name of an S3 object.
374
     *
375
     * @return bool|array
376
     */
377 View Code Duplication
    public function getS3ParamsAttribute()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
378
    {
379
        if (!preg_match('/^s3:\\/\\/(.*)/', $this->path, $matches)) {
380
            return false;
381
        }
382
383
        list($bucket, $key) = explode('/', $matches[1], 2);
384
385
        return compact('bucket', 'key');
386
    }
387
388
    public function isGCPObjectAttribute()
389
    {
390
        return starts_with($this->path, 'gs://');
391
    }
392
393
    /**
394
     * Get the bucket and key name of an GCS object.
395
     *
396
     * @return bool|array
397
     */
398 View Code Duplication
    public function getGCPParamsAttribute()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
399
    {
400
        if (!preg_match('/^gs:\\/\\/(.*)/', $this->path, $matches)) {
401
            return false;
402
        }
403
404
        list($bucket, $key) = explode('/', $matches[1], 2);
405
406
        return compact('bucket', 'key');
407
    }	
408
}
409