diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/LastFMToSpotify.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/LastFMToSpotify.java index c32d43e..c96ca36 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/LastFMToSpotify.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/LastFMToSpotify.java @@ -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. ").contentType(ContentType.TEXT_HTML).status(HttpStatus.OK); waiting.set(false); } else { @@ -111,12 +123,14 @@ public class LastFMToSpotify { logLn("Reading from LastFM...", 1); Collection 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 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); diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/ArgumentHandler.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/ArgumentHandler.java index 58c690e..c58d08a 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/ArgumentHandler.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/ArgumentHandler.java @@ -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 null 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 string[] args 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 string[] args 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 .", 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 playlist.cover 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 "collaborative" or "public". + * @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 playlist.name value in the configuration. Supports templating and date offsetting. See wiki 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 cache.crypto 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); diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/Arguments.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/Arguments.java index 396e71d..9a92ada 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/Arguments.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/arguments/Arguments.java @@ -6,6 +6,7 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.LINE_SEP public enum Arguments { + //Defining arguments HELP("help", "[Optional, will not execute tool] " + LINE_SEPERATOR + "Shows a list of all commands or, if provided, help for a given command.", "--help [argument]", "h", "?"), VERBOSE("loglevel", "[Optional] " + LINE_SEPERATOR @@ -73,6 +74,11 @@ public enum Arguments { return aliases; } + /** + * Resolves an alias-String into an Argument-object + * @param alias The alias to resolve + * @return The resolved Argument, null if alias does not exist. + */ public static Arguments getByAlias(String alias){ for(Arguments arg : values()){ if(List.of(arg.getAliases()).contains(alias)) return arg; @@ -80,6 +86,11 @@ public enum Arguments { return null; } + /** + * Resolves an argument-String into an Argument-object + * @param name The argument to resolve + * @return The resolved Argument, null if alias does not exist. + */ public static Arguments getByName(String name){ for(Arguments arg : values()){ if(arg.getName().equalsIgnoreCase(name)) return arg; @@ -87,6 +98,11 @@ public enum Arguments { return null; } + /** + * Resolves an argument- or alias-String into an Argument-object + * @param v The alias or argument to resolve + * @return The resolved Argument, null if alias does not exist. + */ public static Arguments resolveByNameOrAlias(String v){ Arguments ret = getByName(v); if(ret != null) return ret; @@ -94,6 +110,10 @@ public enum Arguments { return ret; } + /** + * Builds a String consisting of the argument name and all aliases listed + * @return "--$argument ($aliases)" + */ @Override public String toString() { StringBuilder args = new StringBuilder("--").append(this.name).append(" ("); diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/CryptoHelper.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/CryptoHelper.java index 4339930..70183fd 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/CryptoHelper.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/CryptoHelper.java @@ -15,18 +15,28 @@ import java.security.spec.KeySpec; public class CryptoHelper { + /** + * Creates a javax.crypto.SecretKey from a provided password + * @param pass The password + * @return the generated secret key + */ public static SecretKey createKeyFromPassword(String pass){ try { KeySpec spec = new PBEKeySpec(pass.toCharArray(), "abcdefghijklmnop".getBytes(), 65536, 256); // AES-256 SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - byte[] key = new byte[0]; - key = f.generateSecret(spec).getEncoded(); + byte[] key = f.generateSecret(spec).getEncoded(); return new SecretKeySpec(key, "AES"); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } + /** + * Saves a java.io.Serializable Object into an encrypted file + * @param obj The object to save + * @param file The Path where to save the file + * @param key The SecretKey (AES) to encrypt the file with + */ public static void serializeEncrypted(Serializable obj, Path file, SecretKey key){ try { if(file.toFile().exists()) file.toFile().delete(); @@ -45,8 +55,14 @@ public class CryptoHelper { } } + /** + * Reads an encrypted file into a java.io.Serializable object. + * @param file The java.nio.Path where the encrypted file is stored. + * @param key The SecretKey (AES) to decrypt the file with + * @return The java.io.Serializable object read from the file. + */ public static Serializable deserializeEncrypted(Path file, SecretKey key) { - Serializable ret = null; + Serializable ret; try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec("abcdefghijklmnop".getBytes()); diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/FileHelper.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/FileHelper.java index e1ad05b..52e2890 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/FileHelper.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/FileHelper.java @@ -7,6 +7,11 @@ import java.util.Base64; public class FileHelper { + /** + * Reads a file and encodes it into Base64 + * @param file The file to read + * @return A Base64 encoded String containing the data of the file + */ public static String encodeFileToBase64(File file){ String encodedfile = null; try (FileInputStream fileInputStreamReader = new FileInputStream(file)){ diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/Logger.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/Logger.java index cad03cc..15c8ee4 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/Logger.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/Logger.java @@ -4,6 +4,11 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.configur public class Logger { + /** + * Logs the provided String to console if the option logging.level in the configuration is higher or equal to the provided priority + * @param string The String to log + * @param priority The minimum logging level with which the provided string should be logged + */ public static void logLn(String string, int priority){ if(Integer.parseInt(configuration.get("logging.level"))>=priority){ System.out.println(string); diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/PeriodHelper.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/PeriodHelper.java index 2c68faf..6ded178 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/PeriodHelper.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/PeriodHelper.java @@ -4,6 +4,11 @@ import de.umass.lastfm.Period; public class PeriodHelper { + /** + * Converts a provided String (de.umass.lastfm.Period.getString()) into the corresponding de.umass.lastfm.Period + * @param string The value to be converted into a de.umass.lastfm.Period + * @return The converted de.umass.lastfm.Period, defaults to de.umass.lastfm.Period.ONE_MONTH + */ public static Period getPeriodByString(String string){ for(Period p : Period.values()){ if(p.getString().equalsIgnoreCase(string)) return p; diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TimeHelper.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TimeHelper.java index 8e6ba74..3cf12c6 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TimeHelper.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TimeHelper.java @@ -5,19 +5,33 @@ import java.time.ZoneId; public class TimeHelper { + /** + * Gets the hours of the UTC offset from a LocalDateTime, which is asserted to be at the system default Timezone (ZoneId.systemDefault()) + * @param now The java.time.LocalDateTime for which the offset should be calculated + * @return The hours of offset from UTC + */ public static int getUTCOffsetHours(LocalDateTime now){ - return (int) Math.floor((double) now.atZone(ZoneId.systemDefault()).getOffset().getTotalSeconds()/3600); } + /** + * Gets the minutes of the UTC offset from a LocalDateTime, which is asserted to be at the system default Timezone (ZoneId.systemDefault()) + * @param now The java.time.LocalDateTime for which the offset should be calculated + * @return The minutes of offset from UTC + */ public static int getUTCOffsetMinutes(LocalDateTime now){ return (now.atZone(ZoneId.systemDefault()).getOffset().getTotalSeconds()/60); } + /** + * Generates an ISO 8601 complying String containing the UTC offset from a LocalDateTime, which is asserted to be at the system default Timezone (ZoneId.systemDefault()) + * @param now The java.time.LocalDateTime for which the offset should be calculated + * @return an ISO 8601 complying String containing the UTC offset (e.g. "+01:00") + */ public static String getUTCOffset(LocalDateTime now){ int hour = getUTCOffsetHours(now); String h = (hour == Math.abs(hour) ? "+" : "-") + (String.valueOf(Math.abs(hour)).length() == 1 ? "0" + Math.abs(hour) : String.valueOf(Math.abs(hour))); - int min = Math.abs(getUTCOffsetMinutes(now))-(Math.abs(hour)*60); + int min = Math.abs(getUTCOffsetMinutes(now))%(Math.abs(hour)); String m = (String.valueOf(Math.abs(min)).length() == 1 ? "0" + Math.abs(min) : String.valueOf(Math.abs(min))); return h + ":" + m; } diff --git a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TokenHelper.java b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TokenHelper.java index 8197b21..b9e434a 100644 --- a/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TokenHelper.java +++ b/src/main/java/de/b00tload/tools/lastfmtospotifyplaylist/util/TokenHelper.java @@ -8,14 +8,27 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.USER_HOM import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.configuration; public class TokenHelper { + + /** + * Manages saving a se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials into "~/.lfm2s/spotify.lfm2scred" using de.b00tload.tools.lastfmtospotifyplaylist.util.CryptoHelper.serializeEncrypted(...) + * @param cred The se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials to be saved + */ public static void saveTokens(AuthorizationCodeCredentials cred) { CryptoHelper.serializeEncrypted(cred, Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred"), CryptoHelper.createKeyFromPassword(configuration.get("cache.crypto"))); } + /** + * Manages retrieving a se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials from "~/.lfm2s/spotify.lfm2scred" using de.b00tload.tools.lastfmtospotifyplaylist.util.CryptoHelper.deserializeEncrypted(...) + * @return The retrieved se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials + */ public static AuthorizationCodeCredentials fetchTokens() { return (AuthorizationCodeCredentials) CryptoHelper.deserializeEncrypted(Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred"), CryptoHelper.createKeyFromPassword(configuration.get("cache.crypto"))); } + /** + * Checks whether the saved spotify AuthorizationCodeCredentials at "~/.lfm2s/spotify.lfm2scred" exist + * @return true if file exists, false if not + */ public static boolean existsTokens(){ return Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred").toFile().exists(); }