koel/app/Services/Media.php

300 lines
8.4 KiB
PHP
Raw Normal View History

2015-12-13 04:42:28 +00:00
<?php
namespace App\Services;
2015-12-14 13:22:39 +00:00
use App\Console\Commands\SyncMedia;
2016-02-04 15:04:53 +00:00
use App\Libraries\WatchRecord\WatchRecordInterface;
2015-12-13 04:42:28 +00:00
use App\Models\Album;
use App\Models\Artist;
use App\Models\Setting;
use App\Models\Song;
2016-02-02 07:47:00 +00:00
use App\Events\LibraryChanged;
2015-12-14 13:22:39 +00:00
use Exception;
2015-12-13 04:42:28 +00:00
use getID3;
use getid3_lib;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Finder\Finder;
2016-02-02 07:47:00 +00:00
use SplFileInfo;
2015-12-13 04:42:28 +00:00
class Media
{
/**
* @var getID3
*/
protected $getID3;
public function __construct()
{
$this->setGetID3();
}
/**
* Sync the media. Oh sync the media.
*
* @param string|null $path
* @param SyncMedia $syncCommand The SyncMedia command object, to log to console if executed by artisan.
*/
public function sync($path = null, SyncMedia $syncCommand = null)
{
2016-01-15 01:53:31 +00:00
if (!app()->runningInConsole()) {
set_time_limit(env('APP_MAX_SCAN_TIME', 600));
}
2015-12-13 04:42:28 +00:00
$path = $path ?: Setting::get('media_path');
$results = [
'good' => [], // Updated or added files
'bad' => [], // Bad files
'ugly' => [], // Unmodified files
];
2016-02-02 07:47:00 +00:00
foreach ($this->gatherFiles($path) as $file) {
2015-12-13 04:42:28 +00:00
$song = $this->syncFile($file);
if ($song === true) {
$results['ugly'][] = $file;
} elseif ($song === false) {
$results['bad'][] = $file;
} else {
$results['good'][] = $file;
}
if ($syncCommand) {
$syncCommand->logToConsole($file->getPathname(), $song);
}
}
// Delete non-existing songs.
$hashes = array_map(function ($f) {
return $this->getHash($f->getPathname());
}, array_merge($results['ugly'], $results['good']));
Song::whereNotIn('id', $hashes)->delete();
2016-02-02 07:47:00 +00:00
// Trigger LibraryChanged, so that TidyLibrary handler is fired to, erm, tidy our library.
event(new LibraryChanged());
}
2015-12-13 04:42:28 +00:00
2016-02-02 07:47:00 +00:00
/**
* Gather all applicable files in a given directory.
*
* @param string $path The directory's full path
*
* @return array An array of SplFileInfo objects
*/
public function gatherFiles($path)
{
return Finder::create()->files()->name('/\.(mp3|ogg|m4a|flac)$/i')->in($path);
2015-12-13 04:42:28 +00:00
}
/**
* Sync a song with all available media info against the database.
*
2016-02-02 07:47:00 +00:00
* @param SplFileInfo|string $file The SplFileInfo instance of the file, or the file path.
2015-12-13 04:42:28 +00:00
*
* @return bool|Song A Song object on success,
2015-12-13 16:13:08 +00:00
* true if file exists but is unmodified,
* or false on an error.
2015-12-13 04:42:28 +00:00
*/
2016-02-02 07:47:00 +00:00
public function syncFile($file)
2015-12-13 04:42:28 +00:00
{
2016-02-02 07:47:00 +00:00
if (!($file instanceof SplFileInfo)) {
$file = new SplFileInfo($file);
}
2015-12-13 04:42:28 +00:00
if (!$info = $this->getInfo($file)) {
return false;
}
if (!$this->isNewOrChanged($file)) {
return true;
}
$artist = Artist::get($info['artist']);
$album = Album::get($artist, $info['album']);
if ($info['cover'] && !$album->has_cover) {
try {
$album->generateCover($info['cover']);
} catch (Exception $e) {
Log::error($e);
}
}
$info['album_id'] = $album->id;
unset($info['artist']);
unset($info['album']);
unset($info['cover']);
$song = Song::updateOrCreate(['id' => $this->getHash($file->getPathname())], $info);
$song->save();
return $song;
}
2016-02-02 07:47:00 +00:00
/**
2016-02-04 15:04:53 +00:00
* Sync media using a watch record.
2016-02-02 07:47:00 +00:00
*
2016-02-04 15:04:53 +00:00
* @param WatchRecordInterface $record The watch record.
2016-02-02 07:47:00 +00:00
* @param SyncMedia|null $syncCommand The SyncMedia command object, to log to console if executed by artisan.
*/
2016-02-04 15:04:53 +00:00
public function syncByWatchRecord(WatchRecordInterface $record, SyncMedia $syncCommand = null)
2016-02-02 07:47:00 +00:00
{
2016-02-04 15:04:53 +00:00
Log::info("New watch record received: $record");
2016-02-02 07:47:00 +00:00
$path = $record->getPath();
if ($record->isFile()) {
2016-02-04 15:04:53 +00:00
Log::info("$record is a file.");
2016-02-02 07:47:00 +00:00
// If the file has been deleted...
if ($record->isDeleted()) {
// ...and it has a record in our database, remove it.
if ($song = Song::byPath($path)) {
$song->delete();
2016-02-04 15:04:53 +00:00
Log::info("$path deleted.");
2016-02-02 07:47:00 +00:00
event(new LibraryChanged());
2016-02-04 15:04:53 +00:00
} else {
Log::info("$path doesn't exist in our database--skipping.");
2016-02-02 07:47:00 +00:00
}
}
// Otherwise, it's a new or changed file. Try to sync it in.
// File format etc. will be handled by the syncFile method.
2016-02-04 15:04:53 +00:00
elseif ($record->isNewOrModified()) {
2016-02-02 07:47:00 +00:00
Log::info($this->syncFile($path) instanceof Song ? "Synchronized $path" : "Invalid file $path");
}
return;
}
2016-02-04 15:04:53 +00:00
// Record is a directory.
Log::info("$record is a directory.");
2016-02-02 07:47:00 +00:00
2016-02-04 15:04:53 +00:00
if ($record->isDeleted()) {
// The directory is removed. We remove all songs in it.
if ($count = Song::inDirectory($path)->delete()) {
Log::info("Deleted $$count song(s) under $path");
2016-02-02 07:47:00 +00:00
event(new LibraryChanged());
} else {
2016-02-04 15:04:53 +00:00
Log::info("$path is empty--no action needed.");
}
} elseif ($record->isNewOrModified()) {
foreach ($this->gatherFiles($path) as $file) {
$this->syncFile($file);
2016-02-02 07:47:00 +00:00
}
2016-02-04 15:04:53 +00:00
Log::info("Synced all song(s) under $path");
2016-02-02 07:47:00 +00:00
}
}
2015-12-13 04:42:28 +00:00
/**
* Check if a media file is new or changed.
* A file is considered existing and unchanged only when:
* - its hash (ID) can be found in the database, and
* - its last modified time is the same with that of the comparing file.
*
* @param SplFileInfo $file
*
* @return bool
*/
protected function isNewOrChanged(SplFileInfo $file)
{
return !Song::whereIdAndMtime($this->getHash($file->getPathname()), $file->getMTime())->count();
}
/**
* Get ID3 info from a file.
*
* @param SplFileInfo $file
*
* @return array|null
*/
public function getInfo(SplFileInfo $file)
{
$info = $this->getID3->analyze($file->getPathname());
if (isset($info['error'])) {
return;
}
// Copy the available tags over to comment.
// This is a helper from getID3, though it doesn't really work well.
// We'll still prefer getting ID3v2 tags directly later.
// Read on.
getid3_lib::CopyTagsToComments($info);
2015-12-14 13:22:39 +00:00
if (!isset($info['playtime_seconds'])) {
return;
}
2015-12-13 04:42:28 +00:00
$props = [
'artist' => '',
'album' => '',
'title' => '',
'length' => $info['playtime_seconds'],
'lyrics' => '',
'cover' => array_get($info, 'comments.picture', [null])[0],
'path' => $file->getPathname(),
'mtime' => $file->getMTime(),
];
if (!$comments = array_get($info, 'comments_html')) {
return $props;
}
// We prefer id3v2 tags over others.
if (!$artist = array_get($info, 'tags.id3v2.artist', [null])[0]) {
$artist = array_get($comments, 'artist', [''])[0];
}
if (!$album = array_get($info, 'tags.id3v2.album', [null])[0]) {
$album = array_get($comments, 'album', [''])[0];
}
if (!$title = array_get($info, 'tags.id3v2.title', [null])[0]) {
$title = array_get($comments, 'title', [''])[0];
}
if (!$lyrics = array_get($info, 'tags.id3v2.unsynchronised_lyric', [null])[0]) {
$lyrics = array_get($comments, 'unsynchronised_lyric', [''])[0];
}
$props['artist'] = trim($artist);
$props['album'] = trim($album);
$props['title'] = trim($title);
$props['lyrics'] = trim($lyrics);
return $props;
}
/**
* Generate a unique hash for a file path.
*
* @param $path
*
* @return string
*/
public function getHash($path)
{
return md5(config('app.key').$path);
}
/**
* @return getID3
*/
public function getGetID3()
{
return $this->getID3;
}
/**
* @param getID3 $getID3
*/
public function setGetID3($getID3 = null)
{
$this->getID3 = $getID3 ?: new getID3();
}
}