forked from michaelherger/lms-plugin-tidal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProtocolHandler.pm
292 lines (228 loc) · 7.67 KB
/
ProtocolHandler.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
package Plugins::TIDAL::ProtocolHandler;
use strict;
use JSON::XS::VersionOneAndTwo;
use URI::Escape qw(uri_escape_utf8);
use Scalar::Util qw(blessed);
use MIME::Base64 qw(encode_base64 decode_base64);
use Slim::Networking::SqueezeNetwork;
use Slim::Utils::Cache;
use Slim::Utils::Log;
use Slim::Utils::Misc;
use Slim::Utils::Prefs;
use Slim::Utils::Timers;
use Plugins::TIDAL::Plugin;
use Plugins::TIDAL::API;
use base qw(Slim::Player::Protocols::HTTPS);
my $prefs = preferences('plugin.tidal');
my $serverPrefs = preferences('server');
my $log = logger('plugin.tidal');
my $cache = Slim::Utils::Cache->new;
# https://tidal.com/browse/track/95570766
# https://tidal.com/browse/album/95570764
# https://tidal.com/browse/playlist/5a36919b-251c-4fa7-802c-b659aef04216
my $URL_REGEX = qr{^https://(?:\w+\.)?tidal.com/(?:browse/)?(track|playlist|album|artist|mix)/([a-z\d-]+)}i;
my $URI_REGEX = qr{^tidal://(playlist|album|artist|mix|):?([0-9a-z-]+)}i;
Slim::Player::ProtocolHandlers->registerURLHandler($URL_REGEX, __PACKAGE__);
Slim::Player::ProtocolHandlers->registerURLHandler($URI_REGEX, __PACKAGE__);
# many method do not need override like isRemote, shouldLoop ...
sub canSkip { 1 } # where is this called?
sub canSeek { 1 }
sub getFormatForURL {
my ($class, $url) = @_;
return if $url =~ m{^tidal://.+:.+};
return Plugins::TIDAL::API::getFormat();
}
sub formatOverride {
my ($class, $song) = @_;
my $format = $song->pluginData('format') || Plugins::TIDAL::API::getFormat;
return $format =~ s/mp4/aac/r;
}
# some TIDAL streams are compressed in a way which causes stutter on ip3k based players
sub forceTranscode {
my ($self, $client, $format) = @_;
return $format eq 'flc' && $client->model =~ /squeezebox|boom|transporter|receiver/;
}
# To support remote streaming (synced players), we need to subclass Protocols::HTTP
sub new {
my $class = shift;
my $args = shift;
my $client = $args->{client};
my $song = $args->{song};
my $streamUrl = $song->streamUrl() || return;
main::DEBUGLOG && $log->debug( 'Remote streaming TIDAL track: ' . $streamUrl );
my $sock = $class->SUPER::new( {
url => $streamUrl,
song => $args->{song},
client => $client,
} ) || return;
return $sock;
}
# Avoid scanning
sub scanUrl {
my ( $class, $url, $args ) = @_;
$args->{cb}->( $args->{song}->currentTrack() );
}
# Source for AudioScrobbler
sub audioScrobblerSource {
my ( $class, $client, $url ) = @_;
# P = Chosen by the user
return 'P';
}
sub explodePlaylist {
my ( $class, $client, $url, $cb ) = @_;
my ($type, $id) = $url =~ $URL_REGEX;
if ( !($type && $id) ) {
($type, $id) = $url =~ $URI_REGEX;
}
if ($id) {
my $method = 'track';
if ($type eq 'playlist') {
$method = 'playlist';
}
elsif ($type eq 'album') {
$method = 'albumTracks';
}
elsif ($type eq 'artist') {
$method = 'artistTracks';
}
elsif ($type eq 'mix') {
$method = 'mix';
}
main::INFOLOG && $log->is_info && $log->info("Getting $url: method: $method, id: $id");
Plugins::TIDAL::Plugin::getAPIHandler($client)->$method(sub {
my $tracks = shift;
if ($tracks) {
$tracks = [ $tracks ] if $method eq 'track';
$tracks = [ map { "tidal://$_->{id}." . Plugins::TIDAL::API::getFormat() } @$tracks ];
}
main::INFOLOG && $log->is_info && $log->info("Got track list: " . Data::Dump::dump($tracks));
$cb->($tracks);
}, $id);
}
else {
$cb->([]);
}
}
sub _gotTrackError {
my ( $error, $errorCb ) = @_;
main::DEBUGLOG && $log->debug("Error during getTrackInfo: $error");
$errorCb->($error);
}
sub getNextTrack {
my ( $class, $song, $successCb, $errorCb ) = @_;
my $client = $song->master();
my $url = $song->track()->url;
# Get track URL for the next track
my $trackId = _getId($url);
if (!$trackId) {
$log->error("can't get trackId");
return;
}
Plugins::TIDAL::Plugin::getAPIHandler($client)->getTrackUrl(sub {
my $response = shift;
# no DASH or other for now
if ($response->{manifestMimeType} !~ m|application/vnd.tidal.bt|) {
return _gotTrackError("only plays streams $response->{manifestMimeType}", $errorCb);
}
my $manifest = eval { from_json(decode_base64($response->{manifest})) };
return _gotTrackError($@, $errorCb) if $@;
my $streamUrl = $manifest->{urls}[0];
my ($format) = $manifest->{mimeType} =~ m|audio/(\w+)|;
$format =~ s/flac/flc/;
# this should not happen
if ($format ne Plugins::TIDAL::API::getFormat) {
$log->warn("did not get the expected format for $trackId ($format <> " . Plugins::TIDAL::API::getFormat() . ')');
$song->pluginData(format => $format);
}
# main::INFOLOG && $log->info("got $format track at $streamUrl");
$song->streamUrl($streamUrl);
# now try to acquire the header for seeking and various details
Slim::Utils::Scanner::Remote::parseRemoteHeader(
$song->track, $streamUrl, $format,
sub {
# update what we got from parsing actual stream and update metadata
$song->pluginData('bitrate', sprintf("%.0f" . Slim::Utils::Strings::string('KBPS'), $song->track->bitrate/1000));
$client->currentPlaylistUpdateTime( Time::HiRes::time() );
Slim::Control::Request::notifyFromArray( $client, [ 'newmetadata' ] );
$successCb->();
},
sub {
my ($self, $error) = @_;
$log->warn( "could not find $format header $error" );
$successCb->();
}
);
}, $trackId,
{
audioquality => $prefs->get('quality'),
playbackmode => 'STREAM',
assetpresentation => 'FULL',
});
main::DEBUGLOG && $log->is_debug && $log->debug("Getting next track playback info for $url");
}
=comment
# URL used for CLI trackinfo queries
sub trackInfoURL {
my ( $class, $client, $url ) = @_;
my ($trackId) = _getStreamParams( $url );
# SN URL to fetch track info menu
my $trackInfoURL = Slim::Networking::SqueezeNetwork->url(
'/api/wimp/v1/opml/trackinfo?trackId=' . $trackId
);
return $trackInfoURL;
}
=cut
my @pendingMeta = ();
sub getMetadataFor {
my ( $class, $client, $url ) = @_;
return {} unless $url;
my $trackId = _getId($url);
my $meta = $cache->get( 'tidal_meta_' . ($trackId || '') );
# if metadata is in cache, we just need to add bitrate
if ($meta) {
# TODO - remove if we decide to move to our own cache file which we can version
$meta->{artist} = $meta->{artist}->{name} if ref $meta->{artist};
my $song = $client->playingSong();
if ($song && ($song->track->url eq $url || $song->currentTrack->url eq $url)) {
$meta->{bitrate} = $song->pluginData('bitrate') || 'n/a';
}
return $meta;
}
my $now = time();
# first cleanup old requests in case some got lost
@pendingMeta = grep { $_->{time} + 60 > $now } @pendingMeta;
# only proceed if our request is not pending and we have less than 10 in parallel
if ( !(grep { $_->{id} == $trackId } @pendingMeta) && scalar(@pendingMeta) < 10 ) {
push @pendingMeta, {
id => $trackId,
time => $now,
};
main::DEBUGLOG && $log->is_debug && $log->debug("adding metadata query for $trackId");
Plugins::TIDAL::Plugin::getAPIHandler($client)->track(sub {
my $meta = shift;
@pendingMeta = grep { $_->{id} != $trackId } @pendingMeta;
return unless $meta;
main::DEBUGLOG && $log->is_debug && $log->debug("found metadata for $trackId", Data::Dump::dump($meta));
return if @pendingMeta;
# Update the playlist time so the web will refresh, etc
$client->currentPlaylistUpdateTime( Time::HiRes::time() );
Slim::Control::Request::notifyFromArray( $client, [ 'newmetadata' ] );
}, $trackId );
}
my $icon = $class->getIcon();
return $meta || {
bitrate => 'N/A',
type => Plugins::TIDAL::API::getFormat(),
icon => $icon,
cover => $icon,
};
}
sub getIcon {
my ( $class, $url ) = @_;
return Plugins::TIDAL::Plugin->_pluginDataFor('icon');
}
sub _getId {
my ($id) = $_[0] =~ m|tidal://(\d+)|;
return $id;
}
1;