-
Notifications
You must be signed in to change notification settings - Fork 13
/
Plugin.pm
496 lines (414 loc) · 12.8 KB
/
Plugin.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package Plugins::MixCloud::Plugin;
# Plugin to stream audio from Mixcloud
#
# Released under GNU General Public License version 2 (GPLv2)
# Written by Christian Mueller,
# See file LICENSE for full license details
use strict;
use utf8;
use vars qw(@ISA);
use URI::Escape;
use JSON::XS::VersionOneAndTwo;
use LWP::Simple;
use LWP::UserAgent;
use File::Spec::Functions qw(:ALL);
use List::Util qw(min max);
use Slim::Utils::Strings qw(string);
use Slim::Utils::Prefs;
use Slim::Utils::Log;
use Date::Parse;
use Data::Dumper;
use Plugins::MixCloud::ProtocolHandler;
my $log;
my $compat;
my $CLIENT_ID = "Js32JMBmKGRg4zjHrY";
my $CLIENT_SECRET = "E3uDXKnsMdWjxJMRtkY3e52JZfUAGnwM";
my $token = "";
my %METADATA_CACHE= {};
BEGIN {
$log = Slim::Utils::Log->addLogCategory({
'category' => 'plugin.mixcloud',
'defaultLevel' => 'DEBUG',
'description' => string('PLUGIN_MIXCLOUD'),
});
if (exists &Slim::Control::XMLBrowser::findAction) {
$log->info("using server XMLBrowser");
require Slim::Plugin::OPMLBased;
push @ISA, 'Slim::Plugin::OPMLBased';
} else {
$log->info("using packaged XMLBrowser: Slim76Compat");
require Slim76Compat::Plugin::OPMLBased;
push @ISA, 'Slim76Compat::Plugin::OPMLBased';
$compat = 1;
}
}
my $prefs = preferences('plugin.mixcloud');
$prefs->init({ apiKey => "", playmethod => "stream" });
sub getToken {
my ($callback) = shift;
if ($prefs->get('apiKey')) {
my $tokenurl = "https://www.mixcloud.com/oauth/access_token?client_id=".$CLIENT_ID."&redirect_uri=http://findechris.github.io/lms_mixcloud/app.html&client_secret=".$CLIENT_SECRET."&code=".$prefs->get('apiKey');
$log->info("gettokenurl:".$tokenurl);
Slim::Networking::SimpleAsyncHTTP->new(
sub {
my $http = shift;
my $json = eval { from_json($http->content) };
if ($json->{"access_token"}) {
$token = $json->{"access_token"};
$log->info("token:".$token);
}
$callback->({token=>$token});
},
sub {
$log->warn("error: $_[1]");
$callback->({});
},
)->get($tokenurl);
}else{
$callback->({});
}
}
sub _makeMetadata {
my ($json) = shift;
my $icon = "";
if (defined $json->{'pictures'}->{'medium'}) {
$icon = $json->{'pictures'}->{'medium'};
#$icon =~ s/-large/-t500x500/g;
}
#my ($ss,$mm,$hh,$day,$month,$year,$zone,$help) = strptime($json->{'created_time'});
my $dminutes = int(int($json->{'audio_length'})/60);
my $dhours = int($dminutes/60);
my $dminutesrest = int($dminutes-$dhours*60);
my $DATA = {
duration => $dhours."h".$dminutesrest."m",
name => $json->{'name'}.($json->{'created_time'}?" : ".substr($json->{'created_time'},0,10):""),
title => $json->{'name'},
#label => substr($json->{'created_time'},0,10),
artists => $json->{'user'}->{'username'},
artist => $json->{'user'}->{'username'},
album => $json->{'user'}->{'name'},
play => "mixcloud:/" . $json->{'key'},
bitrate => '320/70',
#url => \&_fetchMeta,
passthrough => [ { key => $json->{'key'}} ],
type => 'audio',
#line1 => $json->{'name'},
#line2 => $json->{'name'},
icon => $icon,
image => $icon,
cover => $icon,
};
return $DATA;
}
sub _fetchMeta {
my ($client, $callback, $args, $passDict) = @_;
my $fetchURL = "http://api.mixcloud.com" . $passDict->{"key"} ;
$log->debug("fetching meta for $fetchURL");
Slim::Networking::SimpleAsyncHTTP->new(
sub {
my $track = eval { from_json($_[0]->content) };
if ($@) {
$log->warn($@);
}
$log->debug("got meta for $fetchURL");
my $meta ={name => "hallo"};# _makeMetadata($track);
#$meta->{'name'} = "hallo";
#%meta{"items"} = [_makeMetadata($track)];
$callback->(_makeMetadata($track));
},
sub {
$log->warn("error fetching track data: $_[1]");
},
{ timeout => 35 },
)->get($fetchURL);
}
sub _parseTracks {
my ($json, $menu) = @_;
my $data = $json->{'data'};
for my $entry (@$data) {
push @$menu, _makeMetadata($entry);
}
}
sub tracksHandler {
my ($client, $callback, $args, $passDict) = @_;
my $index = ($args->{'index'} || 0); # ie, offset
my $quantity = $args->{'quantity'} || 200;
my $searchType = $passDict->{'type'};
my $parser = $passDict->{'parser'} || \&_parseTracks;
my $params = $passDict->{'params'} || '';
$log->warn('search type: ' . $searchType);
$log->warn("index: " . $index);
$log->warn("quantity: " . $quantity);
my $menu = [];
# fetch in stages as api only allows 50 items per response, cli clients require $quantity responses which can be more than 50
my $fetch;
# FIXME: this could be sped up by performing parallel requests once the number of responses is known??
$fetch = sub {
# in case we've already fetched some of this page, keep going
my $i = $index + scalar @$menu;
$log->warn("i: " . $i);
my $max = min($quantity - scalar @$menu, 200); # api allows max of 200 items per response
$log->warn("max: " . $max);
my $method = "http";
my $uid = $passDict->{'uid'} || '';
my $resource = "";
if ($searchType eq 'hot') {
$resource = "popular/hot";
}
if ($searchType eq 'popular') {
$resource = "popular";
}
if ($searchType eq 'new') {
$resource = "new";
}
if ($searchType eq 'categories') {
if ($params eq "") {
$resource = "categories";
}else{
$resource = $params;
$params = "";
}
}
if ($searchType eq 'search') {
$resource = "search";
$params = "q=".$args->{'search'}."&type=cloudcast";
}
if ($searchType eq 'usersearch') {
$resource = "search";
$params = "q=".$args->{'search'}."&type=user";
}
if ($searchType eq 'tags') {
if ($params eq "") {
$resource = "search";
$params = "q=".$args->{'search'}."&type=tag";
}else{
$resource = $params;
$params = "";
}
}
if ($searchType eq 'following' || $searchType eq 'favorites' || $searchType eq 'cloudcasts' || $searchType eq 'user') {
$resource = $params;
$params = '';
if (substr($resource,0,2) eq 'me') {
if ($token ne "") {
$method = "https";
$params .= "&access_token=" . $token;
}
}
}
my $queryUrl = "$method://api.mixcloud.com/$resource?offset=$i&limit=$quantity&" . $params;
#$queryUrl= "http://192.168.56.1/json/cloudcasts.json";
$log->warn("fetching: $queryUrl");
Slim::Networking::SimpleAsyncHTTP->new(
sub {
my $http = shift;
my $json = eval { from_json($http->content) };
$parser->($json, $menu);
# max offset = 8000, max index = 200 sez
my $total = 8000 + $quantity;
if (exists $passDict->{'total'}) {
$total = $passDict->{'total'}
}
$log->info("this page: " . scalar @$menu . " total: $total");
# TODO: check this logic makes sense
if (scalar @$menu < $quantity) {
$total = $index + @$menu;
$log->debug("short page, truncate total to $total");
}
if ($searchType eq 'user') {
$callback->($menu);
}else{
$callback->({
items => $menu,
offset => $index,
total => $total,
});
}
},
sub {
$log->warn("error: $_[1]");
$callback->([ { name => $_[1], type => 'text' } ]);
},
)->get($queryUrl);
};
$fetch->();
}
sub urlHandler {
my ($client, $callback, $args) = @_;
my $url = $args->{'search'};
$url =~ s/ com/.com/;
$url =~ s/www /www./;
my ($trackhome) = $url =~ m{^http://www.mixcloud.com/(.*)$};
my $queryUrl = "http://api.mixcloud.com/" . $trackhome ;
my $fetch = sub {
Slim::Networking::SimpleAsyncHTTP->new(
sub {
my $http = shift;
my $json = eval { from_json($http->content) };
$callback->({
items => [ _makeMetadata($json) ]
});
},
sub {
$log->warn("error: $_[1]");
$callback->([ { name => $_[1], type => 'text' } ]);
},
)->get($queryUrl);
};
$fetch->();
}
sub _parseCategories {
my ($json, $menu) = @_;
my $i = 0;
my $data = $json->{'data'};
for my $entry (@$data) {
my $name = $entry->{'name'};
my $format = $entry->{'format'};
my $slug = $entry->{'slug'};
my $url = $entry->{'url'};
my $key = substr($entry->{'key'},1)."cloudcasts/";
push @$menu, {
name => $name,
type => 'link',
url => \&tracksHandler,
passthrough => [ { type => 'categories', params => $key} ]
};
}
}
sub _parseTags {
my ($json, $menu) = @_;
my $i = 0;
my $data = $json->{'data'};
for my $entry (@$data) {
my $name = $entry->{'name'};
my $format = $entry->{'format'};
my $slug = $entry->{'slug'};
my $url = $entry->{'url'};
my $key = substr($entry->{'key'},1);
push @$menu, {
name => $name,
type => 'link',
url => \&_tagHandler,
passthrough => [ { params => $key} ]
};
}
}
sub _parseUsers {
my ($json, $menu) = @_;
my $i = 0;
my $data = $json->{'data'};
for my $entry (@$data) {
my $name = $entry->{'name'};
my $username = $entry->{'username'};
my $key = substr($entry->{'key'},1);
my $icon = "";
if (defined $json->{'pictures'}->{'medium'}) {
$icon = $json->{'pictures'}->{'medium'};
}
push @$menu, {
name => $name,
type => 'link',
url => \&tracksHandler,
icon => $icon,
image => $icon,
cover => $icon,
passthrough => [ { type=>'user', params => $key,parser=>\&_parseUser} ]
};
}
}
sub _parseUser {
my ($json, $menu) = @_;
my $key = substr($json->{'key'},1);
push(@$menu,
{ name => string('PLUGIN_MIXCLOUD_FOLLOWING')." (".$json->{'following_count'}.")", type => 'link',
url => \&tracksHandler, passthrough => [ { type => 'following',params => $key."following",parser => \&_parseUsers } ] }
);
push(@$menu,
{ name => string('PLUGIN_MIXCLOUD_FAVORITES')." (".$json->{'favorite_count'}.")", type => 'link',
url => \&tracksHandler, passthrough => [ { type => 'favorites',params => $key."favorites" } ] }
);
push(@$menu,
{ name => string('PLUGIN_MIXCLOUD_CLOUDCASTS')." (".$json->{'cloudcast_count'}.")", type => 'link',
url => \&tracksHandler, passthrough => [ { type => 'cloudcasts',params => $key."cloudcasts"} ] }
);
}
sub _tagHandler {
my ($client, $callback, $args, $passDict) = @_;
my $params = $passDict->{'params'} || '';
my $callbacks = [
{ name => string('PLUGIN_MIXCLOUD_NEW'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'tags' ,params=>$params.'new/' } ], },
{ name => string('PLUGIN_MIXCLOUD_POPULAR'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'tags' ,params=>$params.'popular/'} ], },
{ name => string('PLUGIN_MIXCLOUD_HOT'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'tags' ,params=>$params.'hot/' } ], },
];
$callback->($callbacks);
}
sub initPlugin {
my $class = shift;
$class->SUPER::initPlugin(
feed => \&toplevel,
tag => 'mixcloud',
menu => 'radios',
is_app => $class->can('nonSNApps') ? 1 : undef,
weight => 10,
);
if (!$::noweb) {
require Plugins::MixCloud::Settings;
Plugins::MixCloud::Settings->new;
}
Slim::Formats::RemoteMetadata->registerProvider(
match => qr/mixcloud/,
func => \&_fetchMeta,
);
Slim::Player::ProtocolHandlers->registerHandler(
mixcloud => 'Plugins::MixCloud::ProtocolHandler'
);
}
sub shutdownPlugin {
my $class = shift;
}
sub getDisplayName { 'PLUGIN_MIXCLOUD' }
sub playerMenu { shift->can('nonSNApps') ? undef : 'RADIO' }
sub toplevel {
my ($client, $callback, $args) = @_;
my $callbacks = [
{ name => string('PLUGIN_MIXCLOUD_HOT'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'hot' } ], },
{ name => string('PLUGIN_MIXCLOUD_NEW'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'new' } ], },
{ name => string('PLUGIN_MIXCLOUD_POPULAR'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'popular' } ], },
{ name => string('PLUGIN_MIXCLOUD_CATEGORIES'), type => 'link',
url => \&tracksHandler, passthrough => [ {type=>'categories',parser => \&_parseCategories } ], },
{ name => string('PLUGIN_MIXCLOUD_MYSEARCH'), type => 'link',
url =>sub{
my ($client, $callback, $args) = @_;
my $searchcallbacks = [
{ name => string('PLUGIN_MIXCLOUD_SEARCH'), type => 'search',
url => \&tracksHandler, passthrough => [ { type => 'search' } ], },
{ name => string('PLUGIN_MIXCLOUD_TAGS'), type => 'search',
url => \&tracksHandler, passthrough => [ { type => 'tags',parser => \&_parseTags } ], },
{ name => string('PLUGIN_MIXCLOUD_SEARCH_USER'), type => 'search',
url => \&tracksHandler, passthrough => [ { type => 'usersearch',parser => \&_parseUsers } ], }
];
$callback->($searchcallbacks);
}, passthrough => [ { type => 'search' } ], }
];
getToken(
sub{
if ($token ne '') {
push(@$callbacks,
{ name => string('PLUGIN_MIXCLOUD_MYMIXCLOUD'), type => 'link',
url => \&tracksHandler, passthrough => [ { type=>'user', params => 'me/',parser=>\&_parseUser} ] }
);
}
push(@$callbacks,
{ name => string('PLUGIN_MIXCLOUD_URL'), type => 'search', url => \&urlHandler }
);
$callback->($callbacks);
}
)
}
1;