Merge pull request #14 from B00tLoad/documentation

Added documentation
This commit was merged in pull request #14.
This commit is contained in:
Môrrîl
2023-01-28 07:02:34 +01:00
committed by GitHub
9 changed files with 205 additions and 15 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("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("playlist.name", "LastFMToSpotify@" + LocalDateTime.now(Clock.systemDefaultZone()).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
configuration.put("logging.level", "1"); configuration.put("logging.level", "1");
//check whether all required arguments are set
if (!ArgumentHandler.checkArguments(args)) { if (!ArgumentHandler.checkArguments(args)) {
return; return;
} }
//check whether multiple arguments from an exclusive set are used
if(!ArgumentHandler.checkExclusivity(args)){ if(!ArgumentHandler.checkExclusivity(args)){
return; return;
} }
@@ -77,21 +81,29 @@ public class LastFMToSpotify {
SpotifyApi api = build.build(); SpotifyApi api = build.build();
AtomicBoolean waiting = new AtomicBoolean(true); AtomicBoolean waiting = new AtomicBoolean(true);
if (configuration.containsKey("cache.crypto") && TokenHelper.existsTokens()) { 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 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); TokenHelper.saveTokens(newcred);
configuration.put("spotify.access", newcred.getAccessToken()); configuration.put("spotify.access", newcred.getAccessToken());
} else { } else {
try (Javalin webserver = Javalin.create().start(9876)) { 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)); Runtime.getRuntime().addShutdownHook(new Thread(webserver::stop));
// webserver.exception(Exception.class, (exception, ctx) -> { // webserver.exception(Exception.class, (exception, ctx) -> {
// ctx.result(exception.getMessage()); // ctx.result(exception.getMessage());
// }); // });
webserver.get("/callback/spotify", ctx -> { webserver.get("/callback/spotify", ctx -> {
if(ctx.queryParamMap().containsKey("code")) { 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()); 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); ctx.result("success. <script>let win = window.open(null, '_self');win.close();</script>").contentType(ContentType.TEXT_HTML).status(HttpStatus.OK);
waiting.set(false); waiting.set(false);
} else { } else {
@@ -111,12 +123,14 @@ public class LastFMToSpotify {
logLn("Reading from LastFM...", 1); logLn("Reading from LastFM...", 1);
Collection<Track> tracks = User.getTopTracks(configuration.get("lastfm.user"), PeriodHelper.getPeriodByString(configuration.get("lastfm.period")), configuration.get("lastfm.apikey")); Collection<Track> tracks = User.getTopTracks(configuration.get("lastfm.user"), PeriodHelper.getPeriodByString(configuration.get("lastfm.period")), configuration.get("lastfm.apikey"));
logLn("Creating Playlist...", 1); logLn("Creating Playlist...", 1);
logLn("... with custom playlistname (if set) and access modifiers (if set).", 2);
api.setAccessToken(configuration.get("spotify.access")); 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(); 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<>(); 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) { for (Track track : tracks) {
logLn("Adding " + track.getName() + " by " + track.getArtist(), 3); logLn("Searching " + track.getName() + " by " + track.getArtist(), 3);
StringBuilder searchQuery = new StringBuilder(); StringBuilder searchQuery = new StringBuilder();
searchQuery.append("track:").append(track.getName().replaceAll(charsToReplace, "")); searchQuery.append("track:").append(track.getName().replaceAll(charsToReplace, ""));
searchQuery.append(" artist:").append(track.getArtist()); 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")){ 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("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); logLn("Done.", 1);

View File

@@ -7,6 +7,7 @@ import de.umass.lastfm.Period;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Clock; import java.time.Clock;
@@ -24,6 +25,11 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.util.Logger.logLn;
import java.util.List; import java.util.List;
public class ArgumentHandler { 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) { public static void handle(Arguments argument, @Nullable String value) {
switch (argument) { switch (argument) {
case HELP -> help(value); 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) { public static void handle(Arguments argument) {
handle(argument, null); 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) { public static boolean checkArguments(String[] args) {
// check if all required arguments are given // check if all required arguments are given
Arguments[] required = {Arguments.SECRET, Arguments.CLIENT, Arguments.TOKEN, Arguments.USER}; Arguments[] required = {Arguments.SECRET, Arguments.CLIENT, Arguments.TOKEN, Arguments.USER};
@@ -72,6 +86,11 @@ public class ArgumentHandler {
return true; 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){ public static boolean checkExclusivity(String[] args){
Arguments[][] exclusive = {{Arguments.PUBLIC, Arguments.COLLABORATIVE}, {Arguments.WEEKLY, Arguments.MONTHLY, Arguments.QUARTERLY, Arguments.BIANNUALLY, Arguments.YEARLY}}; Arguments[][] exclusive = {{Arguments.PUBLIC, Arguments.COLLABORATIVE}, {Arguments.WEEKLY, Arguments.MONTHLY, Arguments.QUARTERLY, Arguments.BIANNUALLY, Arguments.YEARLY}};
for(Arguments[] arguments : exclusive){ for(Arguments[] arguments : exclusive){
@@ -91,7 +110,12 @@ public class ArgumentHandler {
return true; return true;
} }
/**
* Displays help into the console.
* @param value The argument or alias to display help for.
*/
private static void help(String value) { 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()) { 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); 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()) { for (Arguments arg : Arguments.values()) {
@@ -103,11 +127,13 @@ public class ArgumentHandler {
} }
System.exit(200); System.exit(200);
} }
//resolves argument or alias. If no match is found tool will exit
Arguments arg = Arguments.resolveByNameOrAlias(value); Arguments arg = Arguments.resolveByNameOrAlias(value);
if (arg == null) { if (arg == null) {
logLn("This argument is unknown. Use --help to get a list of all arguments", 1); logLn("This argument is unknown. Use --help to get a list of all arguments", 1);
System.exit(200); System.exit(200);
} }
//Displays information about the selected argument
String name = arg.getName(); String name = arg.getName();
String description = arg.getDescription(); String description = arg.getDescription();
String[] aliases = arg.getAliases(); String[] aliases = arg.getAliases();
@@ -121,10 +147,21 @@ public class ArgumentHandler {
} }
logLn(" ALIASES:" + aliasString.substring(1), 1); logLn(" ALIASES:" + aliasString.substring(1), 1);
logLn("____________________", 1); logLn("____________________", 1);
//tool exits
System.exit(200); 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) { private static void verbose(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--loglevel must be provided with a numeric log level. Check usage: " + Arguments.VERBOSE.getUsage(), 1); logLn("--loglevel must be provided with a numeric log level. Check usage: " + Arguments.VERBOSE.getUsage(), 1);
System.exit(500); 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) { private static void token(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--lastfmtoken must be provided with an api token from LastFM. Check usage: " + Arguments.TOKEN.getUsage(), 1); logLn("--lastfmtoken must be provided with an api token from LastFM. Check usage: " + Arguments.TOKEN.getUsage(), 1);
System.exit(500); System.exit(500);
@@ -147,7 +189,12 @@ public class ArgumentHandler {
configuration.put("lastfm.apikey", value); configuration.put("lastfm.apikey", value);
} }
/**
* Sets the LastFM username into the configuration
* @param value The LastFM username
*/
private static void user(String value) { private static void user(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--lastfmuser must be provided with a LastFM username. Check usage: " + Arguments.USER.getUsage(), 1); logLn("--lastfmuser must be provided with a LastFM username. Check usage: " + Arguments.USER.getUsage(), 1);
System.exit(500); System.exit(500);
@@ -155,7 +202,12 @@ public class ArgumentHandler {
configuration.put("lastfm.user", value); 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) { private static void client(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--spotifyclient must be provided with a client id from Spotify. Check usage: " + Arguments.CLIENT.getUsage(), 1); logLn("--spotifyclient must be provided with a client id from Spotify. Check usage: " + Arguments.CLIENT.getUsage(), 1);
System.exit(500); System.exit(500);
@@ -163,7 +215,12 @@ public class ArgumentHandler {
configuration.put("spotify.clientid", value); 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) { private static void secret(String value) {
//evaluates whether value is set
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--spotifysecret must be provided with a client secret from Spotify. Check usage: " + Arguments.SECRET.getUsage(), 1); logLn("--spotifysecret must be provided with a client secret from Spotify. Check usage: " + Arguments.SECRET.getUsage(), 1);
System.exit(500); System.exit(500);
@@ -171,20 +228,44 @@ public class ArgumentHandler {
configuration.put("spotify.secret", value); 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) { private static void period(Period value) {
configuration.put("lastfm.period", value.getString()); 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) { private static void cover(String value) {
if (value == null || value.isEmpty() || !Files.exists(Path.of(value.replace("\\", "//")))) { //evaluating if value is provided and of content-type image/jpeg
logLn("--coverart must be provided with a path to a png file. Check usage: " + Arguments.COVER.getUsage(), 1); 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); 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("\\", "//"))); String base64 = FileHelper.encodeFileToBase64(new File(value.replace("\\", "//")));
//saves to configuration
configuration.put("playlist.cover", base64); 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) { private static void access(String value) {
switch (value) { switch (value) {
case "collaborative" -> configuration.put("playlist.collab", "collab"); 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) { private static void name(String value) {
//evaluating if value is provided
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--playlistname must be provided with a playlist name. Check usage: " + Arguments.NAME.getUsage(), 1); logLn("--playlistname must be provided with a playlist name. Check usage: " + Arguments.NAME.getUsage(), 1);
System.exit(500); System.exit(500);
} }
//creating current datetime and users locale
LocalDateTime now = LocalDateTime.now(Clock.systemDefaultZone()); LocalDateTime now = LocalDateTime.now(Clock.systemDefaultZone());
Locale loc = Locale.forLanguageTag(System.getProperty("user.country")); Locale loc = Locale.forLanguageTag(System.getProperty("user.country"));
//checking for the date offset flag and applying it if necessary
if(value.matches("(%\\$-?\\d*\\$).*")){ if(value.matches("(%\\$-?\\d*\\$).*")){
int offsetDays = Integer.parseInt(value.substring(2).split("\\$")[0]); int offsetDays = Integer.parseInt(value.substring(2).split("\\$")[0]);
now = offsetDays < 0 ? now.minusDays(Math.abs(offsetDays)) : now.plusDays(Math.abs(offsetDays)); 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)) 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("%MMMM", now.getMonth().name().charAt(0) + now.getMonth().name().toLowerCase().substring(1))
.replace("%MMM", now.getMonth().getDisplayName(TextStyle.FULL, loc)) .replace("%MMM", now.getMonth().getDisplayName(TextStyle.FULL, loc))
@@ -231,7 +322,12 @@ public class ArgumentHandler {
configuration.put("playlist.name", name); 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){ public static void cache(String value){
//evaluating if value is provided
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
logLn("--spotifycache must be provided with a password. Check usage: " + Arguments.SPOTIFY_CACHING.getUsage(), 1); logLn("--spotifycache must be provided with a password. Check usage: " + Arguments.SPOTIFY_CACHING.getUsage(), 1);
System.exit(500); System.exit(500);

View File

@@ -6,6 +6,7 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.LINE_SEP
public enum Arguments { public enum Arguments {
//Defining arguments
HELP("help", "[Optional, will not execute tool] " + LINE_SEPERATOR 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", "?"), + "Shows a list of all commands or, if provided, help for a given command.", "--help [argument]", "h", "?"),
VERBOSE("loglevel", "[Optional] " + LINE_SEPERATOR VERBOSE("loglevel", "[Optional] " + LINE_SEPERATOR
@@ -73,6 +74,11 @@ public enum Arguments {
return aliases; 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){ public static Arguments getByAlias(String alias){
for(Arguments arg : values()){ for(Arguments arg : values()){
if(List.of(arg.getAliases()).contains(alias)) return arg; if(List.of(arg.getAliases()).contains(alias)) return arg;
@@ -80,6 +86,11 @@ public enum Arguments {
return null; 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){ public static Arguments getByName(String name){
for(Arguments arg : values()){ for(Arguments arg : values()){
if(arg.getName().equalsIgnoreCase(name)) return arg; if(arg.getName().equalsIgnoreCase(name)) return arg;
@@ -87,6 +98,11 @@ public enum Arguments {
return null; 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){ public static Arguments resolveByNameOrAlias(String v){
Arguments ret = getByName(v); Arguments ret = getByName(v);
if(ret != null) return ret; if(ret != null) return ret;
@@ -94,6 +110,10 @@ public enum Arguments {
return ret; return ret;
} }
/**
* Builds a String consisting of the argument name and all aliases listed
* @return "--$argument ($aliases)"
*/
@Override @Override
public String toString() { public String toString() {
StringBuilder args = new StringBuilder("--").append(this.name).append(" ("); StringBuilder args = new StringBuilder("--").append(this.name).append(" (");

View File

@@ -15,18 +15,28 @@ import java.security.spec.KeySpec;
public class CryptoHelper { public class CryptoHelper {
/**
* Creates a <code>javax.crypto.SecretKey</code> from a provided password
* @param pass The password
* @return the generated secret key
*/
public static SecretKey createKeyFromPassword(String pass){ public static SecretKey createKeyFromPassword(String pass){
try { try {
KeySpec spec = new PBEKeySpec(pass.toCharArray(), "abcdefghijklmnop".getBytes(), 65536, 256); // AES-256 KeySpec spec = new PBEKeySpec(pass.toCharArray(), "abcdefghijklmnop".getBytes(), 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = new byte[0]; byte[] key = f.generateSecret(spec).getEncoded();
key = f.generateSecret(spec).getEncoded();
return new SecretKeySpec(key, "AES"); return new SecretKeySpec(key, "AES");
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) { } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/**
* Saves a <code>java.io.Serializable</code> 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){ public static void serializeEncrypted(Serializable obj, Path file, SecretKey key){
try { try {
if(file.toFile().exists()) file.toFile().delete(); if(file.toFile().exists()) file.toFile().delete();
@@ -45,8 +55,14 @@ public class CryptoHelper {
} }
} }
/**
* Reads an encrypted file into a <code>java.io.Serializable</code> object.
* @param file The <code>java.nio.Path</code> where the encrypted file is stored.
* @param key The SecretKey (AES) to decrypt the file with
* @return The <code>java.io.Serializable</code> object read from the file.
*/
public static Serializable deserializeEncrypted(Path file, SecretKey key) { public static Serializable deserializeEncrypted(Path file, SecretKey key) {
Serializable ret = null; Serializable ret;
try { try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("abcdefghijklmnop".getBytes()); IvParameterSpec iv = new IvParameterSpec("abcdefghijklmnop".getBytes());

View File

@@ -7,6 +7,11 @@ import java.util.Base64;
public class FileHelper { 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){ public static String encodeFileToBase64(File file){
String encodedfile = null; String encodedfile = null;
try (FileInputStream fileInputStreamReader = new FileInputStream(file)){ try (FileInputStream fileInputStreamReader = new FileInputStream(file)){

View File

@@ -4,6 +4,11 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.configur
public class Logger { public class Logger {
/**
* Logs the provided String to console if the option <code>logging.level</code> 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){ public static void logLn(String string, int priority){
if(Integer.parseInt(configuration.get("logging.level"))>=priority){ if(Integer.parseInt(configuration.get("logging.level"))>=priority){
System.out.println(string); System.out.println(string);

View File

@@ -4,6 +4,11 @@ import de.umass.lastfm.Period;
public class PeriodHelper { public class PeriodHelper {
/**
* Converts a provided String (<code>de.umass.lastfm.Period.getString()</code>) into the corresponding <code>de.umass.lastfm.Period</code>
* @param string The value to be converted into a <code>de.umass.lastfm.Period</code>
* @return The converted <code>de.umass.lastfm.Period</code>, defaults to <code>de.umass.lastfm.Period.ONE_MONTH</code>
*/
public static Period getPeriodByString(String string){ public static Period getPeriodByString(String string){
for(Period p : Period.values()){ for(Period p : Period.values()){
if(p.getString().equalsIgnoreCase(string)) return p; if(p.getString().equalsIgnoreCase(string)) return p;

View File

@@ -5,19 +5,33 @@ import java.time.ZoneId;
public class TimeHelper { public class TimeHelper {
/**
* Gets the hours of the UTC offset from a LocalDateTime, which is asserted to be at the system default Timezone (<code>ZoneId.systemDefault()</code>)
* @param now The <code>java.time.LocalDateTime</code> for which the offset should be calculated
* @return The hours of offset from UTC
*/
public static int getUTCOffsetHours(LocalDateTime now){ public static int getUTCOffsetHours(LocalDateTime now){
return (int) Math.floor((double) now.atZone(ZoneId.systemDefault()).getOffset().getTotalSeconds()/3600); 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 (<code>ZoneId.systemDefault()</code>)
* @param now The <code>java.time.LocalDateTime</code> for which the offset should be calculated
* @return The minutes of offset from UTC
*/
public static int getUTCOffsetMinutes(LocalDateTime now){ public static int getUTCOffsetMinutes(LocalDateTime now){
return (now.atZone(ZoneId.systemDefault()).getOffset().getTotalSeconds()/60); 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 (<code>ZoneId.systemDefault()</code>)
* @param now The <code>java.time.LocalDateTime</code> 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){ public static String getUTCOffset(LocalDateTime now){
int hour = getUTCOffsetHours(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))); 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))); String m = (String.valueOf(Math.abs(min)).length() == 1 ? "0" + Math.abs(min) : String.valueOf(Math.abs(min)));
return h + ":" + m; return h + ":" + m;
} }

View File

@@ -8,14 +8,27 @@ import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.USER_HOM
import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.configuration; import static de.b00tload.tools.lastfmtospotifyplaylist.LastFMToSpotify.configuration;
public class TokenHelper { public class TokenHelper {
/**
* Manages saving a <code>se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials</code> into "~/.lfm2s/spotify.lfm2scred" using <code>de.b00tload.tools.lastfmtospotifyplaylist.util.CryptoHelper.serializeEncrypted(...)</code>
* @param cred The <code>se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials</code> to be saved
*/
public static void saveTokens(AuthorizationCodeCredentials cred) { public static void saveTokens(AuthorizationCodeCredentials cred) {
CryptoHelper.serializeEncrypted(cred, Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred"), CryptoHelper.createKeyFromPassword(configuration.get("cache.crypto"))); CryptoHelper.serializeEncrypted(cred, Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred"), CryptoHelper.createKeyFromPassword(configuration.get("cache.crypto")));
} }
/**
* Manages retrieving a <code>se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials</code> from "~/.lfm2s/spotify.lfm2scred" using <code>de.b00tload.tools.lastfmtospotifyplaylist.util.CryptoHelper.deserializeEncrypted(...)</code>
* @return The retrieved <code>se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials</code>
*/
public static AuthorizationCodeCredentials fetchTokens() { public static AuthorizationCodeCredentials fetchTokens() {
return (AuthorizationCodeCredentials) CryptoHelper.deserializeEncrypted(Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred"), CryptoHelper.createKeyFromPassword(configuration.get("cache.crypto"))); 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(){ public static boolean existsTokens(){
return Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred").toFile().exists(); return Path.of(USER_HOME, "/.lfm2s/spotify.lfm2scred").toFile().exists();
} }