Compare commits

...

2 Commits

Author SHA1 Message Date
mschuepbach
128f6ca6f0 Format files
All checks were successful
release / release-plugins (push) Successful in 25s
2024-03-27 16:24:10 +01:00
mschuepbach
2c941230a5 Add additional options to plugin init 2024-03-27 16:23:17 +01:00
5 changed files with 354 additions and 274 deletions

View File

@@ -11,7 +11,8 @@ use MIME::Base64 qw(decode_base64);
use constant API_URL => 'https://music.youtube.com/youtubei/v1/'; use constant API_URL => 'https://music.youtube.com/youtubei/v1/';
use constant DEFAULT_CACHE_TTL => 24 * 3600; use constant DEFAULT_CACHE_TTL => 24 * 3600;
use constant DEFAULT_API_KEY => 'QUl6YVN5Qi1wd1B0RGt4RjZKUW1BOHFxOWgxbWQ2ME15STVRNWlB'; use constant DEFAULT_API_KEY =>
'QUl6YVN5Qi1wd1B0RGt4RjZKUW1BOHFxOWgxbWQ2ME15STVRNWlB';
use Slim::Utils::Cache; use Slim::Utils::Cache;
use Slim::Utils::Log; use Slim::Utils::Log;
@@ -32,7 +33,7 @@ sub search {
$args->{order} ||= $prefs->get('search_rank'); $args->{order} ||= $prefs->get('search_rank');
$args->{relevanceLanguage} = Slim::Utils::Strings::getLanguage(); $args->{relevanceLanguage} = Slim::Utils::Strings::getLanguage();
_pagedCall('search', $args, $cb); _pagedCall( 'search', $args, $cb );
} }
sub searchDirect { sub searchDirect {
@@ -41,7 +42,7 @@ sub searchDirect {
$args ||= {}; $args ||= {};
$args->{_noRegion} = 1; $args->{_noRegion} = 1;
_pagedCall( $type, $args, $cb); _pagedCall( $type, $args, $cb );
} }
sub getCategories { sub getCategories {
@@ -51,23 +52,29 @@ sub getCategories {
$args->{hl} = Slim::Utils::Strings::getLanguage(); $args->{hl} = Slim::Utils::Strings::getLanguage();
$args->{_cache_ttl} = 7 * 86400; $args->{_cache_ttl} = 7 * 86400;
_pagedCall($type, $args, $cb); _pagedCall( $type, $args, $cb );
} }
sub getVideoDetails { sub getVideoDetails {
my ( $class, $cb, $ids ) = @_; my ( $class, $cb, $ids ) = @_;
_call('videos', { _call(
'videos',
{
part => 'snippet,contentDetails', part => 'snippet,contentDetails',
id => $ids, id => $ids,
# cache video details a bit longer # cache video details a bit longer
_cache_ttl => 7 * 86400, _cache_ttl => 7 * 86400,
}, $cb); },
$cb
);
} }
sub _pagedCall { sub _pagedCall {
my ( $method, $args, $cb ) = @_; my ( $method, $args, $cb ) = @_;
my $wantedItems = $args->{_quantity} || $prefs->get('max_items'); my $wantedItems = $args->{_quantity} || $prefs->get('max_items');
# ignore $args->{_index} and let LMS handle offset # ignore $args->{_index} and let LMS handle offset
my $wantedIndex = 0; my $wantedIndex = 0;
my @items; my @items;
@@ -78,16 +85,27 @@ sub _pagedCall {
$wantedItems += $args->{_index} || 0; $wantedItems += $args->{_index} || 0;
main::INFOLOG && $log->info("Searching by [$args->{order}]"); main::INFOLOG && $log->info("Searching by [$args->{order}]");
main::INFOLOG && $log->info("Querying [$args->{_quantity}] from [$args->{_index}] to [", $wantedItems-1, "] using [$method]"); main::INFOLOG && $log->info(
"Querying [$args->{_quantity}] from [$args->{_index}] to [",
$wantedItems - 1,
"] using [$method]"
);
# doing a search with a display order, so need to give precedence to 'query_size' # doing a search with a display order, so need to give precedence to 'query_size'
if ($prefs->get('search_sort') || $prefs->get('channel_sort') || $prefs->get('playlist_sort')) { if ( $prefs->get('search_sort')
$wantedItems = (int(($wantedItems - 1) / $prefs->get('query_size')) + 1) * $prefs->get('query_size'); || $prefs->get('channel_sort')
main::INFOLOG && $log->info("Stretching quantity to [$wantedItems] due to sorting"); || $prefs->get('playlist_sort') )
{
$wantedItems =
( int( ( $wantedItems - 1 ) / $prefs->get('query_size') ) + 1 ) *
$prefs->get('query_size');
main::INFOLOG
&& $log->info("Stretching quantity to [$wantedItems] due to sorting");
} }
# that the maximum we'll get anyway # that the maximum we'll get anyway
$wantedItems = $prefs->get('max_items') if $wantedItems > $prefs->get('max_items'); $wantedItems = $prefs->get('max_items')
if $wantedItems > $prefs->get('max_items');
$pagingCb = sub { $pagingCb = sub {
my $results = shift; my $results = shift;
@@ -98,30 +116,45 @@ sub _pagedCall {
return; return;
} }
push @items, @{$results->{items}}; push @items, @{ $results->{items} };
$pageIndex += scalar @{$results->{items}}; $pageIndex += scalar @{ $results->{items} };
main::INFOLOG && $log->info("Want $wantedItems items from offset ", $wantedIndex, ", have " . scalar @items . " so far [acquired $pageIndex]"); main::INFOLOG && $log->info( "Want $wantedItems items from offset ",
$wantedIndex,
", have " . scalar @items . " so far [acquired $pageIndex]" );
if (@items < $wantedItems && $results->{nextPageToken}) { if ( @items < $wantedItems && $results->{nextPageToken} ) {
$args->{pageToken} = $results->{nextPageToken}; $args->{pageToken} = $results->{nextPageToken};
main::INFOLOG && $log->info("Get next page using token " . $args->{pageToken}); main::INFOLOG
_call($method, $args, $pagingCb); && $log->info(
} else { "Get next page using token " . $args->{pageToken} );
my $total = min($results->{'pageInfo'}->{'totalResults'} || $pageIndex, $prefs->get('max_items')); _call( $method, $args, $pagingCb );
main::INFOLOG && $log->info("Got all we wanted, return " . scalar @items . "/$total. (YT total ", $results->{'pageInfo'}->{'totalResults'} || 'N/A', ")"); }
$cb->( { items => \@items, offset => $wantedIndex, total => $total } ); else {
my $total =
min( $results->{'pageInfo'}->{'totalResults'} || $pageIndex,
$prefs->get('max_items') );
main::INFOLOG && $log->info(
"Got all we wanted, return "
. scalar @items
. "/$total. (YT total ",
$results->{'pageInfo'}->{'totalResults'} || 'N/A',
")"
);
$cb->(
{ items => \@items, offset => $wantedIndex, total => $total } );
} }
}; };
_call($method, $args, $pagingCb); _call( $method, $args, $pagingCb );
} }
sub _call { sub _call {
my ( $method, $args, $cb ) = @_; my ( $method, $args, $cb ) = @_;
my $API_KEY = $prefs->get('APIkey') || MIME::Base64::decode_base64(DEFAULT_API_KEY); my $API_KEY =
my $url = '?' . ($args->{_noKey} ? '' : 'key=' . $API_KEY . '&'); $prefs->get('APIkey') || MIME::Base64::decode_base64(DEFAULT_API_KEY);
my $url = '?' . ( $args->{_noKey} ? '' : 'key=' . $API_KEY . '&' );
$args->{regionCode} ||= $prefs->get('country') unless $args->{_noRegion}; $args->{regionCode} ||= $prefs->get('country') unless $args->{_noRegion};
$args->{part} ||= 'snippet' unless $args->{_noPart}; $args->{part} ||= 'snippet' unless $args->{_noPart};
@@ -129,7 +162,11 @@ sub _call {
for my $k ( sort keys %{$args} ) { for my $k ( sort keys %{$args} ) {
next if $k =~ /^_/; next if $k =~ /^_/;
$url .= $k . '=' . URI::Escape::uri_escape_utf8( Encode::decode( 'utf8', $args->{$k} ) ) . '&'; $url .=
$k . '='
. URI::Escape::uri_escape_utf8(
Encode::decode( 'utf8', $args->{$k} ) )
. '&';
} }
$url =~ s/&$//; $url =~ s/&$//;
@@ -137,35 +174,41 @@ sub _call {
my $cacheKey = $args->{_noCache} ? '' : md5_hex($url); my $cacheKey = $args->{_noCache} ? '' : md5_hex($url);
if ( $cacheKey && (my $cached = $cache->get($cacheKey)) ) { if ( $cacheKey && ( my $cached = $cache->get($cacheKey) ) ) {
main::INFOLOG && $log->info("Returning cached data for: $url"); main::INFOLOG && $log->info("Returning cached data for: $url");
$cb->($cached); $cb->($cached);
return; return;
} }
main::INFOLOG && $log->info("Calling API (will cache for ", $args->{_cache_ttl} || DEFAULT_CACHE_TTL, "s): $url"); main::INFOLOG && $log->info(
"Calling API (will cache for ",
$args->{_cache_ttl} || DEFAULT_CACHE_TTL,
"s): $url"
);
Slim::Networking::SimpleAsyncHTTP->new( Slim::Networking::SimpleAsyncHTTP->new(
sub { sub {
my $response = shift; my $response = shift;
my $result = eval { from_json($response->content) }; my $result = eval { from_json( $response->content ) };
if ($@) { if ($@) {
$log->error(Data::Dump::dump($response)) unless main::DEBUGLOG && $log->is_debug; $log->error( Data::Dump::dump($response) )
unless main::DEBUGLOG && $log->is_debug;
$log->error($@); $log->error($@);
} }
main::DEBUGLOG && $log->is_debug && warn Data::Dump::dump($result); main::DEBUGLOG && $log->is_debug && warn Data::Dump::dump($result);
$result ||= {}; $result ||= {};
$cache->set($cacheKey, $result, $args->{_cache_ttl} || DEFAULT_CACHE_TTL); $cache->set( $cacheKey, $result,
$args->{_cache_ttl} || DEFAULT_CACHE_TTL );
$cb->($result); $cb->($result);
}, },
sub { sub {
warn Data::Dump::dump(@_); warn Data::Dump::dump(@_);
$log->error($_[1]); $log->error( $_[1] );
$cb->( { error => $_[1] } ); $cb->( { error => $_[1] } );
}, },

View File

@@ -1,26 +1,26 @@
[% PROCESS settings/header.html %] [% PROCESS settings/header.html %]
<div>Hello World</div> <div>Hello World</div>
[% WRAPPER setting title="PLUGIN_YOUTUBEMUSIC_TESTPREF" desc="PLUGIN_YOUTUBEMUSIC_TESTPREF_DESC" %] [% WRAPPER setting title="PLUGIN_YOUTUBEMUSIC_TESTPREF" desc="PLUGIN_YOUTUBEMUSIC_TESTPREF_DESC" %]
<input type="text" class="stdedit" name="pref_testPref" id="pref_testPref" value="[% prefs.pref_testPref %]" size="45"> <input type="text" class="stdedit" name="pref_testPref" id="pref_testPref" value="[% prefs.pref_testPref %]" size="45">
[% END %] [% END %]
[% WRAPPER setting title="PLUGIN_YOUTUBEMUSIC_AUTH" desc="PLUGIN_YOUTUBEMUSIC_AUTH_DESC" %] [% WRAPPER setting title="PLUGIN_YOUTUBEMUSIC_AUTH" desc="PLUGIN_YOUTUBEMUSIC_AUTH_DESC" %]
<div> <div>
[% IF !user_code %] [% IF !user_code %]
<input type="submit" name="get_device_code" value=[% "PLUGIN_YOUTUBEMUSIC_START_AUTH" | string %]> <input type="submit" name="get_device_code" value=[% "PLUGIN_YOUTUBEMUSIC_START_AUTH" | string %]>
[% ELSE %] [% ELSE %]
<a href="[% verification_url %]" target="none">[% "PLUGIN_YOUTUBEMUSIC_VERIFICATIONURL" | string %]</a> <a href="[% verification_url %]" target="none">[% "PLUGIN_YOUTUBEMUSIC_VERIFICATIONURL" | string %]</a>
<div>[% user_code %]</div> <div>[% user_code %]</div>
[% END %] [% END %]
</div> </div>
<div> <div>
<input type="submit" name="get_token" value="Check"> <input type="submit" name="get_token" value="Check">
[% IF access_token %] [% IF access_token %]
<div>Success</div> <div>Success</div>
[% END %] [% END %]
</div> </div>
[% END %] [% END %]
[% PROCESS settings/footer.html %] [% PROCESS settings/footer.html %]

View File

@@ -8,33 +8,42 @@ use Slim::Utils::Strings qw(string cstring);
use JSON::XS::VersionOneAndTwo; use JSON::XS::VersionOneAndTwo;
use Data::Dumper; use Data::Dumper;
use constant CLIENT_ID => "861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com"; use constant CLIENT_ID =>
"861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com";
use constant CLIENT_SECRET => "SboVhoG9s0rNafixCSGGKXAT"; use constant CLIENT_SECRET => "SboVhoG9s0rNafixCSGGKXAT";
my $log = logger('plugin.youtubemusic'); my $log = logger('plugin.youtubemusic');
my $cache = Slim::Utils::Cache->new(); my $cache = Slim::Utils::Cache->new();
sub getDeviceCode { sub getDeviceCode {
my $post = "client_id=" . CLIENT_ID . "&scope=https://www.googleapis.com/auth/youtube"; my $post =
"client_id="
. CLIENT_ID
. "&scope=https://www.googleapis.com/auth/youtube";
my $http = Slim::Networking::SimpleAsyncHTTP->new( my $http = Slim::Networking::SimpleAsyncHTTP->new(
sub { sub {
my $response = shift; my $response = shift;
my $result = eval { from_json($response->content) }; my $result = eval { from_json( $response->content ) };
if ($@) { if ($@) {
$log->error(Data::Dump::dump($response)) unless main::DEBUGLOG && $log->is_debug; $log->error( Data::Dump::dump($response) )
unless main::DEBUGLOG && $log->is_debug;
$log->error($@); $log->error($@);
} else { }
$cache->set("yt:device_code", $result->{device_code}, $result->{expires_in}); else {
$cache->set("yt:verification_url", $result->{verification_url}, $result->{expires_in}); $cache->set( "yt:device_code", $result->{device_code},
$cache->set("yt:user_code", $result->{user_code}, $result->{expires_in}); $result->{expires_in} );
$cache->set( "yt:verification_url", $result->{verification_url},
$result->{expires_in} );
$cache->set( "yt:user_code", $result->{user_code},
$result->{expires_in} );
$log->debug("content:", $response->content); $log->debug( "content:", $response->content );
} }
}, },
sub { sub {
$log->error($_[1]); $log->error( $_[1] );
}, },
{ {
timeout => 15, timeout => 15,
@@ -54,35 +63,47 @@ sub getToken {
my $post = "client_id=" . CLIENT_ID . "&client_secret=" . CLIENT_SECRET; my $post = "client_id=" . CLIENT_ID . "&client_secret=" . CLIENT_SECRET;
my $code = $cache->get('yt:device_code'); my $code = $cache->get('yt:device_code');
if (defined $code) { if ( defined $code ) {
$post .= "&code=$code&grant_type=http://oauth.net/grant_type/device/1.0"; $post .=
} else { "&code=$code&grant_type=http://oauth.net/grant_type/device/1.0";
$post .= "&refresh_token=" . $cache->get('yt:refresh_token') . "&grant_type=refresh_token"; }
else {
$post .=
"&refresh_token="
. $cache->get('yt:refresh_token')
. "&grant_type=refresh_token";
} }
my $http = Slim::Networking::SimpleAsyncHTTP->new( my $http = Slim::Networking::SimpleAsyncHTTP->new(
sub { sub {
my $response = shift; my $response = shift;
my $result = eval { from_json($response->content) }; my $result = eval { from_json( $response->content ) };
if ($@) { if ($@) {
$log->error(Data::Dump::dump($response)) unless main::DEBUGLOG && $log->is_debug; $log->error( Data::Dump::dump($response) )
unless main::DEBUGLOG && $log->is_debug;
$log->error($@); $log->error($@);
} else { }
$cache->set("yt:access_token", $result->{access_token}, $result->{expires_in} - 60); else {
$cache->set('yt:refresh_token', $result->{refresh_token}) if $result->{refresh_token}; $cache->set(
"yt:access_token",
$result->{access_token},
$result->{expires_in} - 60
);
$cache->set( 'yt:refresh_token', $result->{refresh_token} )
if $result->{refresh_token};
$cache->remove('yt:user_code'); $cache->remove('yt:user_code');
$cache->remove('yt:verification_url'); $cache->remove('yt:verification_url');
$cache->remove('yt:device_code'); $cache->remove('yt:device_code');
$log->debug("content:", $response->content); $log->debug( "content:", $response->content );
$cb->(@params) if $cb; $cb->(@params) if $cb;
} }
}, },
sub { sub {
$log->error($_[1]); $log->error( $_[1] );
$cb->(@params) if $cb; $cb->(@params) if $cb;
}, },
{ {

View File

@@ -11,25 +11,32 @@ use Slim::Utils::Cache;
use Plugins::YouTubeMusic::OAuth2; use Plugins::YouTubeMusic::OAuth2;
my $log = Slim::Utils::Log->addLogCategory({ my $log = Slim::Utils::Log->addLogCategory(
{
'category' => 'plugin.youtubemusic', 'category' => 'plugin.youtubemusic',
'defaultLevel' => 'WARN', 'defaultLevel' => 'WARN',
'description' => 'PLUGIN_YOUTUBEMUSIC', 'description' => 'PLUGIN_YOUTUBEMUSIC',
}); }
);
my $prefs = preferences('plugin.youtubemusic'); my $prefs = preferences('plugin.youtubemusic');
my $cache = Slim::Utils::Cache->new(); my $cache = Slim::Utils::Cache->new();
$prefs->init({ $prefs->init(
{
testPref => 'test' testPref => 'test'
}); }
);
sub initPlugin { sub initPlugin {
my $class = shift; my $class = shift;
$class->SUPER::initPlugin( $class->SUPER::initPlugin(
feed => \&mainMenu, feed => \&mainMenu,
is_app => 1 tag => 'youtubemusic',
menu => 'radios',
is_app => 1,
weight => 1,
); );
if (main::WEBUI) { if (main::WEBUI) {
@@ -45,19 +52,25 @@ sub shutdownPlugin {
sub getDisplayName { 'PLUGIN_YOUTUBEMUSIC' } sub getDisplayName { 'PLUGIN_YOUTUBEMUSIC' }
sub mainMenu { sub mainMenu {
my ($client, $callback, $args) = @_; my ( $client, $callback, $args ) = @_;
$callback->([ $callback->(
{ name => cstring($client, 'PLUGIN_YOUTUBEMUSIC_MYPLAYLISTS'), type => 'url', url => \&myPlaylistHandler, passthrough => [ { count => 2 } ] }, [
]); {
name => cstring( $client, 'PLUGIN_YOUTUBEMUSIC_MYPLAYLISTS' ),
type => 'url',
url => \&myPlaylistHandler,
passthrough => [ { count => 2 } ]
},
]
);
} }
sub myPlaylistHandler { sub myPlaylistHandler {
my ($client, $cb, $args, $params) = @_; my ( $client, $cb, $args, $params ) = @_;
if (!$cache->get('yt:access_token')) { if ( !$cache->get('yt:access_token') ) {
Plugins::YouTubeMusic::OAuth2::getToken(\&myPlaylistHandler, @_); Plugins::YouTubeMusic::OAuth2::getToken( \&myPlaylistHandler, @_ );
return; return;
} }
@@ -68,17 +81,21 @@ sub myPlaylistHandler {
access_token => $cache->get('yt:access_token'), access_token => $cache->get('yt:access_token'),
}; };
Plugins::YouTubeMusic::API->searchDirect('playlists', sub { Plugins::YouTubeMusic::API->searchDirect(
$cb->(_renderList($_[0], 'title', $account)); 'playlists',
}, { sub {
$cb->( _renderList( $_[0], 'title', $account ) );
},
{
%$account, %$account,
_index => $args->{index}, _index => $args->{index},
_quantity => $args->{quantity}, _quantity => $args->{quantity},
}); }
);
} }
sub _renderList { sub _renderList {
my ($list, $sort, $passthrough, $tags) = @_; my ( $list, $sort, $passthrough, $tags ) = @_;
my $sortedList = $list->{items}; my $sortedList = $list->{items};
my @items; my @items;
@@ -100,4 +117,3 @@ sub _renderList {
} }
1; 1;

View File

@@ -18,14 +18,15 @@ sub page {
} }
sub prefs { sub prefs {
return (preferences('plugin.youtubemusic'), qw(testPref)); return ( preferences('plugin.youtubemusic'), qw(testPref) );
} }
sub handler { sub handler {
my ($class, $client, $params) = @_; my ( $class, $client, $params ) = @_;
if ($params->{'saveSettings'}) { if ( $params->{'saveSettings'} ) {
preferences('plugin.youtubemusic')->set('testPref', $params->{'pref_testPref'}); preferences('plugin.youtubemusic')
->set( 'testPref', $params->{'pref_testPref'} );
} }
Plugins::YouTubeMusic::OAuth2::getDeviceCode if $params->{get_device_code}; Plugins::YouTubeMusic::OAuth2::getDeviceCode if $params->{get_device_code};
@@ -35,8 +36,7 @@ sub handler {
$params->{verification_url} = $cache->get('yt:verification_url'); $params->{verification_url} = $cache->get('yt:verification_url');
$params->{access_token} = $cache->get('yt:access_token'); $params->{access_token} = $cache->get('yt:access_token');
return $class->SUPER::handler($client, $params); return $class->SUPER::handler( $client, $params );
} }
1; 1;