diff options
| -rw-r--r-- | src/main/java/DownloadConfigPane.form | 10 | ||||
| -rw-r--r-- | src/main/java/DownloadConfigPane.java | 90 | ||||
| -rw-r--r-- | src/main/java/Downloader.java | 115 | ||||
| -rw-r--r-- | src/main/java/FileUtility.java | 106 | ||||
| -rw-r--r-- | src/main/java/Main.java | 291 | ||||
| -rw-r--r-- | src/main/java/TagEditorScreen.java | 103 | ||||
| -rw-r--r-- | src/main/java/UI/Modal.java | 34 |
7 files changed, 338 insertions, 411 deletions
diff --git a/src/main/java/DownloadConfigPane.form b/src/main/java/DownloadConfigPane.form index 2935b75..0dffefb 100644 --- a/src/main/java/DownloadConfigPane.form +++ b/src/main/java/DownloadConfigPane.form @@ -3,7 +3,7 @@ <grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="6" column-count="6" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="5" left="10" bottom="5" right="10"/> <constraints> - <xy x="20" y="20" width="450" height="400"/> + <xy x="20" y="20" width="530" height="400"/> </constraints> <properties/> <border type="none"/> @@ -110,6 +110,14 @@ </component> </children> </scrollpane> + <component id="a718f" class="javax.swing.JCheckBox" binding="fullVideoCheckBox" default-binding="true"> + <constraints> + <grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/> + </constraints> + <properties> + <text value="Full Video"/> + </properties> + </component> </children> </grid> </form> diff --git a/src/main/java/DownloadConfigPane.java b/src/main/java/DownloadConfigPane.java index ba2f6dd..7206d7e 100644 --- a/src/main/java/DownloadConfigPane.java +++ b/src/main/java/DownloadConfigPane.java @@ -22,6 +22,7 @@ public class DownloadConfigPane extends JFrame{ private JButton saveButton; private JButton removeButton; private JScrollPane tableScrollPane; + private JCheckBox fullVideoCheckBox; private String loadedPath; @@ -32,57 +33,50 @@ public class DownloadConfigPane extends JFrame{ initializeTable(); this.add(mainPanel); this.setVisible(true); - loadFromFileButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - loadConfigFromFile(); + loadFromFileButton.addActionListener(e -> loadConfigFromFile()); + addButton.addActionListener(e -> { + String url = urlField.getText(); + String from = fromField.getText(); + String to = toField.getText(); + if (url.isEmpty()){ + return; } - }); - saveButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - + if (from.length() != 8){ + from = "00:00:00"; + } + if (to.length() != 8){ + to = "00:00:00"; } + Object[] song = new Object[]{url, from, to}; + DefaultTableModel model = (DefaultTableModel) outputTable.getModel(); + model.addRow(song); }); - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String url = urlField.getText(); - String from = fromField.getText(); - String to = toField.getText(); - if (url.length() == 0){ - return; - } - if (from.length() != 8){ - from = "00:00:00"; - } - if (to.length() != 8){ - to = "00:00:00"; - } - Object[] song = new Object[]{url, from, to}; - DefaultTableModel model = (DefaultTableModel) outputTable.getModel(); - model.addRow(song); + removeButton.addActionListener(e -> { + int row = outputTable.getSelectedRow(); + if (row == -1){ + return; } + DefaultTableModel model = (DefaultTableModel) outputTable.getModel(); + model.removeRow(row); }); - removeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int row = outputTable.getSelectedRow(); - if (row == -1){ - return; - } - DefaultTableModel model = (DefaultTableModel) outputTable.getModel(); - model.removeRow(row); + + saveButton.addActionListener(e -> { + try { + saveConfigToFile(); + } catch (IOException ex) { + throw new RuntimeException(ex); } }); - saveButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - saveConfigToFile(); - } catch (IOException ex) { - throw new RuntimeException(ex); - } + fullVideoCheckBox.addActionListener(e -> { + if (fullVideoCheckBox.isSelected()){ + fromField.setEnabled(false); + fromField.setText("BEGINNING_OF_VIDEO"); + toField.setEnabled(false); + toField.setText("END_OF_VIDEO"); + } + else{ + fromField.setEnabled(true); + toField.setEnabled(true); } }); } @@ -90,7 +84,6 @@ public class DownloadConfigPane extends JFrame{ private void initializeTable() { DefaultTableModel model = new DefaultTableModel(); // center align the text in the table - DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment( JLabel.CENTER ); outputTable.setDefaultRenderer(String.class, centerRenderer); @@ -162,14 +155,10 @@ public class DownloadConfigPane extends JFrame{ DefaultTableModel model = (DefaultTableModel) outputTable.getModel(); model.addRow(song); // add headers to the table - - - } loadedPath = file.getAbsolutePath(); } catch (Exception e){ - e.printStackTrace(); JOptionPane.showMessageDialog(null, "Please choose a file with the download config format"); System.out.println("Invalid file selected"); loadedPath = null; @@ -205,8 +194,7 @@ public class DownloadConfigPane extends JFrame{ try{ writer.write(line + System.lineSeparator()); } - catch (Exception e){ - e.printStackTrace(); + catch (Exception ignored){ } System.out.println(line); } diff --git a/src/main/java/Downloader.java b/src/main/java/Downloader.java index c0e0651..cf4178c 100644 --- a/src/main/java/Downloader.java +++ b/src/main/java/Downloader.java @@ -11,26 +11,20 @@ import java.text.SimpleDateFormat; import javax.swing.*; import java.io.File; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; public class Downloader { - private String outputDirectory; - private JTextArea outputArea; - private boolean removeNonAlphaNumeric; - String formats[] = {"maxresdefault.jpg", "mqdefault.jpg", "hqdefault.jpg"}; - FileUtility fileUtil = new FileUtility(); - public Downloader(String outputDirectory, JTextArea outputArea, boolean removeNonAlphaNumeric){ - this.outputDirectory = outputDirectory; - this.outputArea = outputArea; - this.removeNonAlphaNumeric = removeNonAlphaNumeric; - } + private final String outputDirectory; + private final JTextArea outputArea; + String[] formats = {"maxresdefault.jpg", "mqdefault.jpg", "hqdefault.jpg"}; public Downloader(String outputDirectory, JTextArea outputArea){ this.outputDirectory = outputDirectory; this.outputArea = outputArea; - this.removeNonAlphaNumeric = false; } /** @@ -41,25 +35,24 @@ public class Downloader { */ public boolean tagMp3InDir(String uploader, String title, String imageUrl, String filePath) {//Tag mp3 file in downloaded directory try { - AudioFile f = AudioFileIO.read(fileUtil.findFileWithType(filePath, "mp3")); - System.out.println("File found at: " + fileUtil.findFileWithType(filePath, "mp3")); + AudioFile f = AudioFileIO.read(FileUtility.findFileWithType(filePath, "mp3")); + System.out.println("File found at: " + FileUtility.findFileWithType(filePath, "mp3")); Tag tag = f.getTag(); System.out.println("Uploader: " + uploader); System.out.println("Title: " + title); tag.setField(FieldKey.ARTIST, uploader); tag.setField(FieldKey.TITLE, title); - String pathToThumnail = fileUtil.downloadImage(imageUrl, "img.jpg", formats); + String pathToThumnail = FileUtility.downloadImage(imageUrl, "img.jpg", formats); Artwork cover = Artwork.createArtworkFromFile(new File(pathToThumnail)); tag.addField(cover); f.commit(); - fileUtil.deleteFile(pathToThumnail); + FileUtility.deleteFile(pathToThumnail); } catch(Exception e){ JOptionPane.showMessageDialog( null, "Error occured while tagging mp3. Check your program version", "ERROR", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); return false; } return true; @@ -114,9 +107,12 @@ public class Downloader { relayConsole(p); } catch (Exception e) { JOptionPane.showMessageDialog(null, "An error occurred while downloading using yt-dlp: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); } - File downloadedWebm = fileUtil.findFileWithType(System.getProperty("user.dir"), "webm"); + File downloadedWebm = FileUtility.findFileWithType(System.getProperty("user.dir"), "webm"); + if(downloadedWebm == null){ + UI.Modal.showError("Error finding downloaded webm file. Ensure that yt-dlp is able to download"); + return false; + } try{ ProcessBuilder builder = new ProcessBuilder( @@ -137,20 +133,39 @@ public class Downloader { JOptionPane.showMessageDialog(null, "An error occurred while converting the webm file to mp3: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } - String info[] = fileUtil.parseInfoJSON(fileUtil.jsonToString(fileUtil.findJsonFile(System.getProperty("user.dir")))); + String[] info = FileUtility.parseInfoJSON(FileUtility.jsonToString(FileUtility.findJsonFile(System.getProperty("user.dir")))); String uploader = info[1]; String title = info[0]; String urlID = info[2]; String imageUrl = "https://img.youtube.com/vi/" + urlID+"/"; - File downloadedMp3 = fileUtil.findFileWithType(System.getProperty("user.dir"), "mp3"); - String savedNonAlphaNumName = downloadedMp3.getName(); + File downloadedMp3 = FileUtility.findFileWithType(System.getProperty("user.dir"), "mp3"); + if(downloadedMp3 == null){ + UI.Modal.showError("Error finding downloaded mp3 file. Ensure that yt-dlp is able to download"); + return false; + } + String savedNonAlphaNumName; + try{ + savedNonAlphaNumName = downloadedMp3.getName(); + } + catch(NullPointerException ex){ + UI.Modal.showError("Error finding downloaded mp3 file. Ensure that yt-dlp is able to download"); + return false; + } String tempRemoveAlphaNumeric = savedNonAlphaNumName.replaceAll("[^a-zA-Z0-9]", "") + ".mp3"; - downloadedMp3.renameTo(new File(tempRemoveAlphaNumeric)); + if(!downloadedMp3.renameTo(new File(tempRemoveAlphaNumeric))) + UI.Modal.showError("Error renaming file"); tagMp3InDir(uploader, title, imageUrl, System.getProperty("user.dir")); - fileUtil.deleteFile(downloadedWebm.getAbsolutePath()); - fileUtil.deleteFile(fileUtil.findJsonFile(System.getProperty("user.dir"))); - downloadedMp3 = fileUtil.findFileWithType(System.getProperty("user.dir"), "mp3"); - downloadedMp3.renameTo(new File(outputDirectory+"/"+savedNonAlphaNumName)); + FileUtility.deleteFile(downloadedWebm.getAbsolutePath()); + FileUtility.deleteFile(FileUtility.findJsonFile(System.getProperty("user.dir"))); + downloadedMp3 = FileUtility.findFileWithType(System.getProperty("user.dir"), "mp3"); + if(downloadedMp3 == null){ + UI.Modal.showError("Error finding downloaded mp3 file. Ensure that yt-dlp is able to download"); + return false; + } + if(!downloadedMp3.renameTo(new File(outputDirectory+"/"+savedNonAlphaNumName+"["+startTime+"-"+endTime+"].mp3"))){ + UI.Modal.showError("Error moving file to output directory"); + return false; + } return true; } @@ -164,46 +179,54 @@ public class Downloader { relayConsole(process); process.waitFor(); } catch(Exception e){ - JOptionPane.showMessageDialog( - null, - "Error occured while downloading mp3. Check that you have yt-dlp installed", - "ERROR", JOptionPane.ERROR_MESSAGE); + UI.Modal.showError("Ensure yt-dlp is installed. An error occurred while downloading using yt-dlp: " + e.getMessage()); return false; } - String info[] = fileUtil.parseInfoJSON(fileUtil.jsonToString(fileUtil.findJsonFile(System.getProperty("user.dir")))); + String[] info = FileUtility.parseInfoJSON(FileUtility.jsonToString(FileUtility.findJsonFile(System.getProperty("user.dir")))); String uploader = info[1]; String title = info[0]; String urlID = info[2]; String imageUrl = "https://img.youtube.com/vi/" + urlID + "/"; - File downloadedMp3 = fileUtil.findFileWithType(System.getProperty("user.dir"), "mp3"); + File downloadedMp3 = FileUtility.findFileWithType(System.getProperty("user.dir"), "mp3"); + if(downloadedMp3 == null){ + UI.Modal.showError("Error finding downloaded mp3 file. Ensure that yt-dlp is able to download"); + return false; + } String savedNonAlphaNumName = downloadedMp3.getName(); String tempRemoveAlphaNumeric = savedNonAlphaNumName.replaceAll("[^a-zA-Z0-9]", "") + ".mp3"; - downloadedMp3.renameTo(new File(tempRemoveAlphaNumeric)); + if(!downloadedMp3.renameTo(new File(tempRemoveAlphaNumeric))){ + UI.Modal.showError("Error renaming file"); + return false; + } System.out.println("File renamed to: " + tempRemoveAlphaNumeric); - fileUtil.deleteFile(fileUtil.findJsonFile(System.getProperty("user.dir"))); + FileUtility.deleteFile(FileUtility.findJsonFile(System.getProperty("user.dir"))); tagMp3InDir(uploader, title, imageUrl, System.getProperty("user.dir")); - downloadedMp3 = fileUtil.findFileWithType(System.getProperty("user.dir"), "mp3"); - downloadedMp3.renameTo(new File(outputDirectory+"/"+savedNonAlphaNumName)); + downloadedMp3 = FileUtility.findFileWithType(System.getProperty("user.dir"), "mp3"); + if(downloadedMp3 == null){ + UI.Modal.showError("Error finding downloaded mp3 file. Ensure that yt-dlp is able to download"); + return false; + } + if(!downloadedMp3.renameTo(new File(outputDirectory+"/"+savedNonAlphaNumName))){ + UI.Modal.showError("Error moving file to output directory"); + return false; + } return true; } - public static int timestampToSeconds(String timestamp){ + 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(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + LocalTime time = LocalTime.parse(timestamp, formatter); + int hours = time.getHour(); + int minutes = time.getMinute(); + int seconds = time.getSecond(); totalSeconds = hours * 3600 + minutes * 60 + seconds; System.out.println(totalSeconds); - } - catch (Exception e){ + } catch (Exception e) { System.out.println("Error converting timestamp to seconds"); - e.printStackTrace(); } return totalSeconds; - } } diff --git a/src/main/java/FileUtility.java b/src/main/java/FileUtility.java index 61eba87..c29d21b 100644 --- a/src/main/java/FileUtility.java +++ b/src/main/java/FileUtility.java @@ -8,19 +8,20 @@ import java.nio.file.Files; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Objects;
public class FileUtility {
- public void deleteFile(String fileName) {
+ public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
- file.delete();
+ if(!file.delete())
+ System.out.println("Failed to delete file: " + fileName);
}
}
- public void deleteALlFileOfType(String path, String fileExt){
+ public static void deleteALlFileOfType(String path, String fileExt){
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for(int i=0;i<listOfFiles.length;i++){
@@ -32,7 +33,7 @@ public class FileUtility { }
}
- public String downloadImage(String url, String fileName,String[] formats) {
+ public static String downloadImage(String url, String fileName, String[] formats) {
boolean successfulDownload = false;
int formatIndex = 0;
String pathToImage = "";
@@ -64,81 +65,24 @@ public class FileUtility { return pathToImage;
}
- public String removeBlacklist(String s, String filename){
- HashMap<String, String> blacklist = arrayListToHashMap(readTextFile(filename),":");
- for(String key : blacklist.keySet()){
- if(s.contains(key)){
- s = s.replace(key,blacklist.get(key));
- }
- }
- return s;
-
-
- }
- //read a text file and return the contents as a hashmap with key value pairs
- public ArrayList<String> readTextFile(String fileName) {
- ArrayList<String> lines = new ArrayList<String>();
- try {
- BufferedReader br = new BufferedReader(new FileReader(fileName));
- String line;
- while ((line = br.readLine()) != null) {
- lines.add(line);
- }
- br.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return lines;
- }
-
- public HashMap<String, String> arrayListToHashMap(ArrayList<String> list, String delimiter) {
- HashMap<String, String> map = new HashMap<String, String>();
- for (String line : list) {
- String[] parts = line.split(delimiter);
- if (parts.length >= 2) {
- String key = parts[0];
- String value = parts[1];
- map.put(key, value);
- }
- else if(parts.length==1){
- String key = parts[0];
- String value = "";
- map.put(key, value);
- }
- else {
- System.out.println("ignoring line: " + line);
- }
- }
- return map;
- }
-
- public void moveFile(String source, String destination) {
- File sourceFile = new File(source);
- File destinationFile = new File(destination);
- sourceFile.renameTo(destinationFile);
- System.out.println("Moved file to Completed Folder");
- }
-
- public String removeNonAlphaNumeric(String str) {
- return str.replaceAll("[^a-zA-Z0-9]", "");
- }
-
public static File findFileWithType(String directory, String fileExt){
System.out.println("Searching for file with extension: " + fileExt + " in directory: " + directory);
File dir = new File(directory);
File[] files = dir.listFiles();
for(File file : files){
if(file.getName().endsWith(fileExt)){
+ System.out.println("Found file: " + file.getName());
return file;
}
}
+ System.out.println("No file found with extension: " + fileExt);
return null;
}
public static String findJsonFile(String folderName) {
File folder = new File(folderName);
File[] listOfFiles = folder.listFiles();
- for (int i = 0; i < listOfFiles.length; i++) {
+ for (int i = 0; i < Objects.requireNonNull(listOfFiles).length; i++) {
if (listOfFiles[i].isFile()) {
if (listOfFiles[i].getName().endsWith(".json")) {
return listOfFiles[i].getAbsolutePath();
@@ -173,15 +117,6 @@ public class FileUtility { }
return json;
}
- public static void deleteAllFilesDir(String path) {
- File folder = new File(path);
- File[] files = folder.listFiles();
- if (files != null) {
- for (File f : files) {
- f.delete();
- }
- }
- }
public static String showImageFileChooser() {
javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
@@ -197,9 +132,7 @@ public class FileUtility { }
}
-
-
- public String showDirectoryChooser(){
+ public static String showDirectoryChooser(){
try {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
@@ -213,8 +146,25 @@ public class FileUtility { }
return "";
}
+
+ 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;
+ }
+
//get the path of all mp3 files in a directory and return them as a file arraylist
- public ArrayList<File> getMp3FilesAsList(String path){
+ public static ArrayList<File> getMp3FilesAsList(String path){
ArrayList<File> mp3Files = new ArrayList<File>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 886afd4..f01ef3a 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,18 +1,18 @@ import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.io.*;
-import java.text.SimpleDateFormat;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
-import java.util.Date;
import java.util.Scanner;
import com.formdev.flatlaf.FlatIntelliJLaf;
import javax.swing.*;
-import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultCaret;
+import static UI.Modal.showTextFileChooser;
+
public class Main extends JFrame {
final static String BLACKLIST = "blacklist.txt";
@@ -48,36 +48,18 @@ public class Main extends JFrame { }
- 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);
+ private int calculatePercentage(int current, int total) {
+ return (int) (((double) current / (double) total) * 100);
}
public void downloadAndTag(){
- ArrayList<String> songs = txtToList(textPath);
+ ArrayList<String> songs = FileUtility.txtToList(textPath);
int totalSongs = songs.size();
int songsProcessed = 0;
for(String line: songs){
@@ -87,11 +69,15 @@ public class Main extends JFrame { String url = parts[0];
String stamp = parts[1];
Downloader downloader = new Downloader(COMPLETED_DIR, outputArea);
- downloader.download(url, stamp);
+ if(!downloader.download(url, stamp)){
+ UI.Modal.showError("Error downloading song: " + url + " at timestamp: " + stamp);
+ }
}
else{
Downloader downloader = new Downloader(COMPLETED_DIR, outputArea);
- downloader.download(line);
+ if(!downloader.download(line)){
+ UI.Modal.showError("Error downloading song: " + line);
+ }
}
songsProcessed++;
progressBar.setValue(calculatePercentage(songsProcessed, totalSongs));
@@ -146,134 +132,16 @@ public class Main extends JFrame { }
- 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);
- }
- });
+ defaultFileBox.addActionListener(e -> useLastInputTextFileLocation());
+ useBlacklistBox.addActionListener(e -> useBlacklist = useBlacklistBox.isSelected());
+ startButton.addActionListener(e -> startDownloadTagJobs());
+ editButton.addActionListener(e -> new TagEditorScreen().setVisible(true));
+ configureDownloadButton.addActionListener(e -> new DownloadConfigPane().setVisible(true));
}
private void writeFileContentsToOutputArea(String path){
@@ -285,7 +153,7 @@ public class Main extends JFrame { outputArea.setText(outputArea.getText() + "\n" + line);
}
} catch (FileNotFoundException e) {
- e.printStackTrace();
+ UI.Modal.showError("Unable to display contents of input file? Did you delete it?");
}
}
@@ -294,49 +162,110 @@ public class Main extends JFrame { * Create the directories for the downloaded and completed files
*/
public void createDirectories(){
- File f2 = new File(COMPLETED_DIR);
- if (!f2.exists()) {
- f2.mkdir();
+ Path completedDirPath = Paths.get(COMPLETED_DIR);
+ try {
+ Files.createDirectories(completedDirPath);
+ } catch (IOException e) {
+ UI.Modal.showError("Unable to create directories for completed files");
}
}
/**
- * Show warning message
+ * Set the text file input path to the location that was used last time
*/
- public static void showWarning(String message) {
- JOptionPane.showMessageDialog(null, message, "JUST YOUR FRIENDLY NEIGHBORLY REMINDER", JOptionPane.WARNING_MESSAGE);
+ private void useLastInputTextFileLocation(){
+ 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;
+ 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) {
+ UI.Modal.showError("Unable to read the last file path. Please select a new file instead");
+ }
+ } else {
+ readyState = false;
+ startButton.setText("Set .txt File");
+ textPath = "";
+
+ }
}
/**
- * Show error message
+ * Deletes any possible remaining files from previous jobs
*/
- public static void showError(String message) {
- JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
+ private void cleanRemainingFiles(){
+ FileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "webm");
+ FileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "json");
+ FileUtility.deleteALlFileOfType(System.getProperty("user.dir"), "mp3");
}
/**
- * 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
+ * Starts the download and tagging process
*/
- 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;
+ private void startDownloadTagJobs(){
+ cleanRemainingFiles();
+ if (!readyState) {
+ 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;
+ if(path == null){
+ UI.Modal.showWarning("No file has been selected... How did we get here?");
+ return;
+ }
+ COMPLETED_DIR = path.substring(0, path.lastIndexOf(File.separator));
+ try {
+ if (!textPath.isEmpty()) {
+ UI.Modal.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();
+ }
}
diff --git a/src/main/java/TagEditorScreen.java b/src/main/java/TagEditorScreen.java index d102537..26f2e29 100644 --- a/src/main/java/TagEditorScreen.java +++ b/src/main/java/TagEditorScreen.java @@ -28,7 +28,6 @@ public class TagEditorScreen extends JFrame { private JLabel artIconLabel; private JTextField searchField; private JButton listenButton; - private FileUtility fileUtil = new FileUtility(); private String setDirPath = ""; private String selectedAlbumArt = ""; private ArrayList<File> songList = new ArrayList<File>(); @@ -79,7 +78,7 @@ public class TagEditorScreen extends JFrame { DefaultTableModel model = (DefaultTableModel) songTable.getModel(); model.addRow(new Object[]{tag.getFirst(FieldKey.TITLE), tag.getFirst(FieldKey.ARTIST), audioFile.getAbsolutePath()}); } catch (Exception e) { - + UI.Modal.showError("Error while adding song to table, wasn't able to read file: " + audioFile.getAbsolutePath()); } } @@ -96,7 +95,7 @@ public class TagEditorScreen extends JFrame { listenButton.setEnabled(true); } catch (Exception e) { - e.printStackTrace(); + UI.Modal.showError("Error while populating fields, wasn't able to read file: " + audioFile.getAbsolutePath()); } } @@ -118,22 +117,20 @@ public class TagEditorScreen extends JFrame { } private void populateSongList(){ - songList = fileUtil.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory - for (int i = 0; i < songList.size(); i++) { - addSongTable(songList.get(i)); + songList = FileUtility.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory + for (File file : songList) { + addSongTable(file); } } private void initalizeListeners() { - chooseAudioDirectoryButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - clearSongTable(); - setDirPath = fileUtil.showDirectoryChooser(); - populateSongList(); - } + chooseAudioDirectoryButton.addActionListener(e -> { + clearSongTable(); + setDirPath = FileUtility.showDirectoryChooser(); + populateSongList(); }); + songTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { @@ -143,6 +140,7 @@ public class TagEditorScreen extends JFrame { imageSelected = false; } }); + songTable.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { @@ -153,7 +151,7 @@ public class TagEditorScreen extends JFrame { currPath = songTable.getModel().getValueAt(songTable.getSelectedRow() + 1, 2).toString(); imageSelected = false; } catch (Exception ex) { - + UI.Modal.showError("Seems that we aren't able to move down a row for some reason..."); } } else if (e.getKeyCode() == KeyEvent.VK_UP) { try { @@ -161,56 +159,53 @@ public class TagEditorScreen extends JFrame { currPath = songTable.getModel().getValueAt(songTable.getSelectedRow() - 1, 2).toString(); imageSelected = false; } catch (Exception ex) { - + UI.Modal.showError("Seems that we aren't able to move up a row for some reason..."); } } } }); - applyChangesButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - System.out.println("CURRENT PATH " + currPath); - AudioFile f = AudioFileIO.read(new File(currPath)); - Tag tag = f.getTag(); - tag.setField(FieldKey.TITLE, titleField.getText()); - tag.setField(FieldKey.ARTIST, uploaderField.getText()); - if (imageSelected) { - tag.deleteArtworkField(); - Artwork cover = Artwork.createArtworkFromFile(new File(selectedAlbumArt)); - tag.addField(cover); - System.out.println("Changed the Artwork"); - } - f.commit(); - clearSongTable(); - songList = fileUtil.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory - for (File file : songList) { - addSongTable(file); - } - } catch (Exception ex) { - ex.printStackTrace(); + applyChangesButton.addActionListener(e -> { + try { + System.out.println("CURRENT PATH " + currPath); + AudioFile f = AudioFileIO.read(new File(currPath)); + Tag tag = f.getTag(); + tag.setField(FieldKey.TITLE, titleField.getText()); + tag.setField(FieldKey.ARTIST, uploaderField.getText()); + if (imageSelected) { + tag.deleteArtworkField(); + Artwork cover = Artwork.createArtworkFromFile(new File(selectedAlbumArt)); + tag.addField(cover); + System.out.println("Changed the Artwork"); } - + f.commit(); + clearSongTable(); + songList = FileUtility.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory + for (File file : songList) { + addSongTable(file); + } + } catch (Exception ex) { + ex.printStackTrace(); } - }); - imageChooseButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - selectedAlbumArt = fileUtil.showImageFileChooser(); - File selectedFile = new File(selectedAlbumArt); - BufferedImage selectedImage = null; - selectedImage = ImageIO.read(selectedFile); - ImageIcon albumArtIcon = new ImageIcon(resizeImage(selectedImage, 260, 180)); - artIconLabel.setText(selectedFile.getName()); - artIconLabel.setIcon(albumArtIcon); - imageSelected = true; - - } catch (Exception ex) { + }); + imageChooseButton.addActionListener(e -> { + try { + selectedAlbumArt = FileUtility.showImageFileChooser(); + if(selectedAlbumArt == null){ + return; } + File selectedFile = new File(selectedAlbumArt); + BufferedImage selectedImage; + selectedImage = ImageIO.read(selectedFile); + ImageIcon albumArtIcon = new ImageIcon(resizeImage(selectedImage, 260, 180)); + artIconLabel.setText(selectedFile.getName()); + artIconLabel.setIcon(albumArtIcon); + imageSelected = true; + } catch (Exception ex) { + UI.Modal.showError("Error while selecting image"); } + }); listenButton.addActionListener(new ActionListener() { @Override diff --git a/src/main/java/UI/Modal.java b/src/main/java/UI/Modal.java new file mode 100644 index 0000000..5a48aa2 --- /dev/null +++ b/src/main/java/UI/Modal.java @@ -0,0 +1,34 @@ +package UI; + +import javax.swing.*; +import javax.swing.filechooser.FileNameExtensionFilter; + +public class Modal { + 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; + } + } + + /** + * 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); + } +} |
