aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/Main.java
blob: 7474de4b3bf668e0b1d81887e8cf1dbba5f2c84b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import com.formdev.flatlaf.FlatIntelliJLaf;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.datatype.Artwork;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultCaret;


public class Main extends JFrame {
    final static String BLACKLIST = "blacklist.txt";
    private static String COMPLETED_DIR = "completed";


    String textPath = "";

    static JTextArea outputArea = new JTextArea("");
    JPanel panel = new JPanel();
    JScrollPane scrollPane;
    JButton songsGen = new JButton("Generate text file");
    JButton editButton = new JButton("Edit Tags");
    JButton startButton = new JButton("Set .txt File");
    JButton configureDownloadButton = new JButton("Configure Download File Interactively");
    JButton setOutputDirButton = new JButton("Set MP3 Output Directory");
    JCheckBox defaultFileBox = new JCheckBox("Use location of last file");
    JCheckBox useBlacklistBox = new JCheckBox("Use Blacklist.txt");
    JProgressBar progressBar = new JProgressBar();
    JLabel title = new JLabel("YouTube to MP3 Auto Tagging [CrossPlatform]");
    Boolean useBlacklist = false;
    Boolean readyState = false;

    public Main() {
        initializeComponents();
        initializeActionsListeners();
        createDirectories();
    }

    public static void main(String[] args) {
        FlatIntelliJLaf.setup();
        new Main().setVisible(true);
    }


    public static ArrayList<String> txtToList(String fileName) {
        ArrayList<String> lines = new ArrayList<String>();
        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines;
    }

    /**
     * Calculate the percentage for progress bar
     * @param current The current number of songs downloaded
     * @param total The total number of songs to download
     * @return The percentage of songs downloaded
     */
    private int calculatePercentage(int current, int total) {//Calculate the percentage when give numerator and denominator
        double currentD = current;
        double totalD = total;
        return (int) ((currentD / totalD) * 100);
    }

    public void downloadAndTag(){
        ArrayList<String> songs = txtToList(textPath);
        int totalSongs = songs.size();
        int songsProcessed = 0;
        for(String line: songs){
            System.out.println(line);
            if(line.contains(",")){
                String[] parts = line.split(",");
                String url = parts[0];
                String stamp = parts[1];
                Downloader downloader = new Downloader(COMPLETED_DIR, outputArea);
                downloader.download(url, stamp);
            }
            else{
                Downloader downloader = new Downloader(COMPLETED_DIR, outputArea);
                downloader.download(line);
            }
            songsProcessed++;
            progressBar.setValue(calculatePercentage(songsProcessed, totalSongs));
        }
    }


