de.dakror.scpuller.SCPuller.java Source code

Java tutorial

Introduction

Here is the source code for de.dakror.scpuller.SCPuller.java

Source

/*******************************************************************************
 * Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package de.dakror.scpuller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mpatric.mp3agic.ID3v2;
import com.mpatric.mp3agic.ID3v24Tag;
import com.mpatric.mp3agic.Mp3File;

/**
 * @author Dakror
 */
public class SCPuller {
    public static final String cID = "070cbe45468b49d028988a6e60b0c4f4";

    static int userID;
    static String userName;
    static String playlist;
    static JSONArray allSongs;
    static ArrayList<Integer> downloadedSongs = new ArrayList<>();

    public static void main(String[] args) {
        new File(System.getProperty("user.home") + "/.dakror/SCPuller").mkdirs();
        new File(System.getProperty("user.home") + "/.dakror/SCPuller/download").mkdir();
        Scanner scanner = new Scanner(System.in);

        loadDownloadedSongs();

        try {
            while (true) {
                String line = scanner.nextLine().trim();
                download(line);

                saveDownloadedSongs();
            }
        } finally {
            scanner.close();
        }
    }

    public static void loadDownloadedSongs() {
        File f = new File(System.getProperty("user.home") + "/.dakror/SCPuller/downloaded.txt");
        if (!f.exists())
            return;
        else {
            try {
                downloadedSongs.clear();
                BufferedReader br = new BufferedReader(new FileReader(f));
                String line = "";
                while ((line = br.readLine()) != null)
                    downloadedSongs.add(Integer.parseInt(line));

                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void saveDownloadedSongs() {
        File f = new File(System.getProperty("user.home") + "/.dakror/SCPuller/downloaded.txt");
        try {
            f.createNewFile();
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            for (int i : downloadedSongs)
                bw.write(i + "\r\n");

            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void download(String url) {
        try {
            String json = jsonQuery(url);
            allSongs = new JSONArray(json);
            if (allSongs.length() == 0) {
                System.out.println("This user has no public songs yet!");
                return;
            }

            File parent = new File(System.getProperty("user.home") + "/.dakror/SCPuller/download");

            int newSongs = 0;

            for (int i = 0; i < allSongs.length(); i++) {
                JSONObject o = allSongs.getJSONObject(i);
                if (!downloadedSongs.contains(o.getInt("id")))
                    newSongs++;
            }

            int doneSongs = 0;

            System.out.println("Found " + allSongs.length() + " songs. New: " + newSongs);
            for (int i = 0; i < allSongs.length(); i++) {
                JSONObject o = allSongs.getJSONObject(i);
                if (downloadedSongs.contains(o.getInt("id")))
                    continue;

                File dest = new File(parent, userName + (playlist != null ? "/" + playlist : ""));
                dest.mkdirs();

                File ftemp = new File(dest, o.getString("title").replaceAll("[^\\w ]", "") + ".mp3.tmp");
                File file = new File(dest, o.getString("title").replaceAll("[^\\w ]", "") + ".mp3");
                try {
                    JSONObject d = allSongs.getJSONObject(i);
                    ftemp.createNewFile();
                    String stream_url = d.getString("stream_url");
                    if (stream_url.length() > 0) {
                        copyInputStream(new URL(stream_url + "?client_id=" + cID).openStream(),
                                new FileOutputStream(ftemp));

                        downloadedSongs.add(d.getInt("id"));

                        Mp3File f = new Mp3File(ftemp.getPath());
                        ID3v2 id3v2;
                        if (f.hasId3v2Tag()) {
                            id3v2 = f.getId3v2Tag();
                        } else {
                            id3v2 = new ID3v24Tag();
                            f.setId3v2Tag(id3v2);
                        }
                        id3v2.setAlbumArtist(d.getJSONObject("user").getString("username"));
                        id3v2.setArtist(d.getJSONObject("user").getString("username"));
                        id3v2.setAlbum(d.getString("title"));
                        id3v2.setComment(d.getString("description"));
                        id3v2.setOriginalArtist(d.getJSONObject("user").getString("username"));
                        id3v2.setTitle(d.getString("title"));
                        try {
                            id3v2.setYear("" + d.getInt("release_year"));
                        } catch (Exception e) {
                        }
                        try {
                            String artwork = (d.has("artwork_url")) ? d.getString("artwork_url") : null;

                            if (artwork != null && !artwork.equals("null")) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                copyInputStream(new URL(artwork.replace("large", "t500x500")).openStream(), baos);
                                id3v2.setAlbumImage(baos.toByteArray(), "image/jpeg");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        f.save(file.getPath());
                        ftemp.delete();
                    }

                    doneSongs++;
                    System.out.println("Done: " + doneSongs + " / " + newSongs + "  " + o.getString("title"));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            System.out.println("Done!");

        } catch (Exception e) {
            System.out.println("Either this link is not valid or you aren't connected to the internet!");
        }
    }

    public static String jsonQuery(String url) throws Exception {
        String content = getFileContents(
                new URL("https://api.soundcloud.com/resolve.json?client_id=" + SCPuller.cID + "&url=" + url));
        JSONObject json = new JSONObject(content);

        if (json.getString("kind").equals("user")) {
            userID = json.getInt("id");
            userName = json.getString("username");
            return getFileContents(
                    new URL("http://dakror.de/AndroidSCPuller/getallsongs.php?uid=" + userID + "&cid=" + cID));
        } else if (json.getString("kind").equals("playlist")) {
            JSONObject user = json.getJSONObject("user");
            userID = user.getInt("id");
            userName = user.getString("username");
            playlist = json.getString("title");

            return json.getJSONArray("tracks").toString();
        } else {
            return null;
        }
    }

    public static String getFileContents(URL u) throws IOException {
        String res = "", line = "";
        BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
        while ((line = br.readLine()) != null) {
            res += line;
        }
        br.close();
        return res;
    }

    public static void copyInputStream(InputStream is, OutputStream out) throws Exception {
        byte[] buffer = new byte[2048];
        int len = is.read(buffer);
        while (len != -1) {
            out.write(buffer, 0, len);
            len = is.read(buffer);
        }
        is.close();
        out.close();
    }

}