Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.nio.charset.StandardCharsets;
- import java.net.*;
- import java.security.MessageDigest;
- import javax.xml.bind.DatatypeConverter;
- public class SubsonicConnectTest1 {
- static final String CLIENT_NAME = "Hamsonic Streaming App";
- static String sServerURL = "http://localhost:4040/";
- static String sDefaultParams;
- static String sUsername = "Ham62";
- static String sPassword = "lolno";
- public static void main(String[] args) throws Exception{
- sDefaultParams = "?f=json&v=1.13.0&c="+URLEncoder.encode(CLIENT_NAME, StandardCharsets.UTF_8.toString());
- System.out.println("Ping successful? "+pingServer());
- getSong("4659");
- //System.out.println(sendRequest("getRandomSongs", "&size=2"));
- //downloadSong("4659");
- }
- static void downloadSong(String sID, SongInfo song) throws Exception {
- InputStream stream = sendRequest("stream", sID);
- if (stream == null) return;
- BufferedInputStream in = new BufferedInputStream(stream);
- FileOutputStream outFile = new FileOutputStream("test.mp3");
- byte dataBuffer[] = new byte[524288];
- int bytesRead;
- while ((bytesRead = in.read(dataBuffer, 0, dataBuffer.length)) != -1) {
- outFile.write(dataBuffer, 0, bytesRead);
- }
- outFile.close();
- }
- static SongInfo getSong(String sID) throws Exception {
- InputStream stream = sendRequest("getSong", "&id="+sID);
- if (stream == null) return null;
- BufferedReader in = new BufferedReader(new InputStreamReader(stream));
- String readLine;
- StringBuffer response = new StringBuffer();
- while ((readLine = in.readLine()) != null)
- response.append(readLine);
- in.close();
- // Parse the JSON
- int i = 0;
- String[] input = response.toString().split("\"");
- SongInfo songInfo = new SongInfo();
- while (i < input.length) {
- if (input[i].equals("status")) {
- if (!input[i+2].equals("ok")) {
- for (int e = i+3; e < input.length; e++) {
- if (input[e].equals("message")) {
- System.out.println("Error: "+input[e+2]);
- return null;
- }
- }
- }
- } else if (input[i].equals("id")) {
- songInfo.id = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("parent")) {
- songInfo.parent = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("title")) {
- songInfo.title = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("album")) {
- songInfo.album = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("artist")) {
- songInfo.artist = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("track")) {
- songInfo.track = extractInteger(input[i+1]);
- i += 2; continue;
- } else if (input[i].equals("year")) {
- songInfo.year = extractInteger(input[i+1]);
- i += 2; continue;
- } else if (input[i].equals("genre")) {
- songInfo.genre = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("coverArt")) {
- songInfo.coverArt = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("transcodedSuffix")) {
- songInfo.transcodedSuffix = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("duration")) {
- songInfo.duration = extractInteger(input[i+1]);
- i += 2; continue;
- } else if (input[i].equals("path")) {
- songInfo.path = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("playCount")) {
- songInfo.playCount = extractInteger(input[i+1]);
- i += 2; continue;
- }
- i++;
- }
- return songInfo;
- }
- // Attempt to ping the server and check if the login info is correct
- static boolean pingServer() throws Exception {
- InputStream stream = sendRequest("ping", "");
- if (stream == null) return false;
- // Download the response from the server
- BufferedReader in = new BufferedReader(new InputStreamReader(stream));
- String readLine;
- StringBuffer response = new StringBuffer();
- while ((readLine = in.readLine()) != null)
- response.append(readLine);
- in.close();
- // Parse the JSON
- int i = 0;
- String[] input = response.toString().split("\"");
- String sStatus = "", sVersion = "", sErrorMsg = "";
- while (i < input.length) {
- if (input[i].equals("status")) {
- sStatus = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("version")) {
- sVersion = input[i+2];
- i += 3; continue;
- } else if (input[i].equals("message")) {
- sErrorMsg = input[i+2];
- i += 3; continue;
- }
- i++;
- }
- //System.out.println("Status: "+sStatus);
- //System.out.println("Server protocol version: "+sVersion);
- if (sStatus.equals("ok")) return true;
- System.out.println("Error: "+sErrorMsg);
- return false;
- }
- // Send a generic request to the server returning an input stream with the response
- static InputStream sendRequest(String sMethod, String sExtraParams) throws Exception {
- // Generate login info for request string
- String sSalt = generateSalt(8);
- String sToken = generateMD5Hash(sPassword+sSalt);
- String sLoginInfo = String.format("&u=%s&t=%s&s=%s", sUsername, sToken, sSalt);
- // Generate the request URL for the server
- String sRequest = sServerURL+"rest/"+sMethod+sDefaultParams+sLoginInfo+sExtraParams;
- HttpURLConnection connection;
- int iResponse;
- // Attempt to resolve the URL address and connect to the server
- try {
- URL requestURL = new URL(sRequest);
- connection = (HttpURLConnection)requestURL.openConnection();
- connection.setRequestMethod("GET");
- iResponse = connection.getResponseCode();
- } catch (Exception e) {
- if (e instanceof MalformedURLException) {
- System.out.println(e.getMessage());
- } else if (e instanceof UnknownHostException) {
- System.out.println("Unknown host: "+e.getMessage());
- } else if (e instanceof ConnectException) {
- System.out.println(e.getMessage());
- } else {
- System.out.println(e);
- }
- return null;
- }
- // Non-200 response means we did something wrong
- if (iResponse != 200) {
- System.out.println("Server returned error code: "+iResponse);
- return null;
- }
- // Return the stream from the server
- return connection.getInputStream();
- }
- // Generate an MD5 hash from a string
- static String generateMD5Hash(String sPassword) throws Exception {
- MessageDigest md = MessageDigest.getInstance("MD5");
- md.update(sPassword.getBytes());
- byte[] digest = md.digest();
- return DatatypeConverter.printHexBinary(digest).toLowerCase();
- }
- // Generate a random salt of specified length
- static String generateSalt(int iLength) {
- byte[] salt = new byte[iLength];
- for (int i = 0; i < salt.length; i++) {
- // Random chance of number or upper/lowecase letter
- switch (random(3)) {
- case 0:
- salt[i] = (byte)('0' + random(10));
- break;
- case 1:
- salt[i] = (byte)('A' + random(26));
- break;
- case 2:
- salt[i] = (byte)('a' + random(26));
- break;
- }
- }
- return new String(salt);
- }
- // Return a random number in range (0-max)
- static int random(int max) {
- return (int)(Math.random() * max);
- }
- // Extract an integer from a token which is surrounded by space/non-numbers
- static int extractInteger(String sToken) {
- // Start at the end of the string and work backward
- int iPos = sToken.length()-1;
- // Find end of integer
- while (!charIsNumber(sToken.charAt(iPos--)));
- int iTopOffset = iPos+1;
- // Find start of integer
- while (iPos > 1 && (charIsNumber(sToken.charAt(iPos--))));
- int iBottomOffset = iPos-1;
- if (iBottomOffset < 0) iBottomOffset = 0;
- System.out.println("");
- System.out.println(sToken.substring(iBottomOffset, iTopOffset));
- // Return integer
- return Integer.parseInt(sToken.substring(iBottomOffset, iTopOffset));
- }
- static boolean charIsNumber(char c) {
- return (c < '0' || c > '0');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement