photo/app/Models/Abstracted/Catalog.php

542 lines
13 KiB
PHP
Raw Normal View History

2018-01-11 12:59:53 +00:00
<?php
2019-11-08 12:51:47 +00:00
namespace App\Models\Abstracted;
2018-01-11 12:59:53 +00:00
2019-12-15 12:34:42 +00:00
use Carbon\Carbon;
2018-01-11 12:59:53 +00:00
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
2018-01-11 12:59:53 +00:00
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
2018-01-11 12:59:53 +00:00
use App\Casts\PostgresBytea;
use App\Jobs\CatalogMove;
use App\Models\{Make,Person,Software,Tag};
2019-11-08 12:51:47 +00:00
2018-01-11 12:59:53 +00:00
abstract class Catalog extends Model
{
2019-12-14 11:29:54 +00:00
protected static $includeSubSecTime = FALSE;
2019-11-23 01:51:30 +00:00
2020-01-04 22:37:50 +00:00
protected $casts = [
'created_manual' => 'datetime',
2020-01-04 22:37:50 +00:00
'subsectime' => 'int',
'thumbnail' => PostgresBytea::class,
2020-01-04 22:37:50 +00:00
];
public const fs = 'nas';
private ?string $move_reason;
protected array $init = [];
/* STATIC */
public static function boot()
{
parent::boot();
// Any video saved, queue it to be moved.
self::saved(function($item) {
if ($item->scanned && (! $item->duplicate) && (! $item->remove) && ($item->shouldMove() === TRUE)) {
Log::info(sprintf('Need to Move [%s] to [%s]',$item->file_name_rel(),$item->file_name_rel(FALSE)));
CatalogMove::dispatch($item)
->onQueue('move');
}
});
}
/**
2024-10-04 01:08:18 +00:00
* Return the prefix for the file path - dependent on the object
*
* @return string
*/
public static function dir_prefix(): string
{
return config(static::config.'.dir').'/';
}
/* RELATIONS */
/**
* People in Multimedia Object
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
2019-11-23 01:51:30 +00:00
public function people()
2018-01-11 12:59:53 +00:00
{
2019-11-08 12:51:47 +00:00
return $this->belongsToMany(Person::class);
2018-01-11 12:59:53 +00:00
}
/**
* Software used to create Multimedia Object
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
2019-12-26 04:56:31 +00:00
public function software()
{
return $this->belongsTo(Software::class);
}
/**
* Tags added to Multimedia Object
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
2019-11-23 01:51:30 +00:00
public function tags()
2018-01-11 12:59:53 +00:00
{
2019-11-08 12:51:47 +00:00
return $this->belongsToMany(Tag::class);
2018-01-11 12:59:53 +00:00
}
/* SCOPES */
/**
* Find records marked as duplicate
*
* @param $query
* @return mixed
*/
public function scopeDuplicates($query)
{
return $query->notRemove()
->where('duplicate',TRUE)
->where(fn($q)=>$q->where('ignore_duplicate','<>',TRUE)->orWhereNull('ignore_duplicate'));
}
/**
* Search Database for duplicates of this object
*
* @param $query
* @return mixed
*/
public function scopeMyDuplicates($query) {
2019-12-14 11:29:54 +00:00
if (! $this->exists)
return $query;
// Exclude this record
$query->where('id','<>',$this->attributes['id']);
// Skip ignore dups
2024-09-16 13:26:54 +00:00
$query->where(fn($q)=>$q->whereNull('ignore_duplicate')
->orWhere('ignore_duplicate',FALSE));
$query
->where(function($q) {
$q->when($this->attributes['signature'],
fn($q)=>$q->where('signature','=',$this->attributes['signature']))
->orWhere('file_signature','=',$this->attributes['file_signature']); })
2019-12-14 11:29:54 +00:00
// Where the signature is the same
->orWhere(function($q) {
// Or they have the same time taken with the same camera
if ($this->attributes['created'] && $this->software_id) {
$q->where(fn($q)=>$q->where('created','=',$this->attributes['created'])
->orWhere('created_manual','=',$this->attributes['created']));
2019-12-14 11:29:54 +00:00
if (static::$includeSubSecTime)
$q->where('subsectime','=',Arr::get($this->attributes,'subsectime'));
$q->where('software_id','=',$this->attributes['software_id']);
} elseif ($this->attributes['created_manual'] && $this->software_id) {
$q->where(fn($q)=>$q->where('created','=',$this->attributes['created_manual'])
->orWhere('created_manual','=',$this->attributes['created_manual']));
if (static::$includeSubSecTime)
$q->where('subsectime','=',Arr::get($this->attributes,'subsectime'));
2019-12-14 11:29:54 +00:00
$q->where('software_id','=',$this->attributes['software_id']);
}
});
return $query;
2019-12-14 11:29:54 +00:00
}
2018-01-11 12:59:53 +00:00
/**
* Multimedia NOT duplicate.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeNotDuplicate($query)
{
return $query->where(
fn($q)=>$q->where('duplicate','<>',TRUE)
2020-01-06 09:01:04 +00:00
->orWhere('duplicate','=',NULL)
->orWhere(fn($q)=>$q->where('duplicate','=',TRUE)->where('ignore_duplicate','=',TRUE))
);
2018-01-11 12:59:53 +00:00
}
/**
* Multimedia NOT pending removal.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeNotRemove($query)
{
return $query->where(fn($q)=>$q->where('remove','<>',TRUE)->orWhere('remove','=',NULL));
2018-01-11 12:59:53 +00:00
}
/**
* Multimedia NOT scanned.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeNotScanned($query)
{
return $query->where(fn($q)=>$q->where('scanned','<>',TRUE)->orWhere('scanned','=',NULL));
2018-01-11 12:59:53 +00:00
}
/* ABSTRACTS */
abstract public function getObjectOriginal(string $property): mixed;
/* ATTRIBUTES */
2018-01-11 12:59:53 +00:00
/**
* Return the time the media was created on the device
*
* This will be (in priority order)
* + the value of created_manual (Carbon)
* + the value of created
*
* @param string|null $date
* @return Carbon|null
2018-01-11 12:59:53 +00:00
*/
public function getCreatedAttribute(string $date=NULL): ?Carbon
2018-01-11 12:59:53 +00:00
{
$result = $this->created_manual ?: ($date ? Carbon::create($date) : NULL);
if ($result && static::$includeSubSecTime)
$result->microseconds($this->subsectime*1000);
return $result ?: $this->getObjectOriginal('creation_date');
2018-01-11 12:59:53 +00:00
}
/**
* What device was the multimedia created on
*
* @return string
*/
public function getDeviceAttribute(): string
2019-12-14 11:29:54 +00:00
{
$result = '';
2019-12-15 10:08:33 +00:00
if ($this->software_id) {
if ($this->software->model_id) {
if ($this->software->model->make_id) {
$result .= $this->software->model->make->name;
}
2019-12-14 11:29:54 +00:00
2019-12-15 10:08:33 +00:00
$result .= ($result ? ' ' : '').$this->software->model->name;
}
2019-12-14 11:29:54 +00:00
$result .= ($result ? ' ' : '').$this->software->name;
2019-12-15 10:08:33 +00:00
}
2019-12-14 11:29:54 +00:00
return $result;
}
/**
* Return item dimensions
*/
public function getDimensionsAttribute(): string
{
return $this->width.'x'.$this->height;
}
/**
* Return the file size
*
* @return int|null
*/
public function getFileSizeAttribute(): ?int
{
return (! $this->isReadable()) ? NULL : filesize($this->file_name(FALSE));
}
public function getGPSAttribute(): ?string
{
return ($this->gps_lat && $this->gps_lon)
? sprintf('%s/%s',$this->gps_lat,$this->gps_lon)
: NULL;
}
/* METHODS */
2020-01-02 21:04:15 +00:00
/**
* Return the filename.
2024-10-04 01:08:18 +00:00
*
* If $short is TRUE, it is the RELATIVE filename that it should be called (and can be compared to $this->filename,
* to see if it is in the wrong place). This path (like filename) is without the DIR prefix, and DIR location.
* If $short is FALSE, it is the FULL path of the actual file (where $this->filename is the RELATIVE path,
* without the DIR prefix, and DIR location)
2020-01-02 21:04:15 +00:00
*
* @param bool $short
2020-01-02 21:04:15 +00:00
* @return string
*/
public function file_name(bool $short=TRUE): string
{
if ($short || preg_match('#^/#',$this->filename)) {
// If the date created is not set, the file name will be based on the ID of the file.
$file = sprintf('%s.%s',
(is_null($this->created)
? sprintf('UNKNOWN/%07s',$this->file_path_id())
: $this->created->format('Y/m/d-His').
($this->subsectime ? sprintf('_%03d',$this->subsectime) : '' ).
sprintf('-%05s',$this->id)),
$this->type()
);
2020-01-02 21:04:15 +00:00
return $file;
2020-01-02 21:04:15 +00:00
} else
return Storage::disk(self::fs)
->path($this->file_name_rel());
}
2024-10-04 01:08:18 +00:00
/**
* Return the path relative to our HTML root
*
* When $source is TRUE, this is the current filename with the DIR prefix added, without the DIR location,
* When $source is FALSE, this is the NEW filename, with the DIR prefix added, without the DIR location.
*
* @param bool $source
* @return string
*/
public function file_name_rel(bool $source=TRUE): string
{
return config(static::config.'.dir').DIRECTORY_SEPARATOR.($source ? $this->filename : $this->file_name());
2020-07-16 02:12:26 +00:00
}
2018-01-11 12:59:53 +00:00
/**
* Calculate a file path ID based on the id of the file
*
* We use this when we cannot determine the create time of the image
2018-01-11 12:59:53 +00:00
*/
2019-11-23 01:51:30 +00:00
public function file_path_id($sep=3,$depth=9): string
2018-01-11 12:59:53 +00:00
{
return trim(chunk_split(sprintf("%0{$depth}s",$this->id),$sep,'/'),'/');
}
2019-11-23 01:51:30 +00:00
/**
* Set values from the media object
2019-11-23 01:51:30 +00:00
*
* @return void
* @throws \Exception
2019-11-23 01:51:30 +00:00
*/
public function init(): void
2018-01-11 12:59:53 +00:00
{
foreach ($this->init as $item) {
switch ($item) {
case 'creation_date':
$this->created = $this->getObjectOriginal('creation_date');
break;
2019-11-23 01:51:30 +00:00
case 'gps':
$this->gps_lat = $this->getObjectOriginal('gps_lat');
$this->gps_lon = $this->getObjectOriginal('gps_lon');
break;
case 'heightwidth':
$this->height = $this->getObjectOriginal('height');
$this->width = $this->getObjectOriginal('width');
break;
case 'signature':
$this->signature = $this->getObjectOriginal('signature');
$this->file_signature = $this->getObjectOriginal('file_signature');
break;
case 'software':
$ma = NULL;
if ($x=$this->getObjectOriginal('make'))
$ma = Make::firstOrCreate([
'name'=>$x,
]);
$mo = \App\Models\Model::firstOrCreate([
'name'=>$this->getObjectOriginal('model') ?: NULL,
'make_id'=>$ma?->id,
]);
$so = Software::firstOrCreate([
'name'=>$this->getObjectOriginal('software') ?: NULL,
'model_id'=>$mo->id,
]);
$this->software_id = $so->id;
2024-09-16 13:26:54 +00:00
break;
case 'subsectime':
$this->subsectime = $this->getObjectOriginal($item);
break;
default:
throw new \Exception('Unknown init item: '.$item);
}
}
$this->custom_init();
2018-01-11 12:59:53 +00:00
}
/**
* Does the file require moving
2018-01-11 12:59:53 +00:00
*
* @return bool
2018-01-11 12:59:53 +00:00
*/
public function isMoveable(): bool
2018-01-11 12:59:53 +00:00
{
// No change to the name
$this->move_reason = 'Filenames match already';
if ($this->filename === $this->file_name())
2018-01-11 12:59:53 +00:00
return FALSE;
// If there is already a file in the target.
// @todo If the target file is to be deleted, we could move this file
$this->move_reason = 'Target file exists';
if (Storage::disk(self::fs)->exists($this->file_name()))
return FALSE;
2018-01-11 12:59:53 +00:00
// Test if the source is readable
$this->move_reason = 'Source is not readable';
if (! $this->isReadable())
return FALSE;
2018-01-11 12:59:53 +00:00
// Test if the dir is writable (so we can remove the file)
$this->move_reason = 'Source parent dir not writable';
2024-10-04 01:08:18 +00:00
if (! $this->isParentWritable(dirname($this->file_name_rel(TRUE))))
return FALSE;
2018-01-11 12:59:53 +00:00
// Test if the target dir is writable
// @todo The target dir may not exist yet, so we should check that a parent exists and is writable.
$this->move_reason = 'Target parent dir is not writable';
2024-10-04 01:08:18 +00:00
if (! $this->isParentWritable(dirname($this->file_name_rel(FALSE))))
return FALSE;
2018-01-11 12:59:53 +00:00
// Otherwise we can move it
$this->move_reason = NULL;
2018-01-11 12:59:53 +00:00
return TRUE;
}
public function isMoveableReason(): ?string
2018-01-11 12:59:53 +00:00
{
2024-09-16 13:26:54 +00:00
return $this->move_reason ?? NULL;
2018-01-11 12:59:53 +00:00
}
/**
2024-10-04 01:08:18 +00:00
* Determine if the parent dir is writable.
*
* $dir should be a relative path, with our DIR prefix (from dirname($this->file_name_rel()))
*
* @param string $dir
* @return bool
2018-01-11 12:59:53 +00:00
*/
public function isParentWritable(string $dir): bool
2018-01-11 12:59:53 +00:00
{
$path = Storage::disk(self::fs)->path($dir);
if (Storage::disk(self::fs)->exists($dir) && is_dir($path) && is_writable($path))
return TRUE;
2024-10-04 01:08:18 +00:00
elseif ($dir === '.')
return FALSE;
else
return ($this->isParentWritable(dirname($dir)));
2018-01-11 12:59:53 +00:00
}
/**
* Return if this source file is readable.
*
* @return bool
2018-01-11 12:59:53 +00:00
*/
public function isReadable(): bool
{
return is_readable($this->file_name(FALSE));
}
/**
* Get the id of the next record
*/
public function next(): ?self
{
return static::where('id','>',$this->id)
->orderby('id','ASC')
->first();
}
2019-11-23 01:51:30 +00:00
/**
* Get the id of the previous record
2019-11-23 01:51:30 +00:00
*/
public function previous(): ?self
2019-11-23 01:51:30 +00:00
{
return static::where('id','<',$this->id)
->orderby('id','DESC')
->first();
2019-11-23 01:51:30 +00:00
}
/**
* Display the media signature
2019-11-23 01:51:30 +00:00
*/
public function signature($short=FALSE)
2018-01-11 12:59:53 +00:00
{
return ($short && $this->signature)
2024-08-31 12:56:52 +00:00
? stringtrim($this->signature)
: $this->signature;
2018-01-11 12:59:53 +00:00
}
/**
* Determine if the image should be moved
*/
2019-12-14 11:29:54 +00:00
public function shouldMove(): bool
2018-01-11 12:59:53 +00:00
{
return $this->filename !== $this->file_name();
2018-01-11 12:59:53 +00:00
}
/**
* Find duplicate images based on some attributes of the current image
*/
private function list_duplicates($includeme=FALSE)
2018-01-11 12:59:53 +00:00
{
$o = static::select();
if ($this->id AND ! $includeme)
$o->where('id','!=',$this->id);
// Ignore photo's pending removal.
if (! $includeme)
$o->where(function($query)
{
2019-11-23 01:51:30 +00:00
$query->where('remove','<>',TRUE)
2018-01-11 12:59:53 +00:00
->orWhere('remove','=',NULL);
});
// Where the signalist_duplicatesture is the same
2018-01-11 12:59:53 +00:00
$o->where(function($query)
{
$query->where('signature','=',$this->signature);
// Or they have the same time taken with the same camera
if ($this->date_created AND ($this->model OR $this->make))
{
$query->orWhere(function($query)
{
$query->where('date_created','=',$this->date_created ? $this->date_created : NULL);
if (Schema::hasColumn($this->getTable(),'subsectime'))
2024-09-16 13:26:54 +00:00
$query->where('subsectime','=',$this->subsectime ?: NULL);
2018-01-11 12:59:53 +00:00
if (! is_null($this->model))
$query->where('model','=',$this->model);
if (! is_null($this->make))
$query->where('make','=',$this->make);
});
}
});
return $o->get();
}
2019-11-08 12:51:47 +00:00
}