Added documentation

+ LastFMToSpotify.java
+ ArgumentHandler.java

Also added a check for image content type
This commit is contained in:
2023-01-24 21:45:43 +01:00
parent a62821f739
commit b643e85711
2 changed files with 122 additions and 10 deletions

View File

@@ -38,9 +38,13 @@ public class LastFMToSpotify {
configuration.put("requests.useragent", "LastFMToSpotify/1.0-Snapshot (" + System.getProperty("os.name") + "; " + System.getProperty("os.arch") + ") Java/" + System.getProperty("java.version"));
configuration.put("playlist.name", "LastFMToSpotify@" + LocalDateTime.now(Clock.systemDefaultZone()).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
configuration.put("logging.level", "1");
//check whether all required arguments are set
if (!ArgumentHandler.checkArguments(args)) {
return;
}
//check whether multiple arguments from an exclusive set are used
if(!ArgumentHandler.checkExclusivity(args)){
return;
}
@@ -77,21 +81,29 @@ public class LastFMToSpotify {
SpotifyApi api = build.build();
AtomicBoolean waiting = new AtomicBoolean(true);
if (configuration.containsKey("cache.crypto") && TokenHelper.existsTokens()) {
logLn("Cached credentials have been found.", 2);
logLn("Fetching old credentials, refreshing them and saving to cache", 2);
AuthorizationCodeCredentials oldcred = TokenHelper.fetchTokens();
AuthorizationCodeCredentials newcred = api.authorizationCodeRefresh(api.getClientId(), api.getClientSecret(), oldcred.getRefreshToken()).build().execute();
AuthorizationCodeCredentials newcred = api.authorizationCodeRefresh(api.getClientId(), api.getClientSecret(), oldcred.getRefreshToken()).setHeader("User-Agent", configuration.get("requests.useragent")).build().execute();
TokenHelper.saveTokens(newcred);
configuration.put("spotify.access", newcred.getAccessToken());
} else {
try (Javalin webserver = Javalin.create().start(9876)) {
if (configuration.containsKey("cache.crypto")) logLn("No cached credentials have been found.", 2);
logLn("Starting webserver to initiate web based authentication.", 2);
Runtime.getRuntime().addShutdownHook(new Thread(webserver::stop));
// webserver.exception(Exception.class, (exception, ctx) -> {
// ctx.result(exception.getMessage());
// });
webserver.get("/callback/spotify", ctx -> {
if(ctx.queryParamMap().containsKey("code")) {
AuthorizationCodeCredentials cred = api.authorizationCode(ctx.queryParam("code")).build().execute();
logLn("Received spotify authentication code. Requesting credentials.", 2);
AuthorizationCodeCredentials cred = api.authorizationCode(ctx.queryParam("code")).setHeader("User-Agent", configuration.get("requests.useragent")).build().execute();
configuration.put("spotify.access", cred.getAccessToken());
if(configuration.containsKey("cache.crypto")) TokenHelper.saveTokens(cred);
if(configuration.containsKey("cache.crypto")) {
logLn("Saving credentials to cache.", 2);
TokenHelper.saveTokens(cred);
}
ctx.result("success. <script>let win = window.open(null, '_self');win.close();</script>").contentType(ContentType.TEXT_HTML).status(HttpStatus.OK);
waiting.set(false);
} else {
@@ -111,12 +123,14 @@ public class LastFMToSpotify {
logLn("Reading from LastFM...", 1);
Collection<Track> tracks = User.getTopTracks(configuration.get("lastfm.user"), PeriodHelper.getPeriodByString(configuration.get("lastfm.period")), configuration.get("lastfm.apikey"));
logLn("Creating Playlist...", 1);
logLn("... with custom playlistname (if set) and access modifiers (if set).", 2);
api.setAccessToken(configuration.get("spotify.access"));
Playlist list = api.createPlaylist(api.getCurrentUsersProfile().build().execute().getId(), configuration.get("playlist.name")).public_(configuration.containsKey("playlist.public")).collaborative(configuration.containsKey("playlist.collab")).setHeader("User-Agent", configuration.get("requests.useragent")).build().execute();
List<String> adders = new LinkedList<>();
String charsToReplace = "[\"']"; //regex for " and '
String charsToReplace = "[\"']"; //regex removing " and ' because of issues with spotify search
logLn("Searching tracks from LastFM data on Spotify.", 2);
for (Track track : tracks) {
logLn("Adding " + track.getName() + " by " + track.getArtist(), 3);
logLn("Searching " + track.getName() + " by " + track.getArtist(), 3);
StringBuilder searchQuery = new StringBuilder();
searchQuery.append("track:").append(track.getName().replaceAll(charsToReplace, ""));
searchQuery.append(" artist:").append(track.getArtist());
@@ -132,8 +146,10 @@ public class LastFMToSpotify {
}
}
}
api.addItemsToPlaylist(list.getId(), adders.toArray(String[]::new)).build().execute();
logLn("Adding tracks to playlist.", 2);
api.addItemsToPlaylist(list.getId(), adders.toArray(String[]::new)).setHeader("User-Agent", configuration.get("requests.useragent")).build().execute();
if(configuration.containsKey("playlist.cover")){
logLn("Setting playlist cover", 2);
logLn("Check for \"null\" if setting cover was successful: " + api.uploadCustomPlaylistCoverImage(list.getId()).image_data(configuration.get("playlist.cover")).setHeader("User-Agent", configuration.get("requests.useragent")).build().execute(),3);
}
logLn("Done.", 1);

View File

@@ -7,6 +7,7 @@ import de.umass.lastfm.Period;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
@@ -24,6 +25,11 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.util.Logger.logLn;
import java.util.List;
public class ArgumentHandler {
/**
* Selects which argument is handled by which method.
* @param argument the argument to handle
* @param value the value supplied with the argument
*/
public static void handle(Arguments argument, @Nullable String value) {
switch (argument) {
case HELP -> help(value);
@@ -45,11 +51,19 @@ public class ArgumentHandler {
}
}
/**
* Handles an argument without a value. Will pass <code>null</code> as value.
* @param argument the argument to handle without value
*/
public static void handle(Arguments argument) {
handle(argument, null);
}
/**
* Checks whether every required argument is used.
* @param args the <code>string[] args</code> passed to psvm.
* @return whether every required argument is used
*/
public static boolean checkArguments(String[] args) {
// check if all required arguments are given
Arguments[] required = {Arguments.SECRET, Arguments.CLIENT, Arguments.TOKEN, Arguments.USER};
@@ -72,6 +86,11 @@ public class ArgumentHandler {
return true;
}
/**
* Checks whether multiple arguments of an exclusivity group are used.
* @param args the <code>string[] args</code> passed to psvm.
* @return Whether only one argument out of every exclusivity group is given
*/
public static boolean checkExclusivity(String[] args){
Arguments[][] exclusive = {{Arguments.PUBLIC, Arguments.COLLABORATIVE}, {Arguments.WEEKLY, Arguments.MONTHLY, Arguments.QUARTERLY, Arguments.BIANNUALLY, Arguments.YEARLY}};
for(Arguments[] arguments : exclusive){
@@ -91,7 +110,12 @@ public class ArgumentHandler {
return true;
}
/**
* Displays help into the console.
* @param value The argument or alias to display help for.
*/
private static void help(String value) {
//evaluates whether an argument or alias is given. If not list of all arguments is displayed.
if (value == null || value.isEmpty()) {
logLn("This is a list of all available commands. For more specific help on the argument run --help <argument>.", 1);
for (Arguments arg : Arguments.values()) {
@@ -103,11 +127,13 @@ public class ArgumentHandler {
}
System.exit(200);
}
//resolves argument or alias. If no match is found tool will exit
Arguments arg = Arguments.resolveByNameOrAlias(value);
if (arg == null) {
logLn("This argument is unknown. Use --help to get a list of all arguments", 1);
System.exit(200);
}
//Displays information about the selected argument
String name = arg.getName();
String description = arg.getDescription();
String[] aliases = arg.getAliases();
@@ -121,10 +147,21 @@ public class ArgumentHandler {
}
logLn(" ALIASES:" + aliasString.substring(1), 1);
logLn("____________________", 1);
//tool exits
System.exit(200);
}
/**
* Sets the log level.
* - 0: Quiet Will run completely quietly
* - 1: Default Will only show progress
* - 2: Verbose Will echo current step being worked on
* - 3: Debug Will give specific information on what excactly the tool is doing
* @param value an int 0 - 3
*/
private static void verbose(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) {
logLn("--loglevel must be provided with a numeric log level. Check usage: " + Arguments.VERBOSE.getUsage(), 1);
System.exit(500);
@@ -139,7 +176,12 @@ public class ArgumentHandler {
}
/**
* Sets the LastFM api token into the configuration
* @param value The LastFM api token
*/
private static void token(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) {
logLn("--lastfmtoken must be provided with an api token from LastFM. Check usage: " + Arguments.TOKEN.getUsage(), 1);
System.exit(500);
@@ -147,7 +189,12 @@ public class ArgumentHandler {
configuration.put("lastfm.apikey", value);
}
/**
* Sets the LastFM username into the configuration
* @param value The LastFM username
*/
private static void user(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) {
logLn("--lastfmuser must be provided with a LastFM username. Check usage: " + Arguments.USER.getUsage(), 1);
System.exit(500);
@@ -155,7 +202,12 @@ public class ArgumentHandler {
configuration.put("lastfm.user", value);
}
/**
* Sets the spotify client id into the configuration
* @param value The Spotify Client ID
*/
private static void client(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) {
logLn("--spotifyclient must be provided with a client id from Spotify. Check usage: " + Arguments.CLIENT.getUsage(), 1);
System.exit(500);
@@ -163,7 +215,12 @@ public class ArgumentHandler {
configuration.put("spotify.clientid", value);
}
/**
* Sets the spotify client secret into the configuration
* @param value The Spotify Client Secret
*/
private static void secret(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) {
logLn("--spotifysecret must be provided with a client secret from Spotify. Check usage: " + Arguments.SECRET.getUsage(), 1);
System.exit(500);
@@ -171,20 +228,44 @@ public class ArgumentHandler {
configuration.put("spotify.secret", value);
}
/**
* Sets the Period to be loaded from LastFM. Possibilities: WEEKLY, MONTHLY, QUARTERLY, BIANNUALLY, YEARLY
* @param value the LastFM Period to be loaded
*/
private static void period(Period value) {
configuration.put("lastfm.period", value.getString());
}
/**
* Takes a path to a jpeg image and turns it into base64 encoded image data which is subsequently saved into <code>playlist.cover</code> in the configuration.
* @param value The filepath to the cover image. Must be jpeg.
*/
private static void cover(String value) {
if (value == null || value.isEmpty() || !Files.exists(Path.of(value.replace("\\", "//")))) {
logLn("--coverart must be provided with a path to a png file. Check usage: " + Arguments.COVER.getUsage(), 1);
System.exit(500);
//evaluating if value is provided and of content-type image/jpeg
try {
if(value == null){
logLn("--coverart must be provided with a path to a jpeg file. Check usage: " + Arguments.COVER.getUsage(), 1);
System.exit(500);
}
Path path = Path.of(value.replace("\\", "//"));
if (value.isEmpty() || !Files.exists(path) || !Files.probeContentType(path).equalsIgnoreCase("image/jpeg")) {
logLn("--coverart must be provided with a path to a jpeg file. Check usage: " + Arguments.COVER.getUsage(), 1);
System.exit(500);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
//encodes image data into base64
String base64 = FileHelper.encodeFileToBase64(new File(value.replace("\\", "//")));
//saves to configuration
configuration.put("playlist.cover", base64);
}
/**
* Sets the access modifier. Can either be <code>"collaborative"</code> or <code>"public"</code>.
* @param value "collaborative" or "public"
*/
private static void access(String value) {
switch (value) {
case "collaborative" -> configuration.put("playlist.collab", "collab");
@@ -192,17 +273,27 @@ public class ArgumentHandler {
}
}
/**
* Sets the <code>playlist.name</code> value in the configuration. Supports templating and date offsetting. See <a href="https://github.com/B00tLoad/LastFMtoSpotifyPlaylist/wiki/Filename-Templating">wiki</a> for further documentation on templating.
* @param value The playlist name string, including templating
*/
private static void name(String value) {
//evaluating if value is provided
if (value == null || value.isEmpty()) {
logLn("--playlistname must be provided with a playlist name. Check usage: " + Arguments.NAME.getUsage(), 1);
System.exit(500);
}
//creating current datetime and users locale
LocalDateTime now = LocalDateTime.now(Clock.systemDefaultZone());
Locale loc = Locale.forLanguageTag(System.getProperty("user.country"));
//checking for the date offset flag and applying it if necessary
if(value.matches("(%\\$-?\\d*\\$).*")){
int offsetDays = Integer.parseInt(value.substring(2).split("\\$")[0]);
now = offsetDays < 0 ? now.minusDays(Math.abs(offsetDays)) : now.plusDays(Math.abs(offsetDays));
}
//replacing datetime template
String name = value.replace("%YYYY", String.valueOf(now.getYear())).replace("%YY", String.valueOf(now.getYear()).substring(2))
.replace("%MMMM", now.getMonth().name().charAt(0) + now.getMonth().name().toLowerCase().substring(1))
.replace("%MMM", now.getMonth().getDisplayName(TextStyle.FULL, loc))
@@ -231,7 +322,12 @@ public class ArgumentHandler {
configuration.put("playlist.name", name);
}
/**
* Sets the <code>cache.crypto</code> value in the configuration
* @param value a password encrypting the credential cache
*/
public static void cache(String value){
//evaluating if value is provided
if (value == null || value.isEmpty()) {
logLn("--spotifycache must be provided with a password. Check usage: " + Arguments.SPOTIFY_CACHING.getUsage(), 1);
System.exit(500);