Pony.fm/app/models/Entities/Track.php

522 lines
17 KiB
PHP
Raw Normal View History

2013-07-25 23:33:04 +02:00
<?php
namespace Entities;
2013-07-27 02:15:07 +02:00
use Cover;
2013-07-28 19:45:21 +02:00
use External;
use getid3_writetags;
2013-08-01 04:01:41 +02:00
use Helpers;
2013-08-01 10:57:08 +02:00
use Illuminate\Support\Facades\Auth;
2013-08-10 00:57:30 +02:00
use Illuminate\Support\Facades\Cache;
2013-09-02 00:51:51 +02:00
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
2013-07-28 19:45:21 +02:00
use Illuminate\Support\Facades\Log;
2013-07-28 23:51:35 +02:00
use Illuminate\Support\Facades\URL;
2013-07-28 19:45:21 +02:00
use Illuminate\Support\Str;
2013-07-25 23:33:04 +02:00
use Whoops\Example\Exception;
2013-07-28 19:45:21 +02:00
use Traits\SlugTrait;
2013-07-25 23:33:04 +02:00
class Track extends \Eloquent {
protected $softDelete = true;
2013-09-23 05:44:37 +02:00
use SlugTrait {
SlugTrait::setTitleAttribute as setTitleAttributeSlug;
}
2013-07-28 19:45:21 +02:00
2013-07-25 23:33:04 +02:00
public static $Formats = [
'FLAC' => ['index' => 0, 'is_lossless' => true, 'extension' => 'flac', 'tag_format' => 'metaflac', 'tag_method' => 'updateTagsWithGetId3', 'mime_type' => 'audio/flac', 'command' => 'ffmpeg 2>&1 -y -i {$source} -acodec flac -aq 8 -f flac {$target}'],
'MP3' => ['index' => 1, 'is_lossless' => false, 'extension' => 'mp3', 'tag_format' => 'id3v2.3', 'tag_method' => 'updateTagsWithGetId3', 'mime_type' => 'audio/mpeg', 'command' => 'ffmpeg 2>&1 -y -i {$source} -acodec libmp3lame -ab 320k -f mp3 {$target}'],
'OGG Vorbis' => ['index' => 2, 'is_lossless' => false, 'extension' => 'ogg', 'tag_format' => 'vorbiscomment', 'tag_method' => 'updateTagsWithGetId3', 'mime_type' => 'audio/ogg', 'command' => 'ffmpeg 2>&1 -y -i {$source} -acodec libvorbis -aq 7 -f ogg {$target}'],
'AAC' => ['index' => 3, 'is_lossless' => false, 'extension' => 'm4a', 'tag_format' => 'AtomicParsley', 'tag_method' => 'updateTagsWithAtomicParsley', 'mime_type' => 'audio/mp4', 'command' => 'ffmpeg 2>&1 -y -i {$source} -acodec libfaac -ab 256k -f mp4 {$target}'],
'ALAC' => ['index' => 4, 'is_lossless' => true, 'extension' => 'alac.m4a', 'tag_format' => 'AtomicParsley', 'tag_method' => 'updateTagsWithAtomicParsley', 'mime_type' => 'audio/mp4', 'command' => 'ffmpeg 2>&1 -y -i {$source} -acodec alac {$target}'],
2013-07-25 23:33:04 +02:00
];
public static function summary() {
2013-08-19 05:39:29 +02:00
return self::select('id', 'title', 'user_id', 'slug', 'is_vocal', 'is_explicit', 'created_at', 'published_at', 'duration', 'is_downloadable', 'genre_id', 'track_type_id', 'cover_id', 'album_id', 'comment_count', 'download_count', 'view_count', 'play_count', 'favourite_count');
2013-07-25 23:33:04 +02:00
}
public function scopeUserDetails($query) {
2013-08-01 10:57:08 +02:00
if (Auth::check()) {
2013-08-19 05:39:29 +02:00
$query->with(['users' => function($query) {
2013-08-01 10:57:08 +02:00
$query->whereUserId(Auth::user()->id);
}]);
}
}
public function scopePublished($query) {
$query->whereNotNull('published_at');
}
2013-09-24 08:27:13 +02:00
public function scopeListed($query) {
$query->whereIsListed(true);
}
public function scopeExplicitFilter($query) {
if (!Auth::check() || !Auth::user()->can_see_explicit_content)
$query->whereIsExplicit(false);
}
2013-08-01 10:57:08 +02:00
public function scopeWithComments($query) {
$query->with(['comments' => function($query) { $query->with('user'); }]);
}
public static function popular($count, $allowExplicit = false) {
2013-09-02 00:51:51 +02:00
$trackIds = Cache::remember('popular_tracks' . $count . '-' . ($allowExplicit ? 'explicit' : 'safe'), 5, function() use ($allowExplicit, $count) {
$query = static
2013-09-01 07:03:37 +02:00
::published()
2013-09-24 08:27:13 +02:00
->listed()
->join(DB::raw('
( SELECT `track_id`, `created_at`
FROM `resource_log_items`
2013-09-01 07:03:37 +02:00
WHERE track_id IS NOT NULL AND log_type = 3 AND `created_at` > now() - INTERVAL 1 DAY
) AS ranged_plays'),
'tracks.id', '=', 'ranged_plays.track_id')
->groupBy('id')
->orderBy('plays', 'desc')
2013-09-02 00:51:51 +02:00
->take($count);
2013-09-01 07:03:37 +02:00
if (!$allowExplicit)
$query->whereIsExplicit(false);
$results = [];
foreach($query->get(['*', DB::raw('count(*) as plays')]) as $track) {
2013-09-01 07:03:37 +02:00
$results[] = $track->id;
}
return $results;
});
2013-09-10 04:25:49 +02:00
if (!count($trackIds))
return [];
2013-09-01 07:03:37 +02:00
$tracks = Track::summary()
->userDetails()
->explicitFilter()
->published()
->with('user', 'genre', 'cover', 'album', 'album.user')
->whereIn('id', $trackIds);
$processed = [];
foreach ($tracks->get() as $track)
$processed[] = Track::mapPublicTrackSummary($track);
return $processed;
}
public static function mapPublicTrackShow($track) {
$returnValue = self::mapPublicTrackSummary($track);
$returnValue['description'] = $track->description;
$returnValue['lyrics'] = $track->lyrics;
2013-08-01 10:57:08 +02:00
$comments = [];
foreach ($track->comments as $comment) {
$comments[] = Comment::mapPublic($comment);
}
2013-08-19 05:39:29 +02:00
$returnValue['comments'] = $comments;
2013-08-01 04:01:41 +02:00
if ($track->album_id != null) {
$returnValue['album'] = [
'title' => $track->album->title,
'url' => $track->album->url,
];
}
$formats = [];
foreach ($track->trackFiles as $trackFile) {
2013-08-10 00:57:30 +02:00
$formats[] = [
'name' => $trackFile->format,
'extension' => $trackFile->extension,
'url' => $trackFile->url,
'size' => $trackFile->size
2013-08-10 00:57:30 +02:00
];
2013-08-01 04:01:41 +02:00
}
$returnValue['share'] = [
'url' => URL::to('/t' . $track->id),
2013-08-31 05:16:16 +02:00
'html' => '<iframe src="' . URL::to('t' . $track->id . '/embed') . '" width="100%" height="150" allowTransparency="true" frameborder="0" seamless allowfullscreen></iframe>',
'bbcode' => '[url=' . $track->url . '][img]' . $track->getCoverUrl() . '[/img][/url]',
'twitterUrl' => 'https://platform.twitter.com/widgets/tweet_button.html?text=' . $track->title . ' by ' . $track->user->display_name . ' on Pony.fm'
];
$returnValue['share']['tumblrUrl'] = 'http://www.tumblr.com/share/video?embed=' . urlencode($returnValue['share']['html']) . '&caption=' . urlencode($track->title);
2013-08-01 04:01:41 +02:00
$returnValue['formats'] = $formats;
return $returnValue;
}
public static function mapPublicTrackSummary($track) {
2013-08-19 05:39:29 +02:00
$userData = [
'stats' => [
'views' => 0,
'plays' => 0,
'downloads' => 0
],
'is_favourited' => false
];
if (Auth::check() && $track->users->count()) {
2013-08-19 05:39:29 +02:00
$userRow = $track->users[0];
$userData = [
'stats' => [
'views' => (int) $userRow->view_count,
'plays' => (int) $userRow->play_count,
2013-08-19 05:39:29 +02:00
'downloads' => $userRow->download_count,
],
'is_favourited' => (bool) $userRow->is_favourited
2013-08-19 05:39:29 +02:00
];
}
return [
'id' => (int) $track->id,
'title' => $track->title,
'user' => [
'id' => (int) $track->user->id,
'name' => $track->user->display_name,
'url' => $track->user->url
],
2013-08-19 05:39:29 +02:00
'stats' => [
'views' => (int) $track->view_count,
'plays' => (int) $track->play_count,
'downloads' => (int) $track->download_count,
'comments' => (int) $track->comment_count,
'favourites' => (int) $track->favourite_count
2013-08-19 05:39:29 +02:00
],
'url' => $track->url,
'slug' => $track->slug,
'is_vocal' => (bool) $track->is_vocal,
'is_explicit' => (bool) $track->is_explicit,
'is_downloadable' => (bool) $track->is_downloadable,
'is_published' => (bool) $track->isPublished(),
'published_at' => $track->published_at,
'duration' => $track->duration,
'genre' => $track->genre != null
?
[
'id' => (int) $track->genre->id,
'slug' => $track->genre->slug,
'name' => $track->genre->name
] : null,
'track_type_id' => $track->track_type_id,
'covers' => [
'thumbnail' => $track->getCoverUrl(Image::THUMBNAIL),
'small' => $track->getCoverUrl(Image::SMALL),
'normal' => $track->getCoverUrl(Image::NORMAL)
2013-08-01 10:57:08 +02:00
],
2013-08-10 00:57:30 +02:00
'streams' => [
2013-09-02 00:51:51 +02:00
'mp3' => $track->getStreamUrl('MP3'),
'aac' => (!Config::get('app.debug') || is_file($track->getFileFor('AAC')) ) ? $track->getStreamUrl('AAC') : null,
'ogg' => ( Config::get('app.debug') || is_file($track->getFileFor('OGG Vorbis'))) ? $track->getStreamUrl('OGG Vorbis') : null
2013-08-19 05:39:29 +02:00
],
'user_data' => $userData,
'permissions' => [
'delete' => Auth::check() && Auth::user()->id == $track->user_id,
'edit' => Auth::check() && Auth::user()->id == $track->user_id
]
];
}
public static function mapPrivateTrackShow($track) {
$showSongs = [];
foreach ($track->showSongs as $showSong) {
$showSongs[] = ['id' => $showSong->id, 'title' => $showSong->title];
}
$returnValue = self::mapPrivateTrackSummary($track);
$returnValue['album_id'] = $track->album_id;
$returnValue['show_songs'] = $showSongs;
$returnValue['real_cover_url'] = $track->getCoverUrl(Image::NORMAL);
$returnValue['cover_url'] = $track->hasCover() ? $track->getCoverUrl(Image::NORMAL) : null;
$returnValue['released_at'] = $track->released_at;
$returnValue['lyrics'] = $track->lyrics;
$returnValue['description'] = $track->description;
$returnValue['is_downloadable'] = !$track->isPublished() ? true : (bool)$track->is_downloadable;
$returnValue['license_id'] = $track->license_id != null ? $track->license_id : 3;
return $returnValue;
}
public static function mapPrivateTrackSummary($track) {
return [
'id' => $track->id,
'title' => $track->title,
'user_id' => $track->user_id,
'slug' => $track->slug,
'is_vocal' => $track->is_vocal,
'is_explicit' => $track->is_explicit,
'is_downloadable' => $track->is_downloadable,
'is_published' => $track->isPublished(),
'created_at' => $track->created_at,
'published_at' => $track->published_at,
'duration' => $track->duration,
'genre_id' => $track->genre_id,
'track_type_id' => $track->track_type_id,
2013-09-24 08:27:13 +02:00
'cover_url' => $track->getCoverUrl(Image::SMALL),
'is_listed' => !!$track->is_listed
];
}
2013-07-25 23:33:04 +02:00
protected $table = 'tracks';
2013-07-28 19:45:21 +02:00
public function genre() {
return $this->belongsTo('Entities\Genre');
}
2013-09-23 05:44:37 +02:00
public function trackType() {
return $this->belongsTo('Entities\TrackType', 'track_type_id');
}
2013-08-01 10:57:08 +02:00
public function comments(){
return $this->hasMany('Entities\Comment')->orderBy('created_at', 'desc');
2013-08-01 10:57:08 +02:00
}
public function favourites() {
return $this->hasMany('Entities\Favourite');
}
2013-07-28 19:45:21 +02:00
public function cover() {
return $this->belongsTo('Entities\Image');
}
public function showSongs() {
return $this->belongsToMany('Entities\ShowSong');
}
2013-08-19 05:39:29 +02:00
public function users() {
return $this->hasMany('Entities\ResourceUser');
}
2013-07-28 19:45:21 +02:00
public function user() {
return $this->belongsTo('Entities\User');
}
public function album() {
return $this->belongsTo('Entities\Album');
}
public function trackFiles() {
return $this->hasMany('Entities\TrackFile');
}
public function getYearAttribute() {
return date('Y', strtotime($this->getReleaseDate()));
2013-07-28 19:45:21 +02:00
}
2013-09-23 05:44:37 +02:00
public function setTitleAttribute($value) {
$this->setTitleAttributeSlug($value);;
$this->updateHash();
}
2013-08-10 00:57:30 +02:00
public function getFilesize($formatName) {
return Cache::remember($this->getCacheKey('filesize-' . $formatName), 1440, function () use ($formatName) {
$file = $this->getFileFor($formatName);
$size = 0;
if (is_file($file))
$size = filesize($file);
return $size;
});
}
public function canView($user) {
if ($this->isPublished())
return true;
return $this->user_id == $user->id;
}
2013-07-28 23:51:35 +02:00
public function getUrlAttribute() {
return URL::to('/tracks/' . $this->id . '-' . $this->slug);
2013-07-28 23:51:35 +02:00
}
public function getDownloadDirectoryAttribute() {
if ($this->album) {
return $this->user->display_name . '/' . $this->album->title;
}
return $this->user->display_name;
}
public function getReleaseDate() {
if($this->released_at !== NULL)
return $this->released_at;
2013-07-28 19:45:21 +02:00
if ($this->published_at !== NULL) {
return Str::limit($this->published_at, 10, '');
}
2013-07-28 19:45:21 +02:00
return Str::limit($this->attributes['created_at'], 10, '');
}
2013-07-27 02:15:07 +02:00
public function ensureDirectoryExists() {
$destination = $this->getDirectory();
2013-09-27 22:49:22 +02:00
umask(0);
2013-07-27 02:15:07 +02:00
if (!is_dir($destination))
mkdir($destination, 0777, true);
2013-07-25 23:33:04 +02:00
}
2013-07-27 02:15:07 +02:00
public function hasCover() {
return $this->cover_id != null;
}
public function isPublished() {
return $this->published_at != null && $this->deleted_at == null;
}
2013-07-28 09:09:10 +02:00
public function getCoverUrl($type = Image::NORMAL) {
2013-07-28 19:45:21 +02:00
if (!$this->hasCover()) {
if ($this->album_id != null)
return $this->album->getCoverUrl($type);
2013-07-27 02:15:07 +02:00
return $this->user->getAvatarUrl($type);
2013-07-28 19:45:21 +02:00
}
2013-07-27 02:15:07 +02:00
return $this->cover->getUrl($type);
2013-07-25 23:33:04 +02:00
}
2013-09-02 00:51:51 +02:00
public function getStreamUrl($format = 'MP3') {
return URL::to('/t' . $this->id . '/stream.' . self::$Formats[$format]['extension']);
2013-08-10 00:57:30 +02:00
}
2013-07-25 23:33:04 +02:00
public function getDirectory() {
$dir = (string) ( floor( $this->id / 100 ) * 100 );
return \Config::get('app.files_directory') . '/tracks/' . $dir;
}
2013-07-27 02:15:07 +02:00
public function getDates() {
return ['created_at', 'deleted_at', 'published_at', 'released_at'];
}
2013-07-25 23:33:04 +02:00
public function getFilenameFor($format) {
if (!isset(self::$Formats[$format]))
throw new Exception("$format is not a valid format!");
$format = self::$Formats[$format];
return "{$this->id}.{$format['extension']}";
}
2013-07-28 19:45:21 +02:00
2013-08-19 05:39:29 +02:00
public function getDownloadFilenameFor($format) {
if (!isset(self::$Formats[$format]))
throw new Exception("$format is not a valid format!");
$format = self::$Formats[$format];
return "{$this->title}.{$format['extension']}";
}
2013-07-28 19:45:21 +02:00
public function getFileFor($format) {
if (!isset(self::$Formats[$format]))
throw new Exception("$format is not a valid format!");
$format = self::$Formats[$format];
return "{$this->getDirectory()}/{$this->id}.{$format['extension']}";
}
2013-08-01 04:01:41 +02:00
public function getUrlFor($format) {
if (!isset(self::$Formats[$format]))
throw new Exception("$format is not a valid format!");
$format = self::$Formats[$format];
return URL::to('/t' . $this->id . '/dl.' . $format['extension']);
}
2013-09-23 05:44:37 +02:00
public function updateHash() {
2014-05-28 09:22:34 +02:00
$this->hash = md5(Helpers::sanitizeInputForHashing($this->user->display_name) . ' - ' . Helpers::sanitizeInputForHashing($this->title));
2013-09-23 05:44:37 +02:00
}
2013-07-28 19:45:21 +02:00
public function updateTags() {
$this->trackFiles()->touch();
foreach ($this->trackFiles as $trackFile) {
$format = $trackFile->format;
$data = self::$Formats[$format];
2013-07-28 19:45:21 +02:00
$this->{$data['tag_method']}($format);
}
}
/** @noinspection PhpUnusedPrivateMethodInspection */
private function updateTagsWithAtomicParsley($format) {
$command = 'AtomicParsley "' . $this->getFileFor($format) . '" ';
$command .= '--title ' . escapeshellarg($this->title) . ' ';
$command .= '--artist ' . escapeshellarg($this->user->display_name) . ' ';
$command .= '--year "' . $this->year . '" ';
$command .= '--genre ' . escapeshellarg($this->genre != null ? $this->genre->name : '') . ' ';
2013-07-28 19:45:21 +02:00
$command .= '--copyright ' . escapeshellarg('© '.$this->year.' '.$this->user->display_name).' ';
$command .= '--comment "' . 'Downloaded from: https://pony.fm/' . '" ';
$command .= '--encodingTool "' . 'Pony.fm - https://pony.fm/' . '" ';
2013-07-28 19:45:21 +02:00
if ($this->album_id !== NULL) {
$command .= '--album ' . escapeshellarg($this->album->title) . ' ';
$command .= '--tracknum ' . $this->track_number . ' ';
}
if ($this->cover !== NULL) {
$command .= '--artwork ' . $this->cover->getFile() . ' ';
2013-07-28 19:45:21 +02:00
}
$command .= '--overWrite';
External::execute($command);
}
/** @noinspection PhpUnusedPrivateMethodInspection */
private function updateTagsWithGetId3($format) {
require_once(app_path() . '/library/getid3/getid3/getid3.php');
require_once(app_path() . '/library/getid3/getid3/write.php');
2013-07-28 19:45:21 +02:00
$tagWriter = new getid3_writetags;
$tagWriter->overwrite_tags = true;
$tagWriter->tag_encoding = 'UTF-8';
$tagWriter->remove_other_tags = true;
$tagWriter->tag_data = [
'title' => [$this->title],
'artist' => [$this->user->display_name],
'year' => ['' . $this->year],
'genre' => [$this->genre != null ? $this->genre->name : ''],
2013-07-28 19:45:21 +02:00
'comment' => ['Downloaded from: https://pony.fm/'],
'copyright' => ['© ' . $this->year . ' ' . $this->user->display_name],
'publisher' => ['Pony.fm - https://pony.fm/'],
'encoded_by' => ['https://pony.fm/'],
// 'url_artist' => [$this->user->url],
// 'url_source' => [$this->url],
// 'url_file' => [$this->url],
'url_publisher' => ['https://pony.fm/']
];
if ($this->album_id !== NULL) {
$tagWriter->tag_data['album'] = [$this->album->title];
$tagWriter->tag_data['track'] = [$this->track_number];
}
if ($format == 'MP3' && $this->cover_id != NULL && is_file($this->cover->getFile())) {
2013-07-28 19:45:21 +02:00
$tagWriter->tag_data['attached_picture'][0] = [
'data' => file_get_contents($this->cover->getFile()),
2013-07-28 19:45:21 +02:00
'picturetypeid' => 2,
'description' => 'cover',
'mime' => 'image/png'
];
}
$tagWriter->filename = $this->getFileFor($format);
$tagWriter->tagformats = [self::$Formats[$format]['tag_format']];
if ($tagWriter->WriteTags()) {
if (!empty($tagWriter->warnings)) {
Log::warning('Track #'.$this->id.': There were some warnings:<br />' . implode('<br /><br />', $tagWriter->warnings));
2013-07-28 19:45:21 +02:00
}
} else {
Log::error('Track #' . $this->id . ': Failed to write tags!<br />' . implode('<br /><br />', $tagWriter->errors));
2013-07-28 19:45:21 +02:00
}
}
2013-08-10 00:57:30 +02:00
private function getCacheKey($key) {
return 'track-' . $this->id . '-' . $key;
}
}