    /**
     * Initialize all GUI components
     */
    private void initializeComponents() {//Initiate GUI components
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon("icon.png").getImage());
        this.add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        scrollPane = new JScrollPane(outputArea);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        outputArea.setEditable(true);
        outputArea.setLineWrap(true);
        DefaultCaret caret = (DefaultCaret) outputArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        panel.add(Box.createRigidArea(new Dimension(0, 5)));
        panel.setBorder(BorderFactory.createEmptyBorder(25, 10, 20, 10));
        startButton.setAlignmentX(CENTER_ALIGNMENT);
        startButton.setSize(new Dimension(300, 20));
        title.setAlignmentX(Component.CENTER_ALIGNMENT);
        defaultFileBox.setAlignmentX(Component.CENTER_ALIGNMENT);
        useBlacklistBox.setAlignmentX(Component.CENTER_ALIGNMENT);
        editButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        songsGen.setAlignmentX(Component.CENTER_ALIGNMENT);
        progressBar.setStringPainted(true);
        progressBar.setFont(new Font("Verdana", Font.PLAIN, 12));
        title.setFont(new Font("Verdana", Font.BOLD, 16));
        panel.add(title);
        panel.add(Box.createVerticalStrut(10));
        panel.add(progressBar);
        panel.add(Box.createVerticalStrut(10));
        panel.add(startButton);
        panel.add(defaultFileBox);
        panel.add(useBlacklistBox);
        panel.add(Box.createVerticalStrut(8));
        panel.add(scrollPane);
        panel.add(Box.createVerticalStrut(5));
        panel.add(editButton);
        panel.add(Box.createVerticalStrut(5));
        outputArea.setEditable(false);
        configureDownloadButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(configureDownloadButton);
        this.setSize(550, 450);
        this.setTitle("YTMP3Tagger");
    }


    public static String showTextFileChooser() {
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt", "text");
        chooser.setFileFilter(filter);
        chooser.setDialogTitle("Select a text file");
        chooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showOpenDialog(null) == javax.swing.JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile().getAbsolutePath();
        } else {
            return null;
        }
    }

    /**
     * Initialize all action listeners for buttons
     */
    private void initializeActionsListeners() { //Add all actionlisteners for buttons
        defaultFileBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (defaultFileBox.isSelected()) {
                    File file = new File("lastFile.txt");
                    if (!file.exists()) {
                        defaultFileBox.setSelected(false);
                        JOptionPane.showMessageDialog(null, "Unable to find the location of your previous file, please select a new one");
                        return;
                    }
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new FileReader(file));
                        String line = br.readLine();
                        if (line == null) {
                            defaultFileBox.setSelected(false);
                            JOptionPane.showMessageDialog(null, "Unable to find the location of your previous file, please select a new one");
                            return;
                        }
                        textPath = line;
                        COMPLETED_DIR = textPath.substring(0, textPath.lastIndexOf(File.separator));
                        readyState = true;
                        startButton.setText("Start Download");
                        outputArea.setText(outputArea.getText() + "\n" + "Ready to begin downloading. Press the button");
                        writeFileContentsToOutputArea(textPath);
                        System.out.println("Ready to begin downloading. Press the button");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    readyState = false;
                    startButton.setText("Set .txt File");
                    textPath = "";

                }

            }
        });
        useBlacklistBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (useBlacklistBox.isSelected()) {
                    useBlacklist = true;
                } else {
                    useBlacklist = false;
                }

            }
        });

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FileUtility fileUtility = new FileUtility();
                fileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "webm");
                fileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "json");
                fileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "mp3");
                if (readyState == false) {
                    outputArea.setText(outputArea.getText() + "\n" + "txt path has not been set. Launching chooserPane");
                    System.out.println(".txt path has not been set. Launching chooserPane");
                    String path = showTextFileChooser();
                    textPath = path;
                    COMPLETED_DIR = path.substring(0, path.lastIndexOf(File.separator));
                    try {
                        if (!textPath.equals("")) {
                            showWarning("File has been set.\nMake sure you add a new line for each URL");
                            readyState = true;
                            writeFileContentsToOutputArea(textPath);
                            startButton.setText("Start Download");
                            outputArea.setText(outputArea.getText() + "\n" + "Ready to begin downloading. Press the button");
                            File file = new File("lastFile.txt");
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            FileWriter fw = new FileWriter(file);
                            fw.write(textPath);
                            fw.close();


                            System.out.println("Ready to begin downloading. Press the button");
                        }
                    } catch (Exception ex) {

                    }
                } else {
                    Runnable runnable = () -> {
                        outputArea.setText("");
                        startButton.setEnabled(false);
                        downloadAndTag();
                        startButton.setEnabled(true);

                    };
                    Thread thread = new Thread(runnable);
                    thread.start();
                }
            }
        });
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new TagEditorScreen().setVisible(true);
            }
        });
        configureDownloadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new DownloadConfigPane().setVisible(true);
            }
        });
    }

    private void writeFileContentsToOutputArea(String path){
        File file = new File(path);
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()){
                String line = scanner.nextLine();
                outputArea.setText(outputArea.getText() + "\n" + line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * Create the directories for the downloaded and completed files
     */
    public void createDirectories(){
        File f2 = new File(COMPLETED_DIR);
        if (!f2.exists()) {
            f2.mkdir();
        }
    }

    /**
     * Show warning message
     */
    public static void showWarning(String message) {
        JOptionPane.showMessageDialog(null, message, "JUST YOUR FRIENDLY NEIGHBORLY REMINDER", JOptionPane.WARNING_MESSAGE);
    }

    /**
     * Show error message
     */
    public static void showError(String message) {
        JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * Convert timestamp to seconds hh:mm:ss or mm:ss
     * @param timestamp The timestamp to convert
     *                  Example: 01:03:20
     * @return The total number of seconds
     */
    public static int timestampToSeconds(String timestamp){
        int totalSeconds = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            Date date = sdf.parse(timestamp);
            int hours = date.getHours();
            int minutes = date.getMinutes();
            int seconds = date.getSeconds();
            totalSeconds = hours * 3600 + minutes * 60 + seconds;
            System.out.println(totalSeconds);
        }
        catch (Exception e){
            System.out.println("Error converting timestamp to seconds");
            e.printStackTrace();
        }
        return totalSeconds;

    }


}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage