forked from michaelherger/MusicArtistInfo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalFile.pm
480 lines (371 loc) · 12.9 KB
/
LocalFile.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package Plugins::MusicArtistInfo::LocalFile;
use strict;
use File::Basename qw(dirname basename);
use File::Next;
use File::Spec::Functions qw(catdir);
use Digest::MD5 qw(md5_hex);
use HTTP::Status qw(
RC_FORBIDDEN
RC_PRECONDITION_FAILED
RC_UNAUTHORIZED
RC_MOVED_PERMANENTLY
RC_NOT_FOUND
RC_METHOD_NOT_ALLOWED
RC_OK
RC_NOT_MODIFIED
);
use Path::Class ();
use Slim::Menu::AlbumInfo;
use Slim::Menu::FolderInfo;
use Slim::Menu::TrackInfo;
use Slim::Utils::Cache;
use Slim::Utils::Strings qw(string cstring);
use Slim::Utils::Log;
use Slim::Utils::Misc;
use Slim::Utils::Prefs;
use Slim::Web::Pages;
use Plugins::MusicArtistInfo::Common qw(CLICOMMAND);
my $log = logger('plugin.musicartistinfo');
my $prefs = preferences('plugin.musicartistinfo');
my $cache = Slim::Utils::Cache->new;
my $URL_PARSER_RE = qr{mai/localfile/([a-f\d]+)/(.*)$};
sub init {
# |requires Client
# | |is a Query
# | | |has Tags
# | | | |Function to call
# C Q T F
Slim::Control::Request::addDispatch([CLICOMMAND, 'localfiles'], [0, 1, 1, \&getLocalFileWeblinksCLI]);
Slim::Menu::AlbumInfo->registerInfoProvider( morefileinfo => (
func => \&albumInfoHandler,
after => 'moreartwork',
) );
Slim::Menu::FolderInfo->registerInfoProvider( morefileinfo => (
func => \&folderInfoHandler,
) );
Slim::Menu::TrackInfo->registerInfoProvider( morefileinfo => (
func => \&trackInfoHandler,
after => 'moreartwork',
) );
Slim::Web::Pages->addRawFunction(
$URL_PARSER_RE,
\&_proxyHandler,
);
}
sub getAlbumReview {
my ( $class, $client, $params, $args ) = @_;
my $review;
if ($args->{album_id}) {
my $dbh = Slim::Schema->dbh;
my $sth = $dbh->prepare_cached(qq(
SELECT tracks.url
FROM tracks
WHERE tracks.album = ? AND tracks.url like 'file://%'
));
$sth->execute($args->{album_id});
$review = _getInfoFileForTrackFromDb($client, $sth, 'review', ['album.nfo', 'review.html?', 'review.txt', 'albumreview.html?', 'albumreview.txt'], $params);
}
if ( !$review && $args->{album} && $args->{artist} && (my $reviewFolder = $prefs->get('reviewFolder')) ) {
my $artists = Plugins::MusicArtistInfo::Common::getLocalnameVariants($args->{artist});
my $candidates = Plugins::MusicArtistInfo::Common::getLocalnameVariants($args->{album});
my $folders = [ map { catdir($reviewFolder, $_) } @$artists ];
$review = _getInfoFileFromFolder($client, $folders, 'review', ['nfo', 'html', 'htm', 'txt'], $candidates, $params);
}
return $review;
}
sub getBiography {
my ( $class, $client, $params, $args ) = @_;
return unless $args->{artist} || $args->{artist_id};
my ($sql, $var);
if ($args->{artist_id}) {
$sql = qq(
SELECT tracks.url
FROM contributor_track
JOIN tracks ON tracks.id = contributor_track.track
WHERE contributor_track.contributor = ? AND contributor_track.role IN (1,5) AND tracks.url like 'file://%'
);
$var = $args->{artist_id};
}
else {
$sql = qq(
SELECT tracks.url
FROM contributors
JOIN contributor_track ON contributor_track.contributor = contributors.id AND contributor_track.role IN (1,5)
JOIN tracks ON tracks.id = contributor_track.track
WHERE contributors.namesearch = ? AND tracks.url like 'file://%'
);
$var = Slim::Utils::Unicode::utf8decode_locale($args->{artist});
$var = Slim::Utils::Text::ignoreCaseArticles($var, 1);
}
# get all tracks where this artist is main contributor
# we'll use the file paths as starting points to find biography etc. files
my $dbh = Slim::Schema->dbh;
my $sth = $dbh->prepare_cached($sql);
$sth->execute($var);
my $biography = _getInfoFileForTrackFromDb($client, $sth, 'biography', ['artist.nfo', 'biography.html?', 'bio.html?', 'biography.txt', 'bio.txt'], $params);
if ( !$biography && $args->{artist} && (my $bioFolder = $prefs->get('bioFolder')) ) {
my $candidates = Plugins::MusicArtistInfo::Common::getLocalnameVariants($args->{artist});
$biography = _getInfoFileFromFolder($client, $bioFolder, 'biography', ['nfo', 'html', 'htm', 'txt'], $candidates, $params);
}
return $biography;
}
sub _getInfoFileForTrackFromDb {
my ( $client, $sth, $key, $candidates, $params ) = @_;
my %seen;
my %files;
while ( my ($url) = $sth->fetchrow_array ) {
my $dir = dirname(Slim::Utils::Misc::pathFromFileURL($url));
next if $seen{$dir}++;
foreach ( @{_findTextFiles($dir)} ) {
$files{catdir($_->{path}, $_->{file})}++
}
}
return unless keys %files;
# our order of priority for candidate files...
my $file;
foreach my $candidate ( @$candidates ) {
($file) = grep /$candidate$/i, keys %files;
last if $file;
}
return _getInfoFileContent($client, $file, $key, $params);
}
sub _getInfoFileFromFolder {
my ($client, $folders, $key, $extensions, $candidates, $params) = @_;
$folders = [$folders] unless ref $folders;
my $file;
foreach my $folder ( @$folders ) {
$file = Plugins::MusicArtistInfo::Common::fileInFolder($folder, $extensions, @$candidates);
last if $file;
}
return _getInfoFileContent($client, $file, $key, $params);
}
sub _getInfoFileContent {
my ($client, $file, $key, $params) = @_;
if ($file && -f $file) {
main::DEBUGLOG && $log->debug("Found $key on local file system: $file");
my $content = getFileContent($client, undef, $params, { path => $file });
# .nfo files are structured XML. They would return a menu, not the biography/review only.
($content) = grep { lc($_->{name}) eq $key } @$content if $file =~ /\.nfo$/i && scalar @$content > 1;
$content = $content->{items} if $content && ref $content && ref $content eq 'HASH' && $content->{items};
return $content;
}
return;
}
sub albumInfoHandler {
my ( $client, $url, $album ) = @_;
# try to grab the first album track to find it's folder location
return trackInfoHandler($client, undef, $album->tracks->first);
}
sub folderInfoHandler {
my ( $client, $tags ) = @_;
return unless $tags->{folder_id};
return trackInfoHandler($client, undef, Slim::Schema->find('Track', $tags->{folder_id}), undef, $tags);
}
sub trackInfoHandler {
my ( $client, $url, $track, $remoteMeta, $tags ) = @_;
# only deal with local media
$url = $track->url if !$url && $track;
$url =~ s/^tmp:/file:/ if $url;
return unless $url && $url =~ /^file:\/\//i;
my $path = Slim::Utils::Misc::pathFromFileURL($url);
if (! -d $path) {
$path = dirname( $path );
}
my $files = _findTextFiles($path);
return unless scalar @$files;
# XMLBrowser for Jive can't handle weblinks - need custom handling there to show files in the browser.
if ( Plugins::MusicArtistInfo::Plugin->canWeblink($client) ) {
return {
name => cstring($client, 'PLUGIN_MUSICARTISTINFO_LOCAL_FILES'),
itemActions => {
items => {
command => [ CLICOMMAND, 'localfiles' ],
fixedParams => {
folder => Slim::Utils::Unicode::utf8decode_locale($path)
},
},
},
}
}
my $items = [ map {
my $file = Slim::Utils::Unicode::utf8decode_locale($_->{file});
{
type => 'link',
name => $file,
weblink => _proxiedUrl($_->{path}, $file),
url => \&getFileContent,
passthrough => [{
path => catdir($_->{path}, $file)
}]
};
} @$files ];
return {
name => cstring($client, 'PLUGIN_MUSICARTISTINFO_LOCAL_FILES'),
type => 'outline',
items => $items,
};
}
sub getLocalFileWeblinksCLI {
my $request = shift;
my $client = $request->client;
if ($request->isNotQuery([[CLICOMMAND], ['localfiles']])) {
$request->setStatusBadDispatch();
return;
}
$request->setStatusProcessing();
my $path = $request->getParam('folder');
my $files = $path ? _findTextFiles(Slim::Utils::Unicode::utf8encode($path)) : [];
my $i = 0;
if (!scalar @$files) {
$request->addResult('window', {
textArea => cstring($client, 'EMPTY'),
});
$i++;
}
else {
my $web_root = 'http://' . Slim::Utils::IPDetect::IP() . ':' . preferences('server')->get('httpport');
foreach (@$files) {
my $file = Slim::Utils::Unicode::utf8decode_locale($_->{file});
$request->addResultLoop('item_loop', $i, 'text', $file );
$request->addResultLoop('item_loop', $i, 'weblink', $web_root . _proxiedUrl($_->{path}, $file));
$i++;
}
}
$request->addResult('count', $i);
$request->addResult('offset', 0);
$request->setStatusDone();
}
sub _proxiedUrl {
my ($path, $file) = @_;
my $pathHash = md5_hex($path);
$cache->set( $pathHash, $path, 3600 );
return "/mai/localfile/$pathHash/" . URI::Escape::uri_escape_utf8($file);
}
# search folder for supported text files, and parent folders for a biography.* file
sub _findTextFiles {
my $previous = shift;
my $pathObj = Path::Class::dir($previous);
my $i = 0;
my $mask = '';
my @files;
my $TEXTFILES = '(?:artist|album|review|albumreview|bio|biogra.*|credits|notes)';
my $EXTENSIONS = '(?:pdf|txt|html|nfo|md)';
while ( $i == 0 || $previous ne $pathObj->parent->stringify ) {
if ($i == 0) {
my $iterator = File::Next::files({
file_filter => sub { /^[^.].*\.$EXTENSIONS$/i }
}, $previous);
while ( defined (my $file = $iterator->()) ) {
# don't walk up the tree if we've found a biography or other
$i = 999 if /$TEXTFILES\./i;
push @files, {
file => basename($file),
path => dirname($file),
};
}
}
else {
opendir(DIR, $previous) || return [];
push @files, map {
# don't walk up the tree if we've found a biography or other
$i = 999 if /$TEXTFILES\./i;
{
file => $_,
path => $previous,
}
} grep {
$_ !~ /^\._/o
} grep /$mask\.$EXTENSIONS$/i, readdir(DIR);
closedir(DIR);
}
$pathObj = $pathObj->parent;
$previous = $pathObj->stringify;
# don't walk up too far - most likely an artist folder is not far from the artist's album folder
last if ++$i > 3;
# we don't show all files in parent folders, only a reasonable selection
$mask = $TEXTFILES;
}
@files = sort { lc($a->{file}) cmp lc($b->{file}) } @files;
return \@files;
}
sub getFileContent {
my ($client, $cb, $params, $args) = @_;
my $path = $args->{path} || '';
my $type = __PACKAGE__->mimeType($path);
$params ||= {};
my $content = cstring($client, 'PLUGIN_MUSICARTISTINFO_UNSUPPORTED_CT');
my $items;
if ( $path =~ /\.nfo$/i ) {
require Plugins::MusicArtistInfo::Parser::NFO;
$items = Plugins::MusicArtistInfo::Parser::NFO->renderAsOPML($client, $path, $params);
$content = '';
}
elsif ( $path =~ /\.md$/i ) {
require Plugins::MusicArtistInfo::Parser::Markdown;
$content = Plugins::MusicArtistInfo::Parser::Markdown->parse($path);
}
elsif ( $type =~ /html/ && !Plugins::MusicArtistInfo::Plugin->isWebBrowser($client, $params) ) {
require HTML::FormatText;
$content = HTML::FormatText->format_file(
$path,
leftmargin => 0,
);
}
elsif ( $type =~ /text/ ) {
require File::Slurp;
$content = File::Slurp::read_file($path);
}
if ($content) {
# we're going to assume that HTML nowadays is in utf8...
$content = Slim::Utils::Unicode::utf8on($content) if $type =~ /html/;
$content = Slim::Utils::Unicode::utf8decode($content);
$items = Plugins::MusicArtistInfo::Plugin->textAreaItem($client, $params->{isButton}, $content);
}
if ($cb) {
$cb->({
items => $items
});
}
else {
return $items;
}
}
sub _proxyHandler {
my ( $httpClient, $response ) = @_;
return unless $httpClient->connected;
my $request = $response->request;
my ($pathHash, $file) = $request->uri->path =~ $URL_PARSER_RE;
my $path = $cache->get($pathHash);
$file = URI::Escape::uri_unescape($file || '');
$path = catdir($path, $file);
main::INFOLOG && $log->info("Getting file: $path");
if ( !-f $path ) {
$response->code(RC_NOT_FOUND);
$response->content_type('text/html');
$response->header('Connection' => 'close');
$response->content_ref(Slim::Web::HTTP::filltemplatefile('html/errors/404.html', { path => $request->uri->path }));
$httpClient->send_response($response);
Slim::Web::HTTP::closeHTTPSocket($httpClient);
return;
}
if ( $path =~ /\.nfo$/i ) {
require Plugins::MusicArtistInfo::Parser::NFO;
return Plugins::MusicArtistInfo::Parser::NFO->renderAsHTML($httpClient, $response, $path);
}
elsif ( $path =~ /\.md$/i ) {
require Plugins::MusicArtistInfo::Parser::Markdown;
return Plugins::MusicArtistInfo::Parser::Markdown->renderAsHTML($httpClient, $response, $path);
}
elsif ( $path =~ /\.html?$/i ) {
require Plugins::MusicArtistInfo::Parser::HTML;
return Plugins::MusicArtistInfo::Parser::HTML->renderAsHTML($httpClient, $response, $path);
}
$response->code(RC_OK);
Slim::Web::HTTP::sendStreamingFile( $httpClient, $response, __PACKAGE__->mimeType($path), $path, '', 'noAttachment' );
return;
}
# this should be in Slim::Music::Info, but needs a track object there. Stupid.
sub mimeType {
return $Slim::Music::Info::types{ Slim::Music::Info::typeFromPath($_[1]) } || 'application/octet-stream';
}
1;