implemented authentication

This commit is contained in:
aj 2019-05-13 13:37:22 +01:00
parent 7a6b9e34c3
commit 23d2b1cffa
4 changed files with 301 additions and 5 deletions

View File

@ -1,9 +1,250 @@
package sarsoo.fmframework.fm;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequest;
import com.mashape.unirest.request.HttpRequestWithBody;
import sarsoo.fmframework.log.Logger;
import sarsoo.fmframework.log.entry.ErrorEntry;
import sarsoo.fmframework.music.Scrobble;
public class FmAuthNetwork extends FmUserNetwork {
public FmAuthNetwork(String key, String userName) {
protected String secretKey;
public FmAuthNetwork(String key, String secretKey, String userName) {
super(key, userName);
this.secretKey = secretKey;
}
public void scrobble(Scrobble scrobble, String sk) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("artist", scrobble.getTrack().getArtist().getName());
params.put("track", scrobble.getTrack().getName());
params.put("timestamp", Long.toString(scrobble.getUTS()));
params.put("sk", sk);
if(scrobble.getAlbum() != null) {
params.put("album", scrobble.getAlbum().getName());
params.put("albumArtist", scrobble.getAlbum().getArtist().getName());
}
JSONObject obj = makeAuthPostRequest("track.scrobble", params);
System.out.println(obj.toString());
}
public String getToken() {
JSONObject obj = makeAuthGetRequest("auth.gettoken");
return obj.getString("token");
}
public String getSession(String token) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", token);
JSONObject obj = makeAuthPostRequest("auth.getSession", params);
return obj.getJSONObject("session").getString("key");
}
public String getApiSignature(HashMap<String, String> parameters) {
TreeMap<String, String> sorted = new TreeMap<>(parameters);
String apiSig = new String();
for (Entry<String, String> i : sorted.entrySet()) {
if (!i.getKey().equals("format") && !i.getKey().equals("callback")) {
apiSig += i.getKey() + i.getValue();
}
}
apiSig += secretKey;
try {
byte[] sigBytes = apiSig.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(sigBytes);
StringBuilder b = new StringBuilder(32);
for(byte aByte : digest) {
String hex = Integer.toHexString((int) aByte & 0xFF);
if(hex.length() == 1) {
b.append('0');
}
b.append(hex);
}
return b.toString();
} catch (UnsupportedEncodingException e) {
Logger.getLog().logError(new ErrorEntry("make API signature").addArg("unsupported encoding"));
}
catch (NoSuchAlgorithmException e) {
Logger.getLog().logError(new ErrorEntry("make API signature").addArg("can't get md5 instance"));
}
return null;
}
protected JSONObject makeAuthGetRequest(String method) {
return makeAuthGetRequest(method, new HashMap<String, String>(), null);
}
protected JSONObject makeAuthGetRequest(String method, HashMap<String, String> parameters) {
return makeAuthGetRequest(method, parameters, null);
}
protected JSONObject makeAuthGetRequest(String method, HashMap<String, String> parameters,
HashMap<String, String> headers) {
HttpRequest request;
try {
request = Unirest.get("https://ws.audioscrobbler.com/2.0/").header("Accept", "application/json")
.header("User-Agent", "fmframework");
parameters.put("method", method);
parameters.put("api_key", key);
parameters.put("format", "json");
parameters.put("api_sig", getApiSignature(parameters).toString());
if (headers != null) {
for (String key : headers.keySet()) {
request = request.header(key, headers.get(key));
}
}
if (parameters != null) {
for (String key : parameters.keySet()) {
request = request.queryString(key, parameters.get(key));
}
}
HttpResponse<JsonNode> response = request.asJson();
if (response.getStatus() == 200) {
return new JSONObject(response.getBody().toString());
} else {
JSONObject obj = new JSONObject(response.getBody().toString());
Logger.getLog().logError(new ErrorEntry("HTTP Get").setErrorCode(response.getStatus())
.addArg(Integer.toString(obj.getInt("error"))).addArg(obj.getString("message")));
return null;
}
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
protected JSONObject makeAuthPostRequest(String method) {
return makeAuthPostRequest(method, new HashMap<String, String>(), null);
}
protected JSONObject makeAuthPostRequest(String method, HashMap<String, String> parameters) {
return makeAuthPostRequest(method, parameters, null);
}
protected JSONObject makeAuthPostRequest(String method, HashMap<String, String> parameters,
HashMap<String, String> headers) {
HttpRequestWithBody request;
try {
request = Unirest.post("https://ws.audioscrobbler.com/2.0/").header("Accept", "application/json")
.header("User-Agent", "fmframework");
parameters.put("method", method);
parameters.put("api_key", key);
parameters.put("format", "json");
String apiSig = getApiSignature(parameters).toString();
parameters.put("api_sig", apiSig);
if (headers != null) {
for (String key : headers.keySet()) {
request = request.header(key, headers.get(key));
}
}
String body = new String();
if (parameters != null) {
body = getBodyString(parameters);
request.body(body);
}
HttpResponse<JsonNode> response = request.asJson();
if (response.getStatus() == 200) {
return new JSONObject(response.getBody().toString());
} else {
JSONObject obj = new JSONObject(response.getBody().toString());
Logger.getLog().logError(new ErrorEntry("HTTP post").setErrorCode(response.getStatus())
.addArg(Integer.toString(obj.getInt("error"))).addArg(obj.getString("message")));
return null;
}
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
public String getBodyString(Map<String, String> params) {
String body = new String();
TreeMap<String, String> sorted = new TreeMap<>(params);
for (Iterator<Entry<String, String>> it = sorted.entrySet().iterator(); it.hasNext();) {
Entry<String, String> entry = it.next();
body += entry.getKey();
body += '=';
body += entry.getValue();
if(it.hasNext()) {
body += '&';
}
}
return body;
}
}

View File

@ -377,7 +377,11 @@ public class FmNetwork {
HttpRequest request;
try {
request = Unirest.get("https://ws.audioscrobbler.com/2.0/").header("Accept", "application/json")
.header("User-Agent", "fmframework").queryString("method", method);
.header("User-Agent", "fmframework");
parameters.put("method", method);
parameters.put("api_key", key);
parameters.put("format", "json");
if (headers != null) {
for (String key : headers.keySet()) {
@ -391,8 +395,6 @@ public class FmNetwork {
}
}
request = request.queryString("api_key", key).queryString("format", "json");
HttpResponse<JsonNode> response = request.asJson();
if (response.getStatus() == 200) {

View File

@ -7,11 +7,13 @@ import java.time.ZoneId;
public class Scrobble {
private LocalDateTime dateTime;
private long uts;
private Track track;
private Album album;
public Scrobble(long uts, Track track) {
this.track = track;
this.uts = uts;
this.dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(uts), ZoneId.systemDefault());
}
@ -25,6 +27,10 @@ public class Scrobble {
return dateTime;
}
public long getUTS() {
return uts;
}
public Track getTrack() {
return track;
}

View File

@ -0,0 +1,47 @@
package sarsoo.fmframework.fm;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Scanner;
import org.junit.Test;
import sarsoo.fmframework.music.Scrobble;
import sarsoo.fmframework.music.Track.TrackBuilder;
import sarsoo.fmframework.music.Artist.ArtistBuilder;
import sarsoo.fmframework.net.Key;
public class FmAuthNetworkTest {
@Test
public void test() {
FmAuthNetwork net = new FmAuthNetwork(Key.getKey(), Key.getSecret(), "sarsoo");
// HashMap<String, String> hash = new HashMap<>();
//
// hash.put("zoo", "ash");
// hash.put("boo", "ash");
// hash.put("ash", "boo");
//
// net.getApiSignature(hash);
String token = net.getToken();
System.out.println(token);
// new Scanner(System.in).nextLine();
String key = net.getSession(token);
System.out.println(key);
Scrobble scrobble = new Scrobble(1557750712, new TrackBuilder("i", new ArtistBuilder("kendrick lamar").build()).build());
net.scrobble(scrobble, key);
assertTrue(true);
}
}