aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPinapelz <yukais@pinapelz.com>2023-12-15 14:59:42 -0800
committerPinapelz <yukais@pinapelz.com>2023-12-15 14:59:42 -0800
commit3eb233db33b89edbd18040020bc277a9974c11ab (patch)
tree191986a93c10a3a96a7b50756111d313dbb34e08
parentd9b49c38b92b87eb797c66d630d9243250bedb38 (diff)
code cleanup + add inital crossplatform implementationcross-platform-clean
-rw-r--r--ffmpeg.exebin49592832 -> 0 bytes
-rw-r--r--icon.pngbin0 -> 1721871 bytes
-rw-r--r--src/main/java/DownloadConfigPane.form20
-rw-r--r--src/main/java/Downloader.java220
-rw-r--r--src/main/java/FileUtility.java39
-rw-r--r--src/main/java/Main.java287
-rw-r--r--src/main/java/TagEditorScreen.java8
-rw-r--r--yt-dlp.exebin13770642 -> 0 bytes
8 files changed, 308 insertions, 266 deletions
diff --git a/ffmpeg.exe b/ffmpeg.exe
deleted file mode 100644
index e4e17f9..0000000
--- a/ffmpeg.exe
+++ /dev/null
Binary files differ
diff --git a/icon.png b/icon.png
new file mode 100644
index 0000000..bea865b
--- /dev/null
+++ b/icon.png
Binary files differ
diff --git a/src/main/java/DownloadConfigPane.form b/src/main/java/DownloadConfigPane.form
index 324f738..2935b75 100644
--- a/src/main/java/DownloadConfigPane.form
+++ b/src/main/java/DownloadConfigPane.form
@@ -1,21 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="DownloadConfigPane">
- <grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="6" column-count="5" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+ <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="500" height="400"/>
+ <xy x="20" y="20" width="450" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<vspacer id="ebbca">
<constraints>
- <grid row="0" column="4" row-span="2" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
+ <grid row="0" column="5" row-span="2" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="b2b01" class="javax.swing.JTextField" binding="urlField">
<constraints>
- <grid row="0" column="1" row-span="1" col-span="3" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
+ <grid row="0" column="1" row-span="1" col-span="4" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -33,7 +33,7 @@
</component>
<component id="397fe" class="javax.swing.JTextField" binding="toField">
<constraints>
- <grid row="1" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
+ <grid row="1" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -59,7 +59,7 @@
</component>
<component id="8697b" class="javax.swing.JLabel" binding="toLabel">
<constraints>
- <grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+ <grid row="1" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="To:"/>
@@ -75,7 +75,7 @@
</component>
<component id="be7e5" class="javax.swing.JButton" binding="addButton" default-binding="true">
<constraints>
- <grid row="2" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+ <grid row="2" column="0" row-span="1" col-span="5" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Add"/>
@@ -83,7 +83,7 @@
</component>
<component id="9d097" class="javax.swing.JButton" binding="saveButton" default-binding="true">
<constraints>
- <grid row="5" column="2" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+ <grid row="5" column="2" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Save"/>
@@ -91,7 +91,7 @@
</component>
<component id="c475a" class="javax.swing.JButton" binding="removeButton" default-binding="true">
<constraints>
- <grid row="3" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+ <grid row="3" column="0" row-span="1" col-span="5" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Remove"/>
@@ -99,7 +99,7 @@
</component>
<scrollpane id="2fcad" binding="tableScrollPane">
<constraints>
- <grid row="4" column="0" row-span="1" col-span="4" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+ <grid row="4" column="0" row-span="1" col-span="5" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
diff --git a/src/main/java/Downloader.java b/src/main/java/Downloader.java
new file mode 100644
index 0000000..d6a1f13
--- /dev/null
+++ b/src/main/java/Downloader.java
@@ -0,0 +1,220 @@
+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 java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.text.SimpleDateFormat;
+
+import javax.swing.*;
+import java.io.File;
+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;
+ }
+
+ public Downloader(String outputDirectory, JTextArea outputArea){
+ this.outputDirectory = outputDirectory;
+ this.outputArea = outputArea;
+ this.removeNonAlphaNumeric = false;
+ }
+
+ /**
+ * Tag mp3 with title, uploader, and image
+ * @param uploader Uploader of the video
+ * @param title Title of the video
+ * @param imageUrl URL of to the thumbnail image
+ */
+ 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"));
+ Tag tag = f.getTag();
+ System.out.println("Uploader: " + uploader);
+ System.out.println("Title: " + title);
+ tag.setField(FieldKey.ARTIST, uploader);
+ tag.setField(FieldKey.TITLE, title);
+ fileUtil.downloadImage(imageUrl, "img.jpg", formats);
+ Artwork cover = Artwork.createArtworkFromFile(new File("img.jpg"));
+ tag.addField(cover);
+ f.commit();
+ fileUtil.deleteFile("img.jpg");
+ }
+ 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;
+ }
+
+
+ /**
+ * Relays the console output from the CMD to the outputArea
+ * @param p The process to relay to the outputArea from
+ */
+ public void relayConsole(Process p) {
+ BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ String cmd_line;
+ while (true) {
+ try {
+ cmd_line = r.readLine();
+ if (cmd_line == null) {
+ break;
+ }
+ System.out.println(cmd_line);
+ outputArea.setText(outputArea.getText() + "\n" + cmd_line);
+ }
+ catch (IOException e) {
+ System.out.println("Error while relaying from CMD");
+ }
+ }
+ }
+
+
+ /*
+ Download a part of a video
+ */
+ public boolean download(String url, String stamp){
+ ArrayList<String> times = new ArrayList<>(Arrays.asList(stamp.split("-")));
+ String startTime = times.get(0);
+ String endTime = times.get(1);
+ int startSec = timestampToSeconds(startTime);
+ int endSec = timestampToSeconds(endTime);
+ String ytDlpExecutable = "yt-dlp" + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
+ String ffmpegExecutable = "ffmpeg" + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
+ try {
+ ProcessBuilder builder = new ProcessBuilder(
+ ytDlpExecutable,
+ "-vU",
+ "-f", "(bestaudio)",
+ "--external-downloader", ffmpegExecutable,
+ "--external-downloader-args", "ffmpeg_i:-ss " + startSec + " -to " + endSec,
+ "--output", "download/%(title)s_%(id)s.webm",
+ "--write-info-json",
+ url
+ );
+ builder.directory(new File(outputDirectory));
+ builder.redirectErrorStream(true);
+ Process p = builder.start();
+ 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 downloadedFile = fileUtil.findFileWithType(outputDirectory+"/download", "webm");
+ try{
+ ProcessBuilder ffmpegBuilder = new ProcessBuilder(
+ ffmpegExecutable,
+ "-i", downloadedFile.getAbsolutePath(),
+ "-vn",
+ "-ab", "128k",
+ "-ar", "44100",
+ "-y",
+ downloadedFile.getAbsolutePath().replace(".webm", ".mp3")
+ );
+ ffmpegBuilder.directory(new File(outputDirectory));
+ ffmpegBuilder.redirectErrorStream(true);
+ Process p = ffmpegBuilder.start();
+ relayConsole(p);
+ }
+ catch(Exception e){
+ JOptionPane.showMessageDialog(null, "An error occurred while converting to mp3: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
+ e.printStackTrace();
+ }
+ fileUtil.deleteFile(downloadedFile.getAbsolutePath()); // Delete old webm file
+
+ String info[] = fileUtil.parseInfoJSON(fileUtil.jsonToString(fileUtil.findJsonFile(outputDirectory+"/download")));
+ String uploader = info[1];
+ String title = info[0];
+ String urlID = info[2];
+ String imageUrl = "https://img.youtube.com/vi/" + urlID+"/";
+
+ if (removeNonAlphaNumeric) {
+ String newTitle = fileUtil.removeNonAlphaNumeric(title);
+ String newUploader = fileUtil.removeNonAlphaNumeric(uploader);
+ String newFileName = newTitle + "_" + newUploader + "_"+stamp+".mp3";
+ File oldFile = new File(outputDirectory + "/" + title + "[" + urlID + "].mp3");
+ File newFile = new File(outputDirectory + "/" + newFileName);
+ oldFile.renameTo(newFile);
+ }
+ tagMp3InDir(uploader, title, imageUrl, outputDirectory+"/download");
+ fileUtil.deleteFile(fileUtil.findJsonFile(outputDirectory+"/download"));
+ File downloadedMp3 = fileUtil.findFileWithType(outputDirectory+"/download", "mp3");
+ downloadedMp3.renameTo(new File(outputDirectory+"/"+downloadedMp3.getName()));
+ fileUtil.deleteFile(outputDirectory+"/download");
+ return true;
+ }
+
+ public boolean download(String url){
+ String ytDlpExecutable = "yt-dlp" + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
+ try {
+ String[] command = {ytDlpExecutable, "-f", "ba", "-x", "--audio-format", "mp3", "--write-info-json", url, "-o", "%(title)s[%(id)s].%(ext)s"};
+ ProcessBuilder processBuilder = new ProcessBuilder(command);
+ processBuilder.directory(new File(outputDirectory));
+ Process process = processBuilder.start();
+ 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);
+ return false;
+ }
+ String info[] = fileUtil.parseInfoJSON(fileUtil.jsonToString(fileUtil.findJsonFile(outputDirectory)));
+ String uploader = info[1];
+ String title = info[0];
+ String urlID = info[2];
+ String imageUrl = "https://img.youtube.com/vi/" + urlID + "/";
+
+ if (removeNonAlphaNumeric) {
+ String newTitle = fileUtil.removeNonAlphaNumeric(title);
+ String newUploader = fileUtil.removeNonAlphaNumeric(uploader);
+ String newFileName = newTitle + "_" + newUploader + ".mp3";
+ File oldFile = new File(outputDirectory + "/" + title + "[" + urlID + "].mp3");
+ File newFile = new File(outputDirectory + "/" + newFileName);
+ oldFile.renameTo(newFile);
+ }
+ fileUtil.deleteFile(fileUtil.findJsonFile(outputDirectory));
+ tagMp3InDir(uploader, title, imageUrl, outputDirectory);
+ return true;
+ }
+
+
+ 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;
+
+ }
+}
diff --git a/src/main/java/FileUtility.java b/src/main/java/FileUtility.java
index a39df78..1a05f3c 100644
--- a/src/main/java/FileUtility.java
+++ b/src/main/java/FileUtility.java
@@ -8,11 +8,13 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileUtility {
+
public void deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
@@ -24,6 +26,7 @@ public class FileUtility {
boolean successfulDownload = false;
int formatIndex = 0;
while(!successfulDownload) {
+ System.out.println("Attempting to download image at: " + url+formats[formatIndex]);
try {
FileOutputStream fos = new FileOutputStream(fileName);
URL urlObj = new URL(url+formats[formatIndex]);
@@ -40,6 +43,7 @@ public class FileUtility {
formatIndex++;
}
}
+ System.out.println("Image downloaded");
}
@@ -102,21 +106,7 @@ public class FileUtility {
return str.replaceAll("[^a-zA-Z0-9]", "");
}
- 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;
- }
- }
-
- public static File findFileType(String directory, String fileExt){
+ public static File findFileWithType(String directory, String fileExt){
File dir = new File(directory);
File[] files = dir.listFiles();
for(File file : files){
@@ -189,21 +179,8 @@ public class FileUtility {
}
}
- public static ArrayList<String> txtToArrayList(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;
- }
+
+
public String showDirectoryChooser(){
try {
JFileChooser fileChooser = new JFileChooser();
@@ -219,7 +196,7 @@ public class FileUtility {
return "";
}
//get the path of all mp3 files in a directory and return them as a file arraylist
- public ArrayList<File> getMp3Files(String path){
+ public 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 c82ccb8..a544001 100644
--- a/src/main/java/Main.java
+++ b/src/main/java/Main.java
@@ -2,10 +2,12 @@ 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;
@@ -16,17 +18,16 @@ 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";
- final static String DOWNLOADED_DIR = "downloaded";
- final static String COMPLETED_DIR = "completed";
+ private static String COMPLETED_DIR = "completed";
String textPath = "";
- String formats[] = {"maxresdefault.jpg", "mqdefault.jpg", "hqdefault.jpg"};
static JTextArea outputArea = new JTextArea("");
JPanel panel = new JPanel();
@@ -35,14 +36,14 @@ public class Main extends JFrame {
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 Default songs.txt file");
JCheckBox useBlacklistBox = new JCheckBox("Use Blacklist.txt");
JProgressBar progressBar = new JProgressBar();
- JLabel title = new JLabel("YouTube to MP3 Auto Tagging [1]");
+ JLabel title = new JLabel("YouTube to MP3 Auto Tagging [CrossPlatform]");
Boolean useBlacklist = false;
Boolean readyState = false;
Boolean useDefault = false;
- FileUtility fileUtil = new FileUtility();
public Main() {
initializeComponents();
@@ -55,173 +56,65 @@ public class Main extends JFrame {
new Main().setVisible(true);
}
- /**
- * Download and tag all songs in the text file
- */
- private void downloadAndTag() {
- ArrayList<String> songs = fileUtil.txtToArrayList(textPath);
- String timeAppend = "";
- boolean partFlag;
- for (int i = 0; i < songs.size(); i++) {
- try {
- fileUtil.deleteAllFilesDir(DOWNLOADED_DIR);
-
- //Check if user's URL wants to download a part or full audio based on commas
- ArrayList<String> splitStamp = new ArrayList<>(Arrays.asList(songs.get(i).split(",")));
- switch(splitStamp.size()){
- case 1:
- downloadContentFull(songs.get(i));
- partFlag = false;
- break;
- case 2:
- timeAppend = downloadContentPartial(splitStamp.get(0), splitStamp.get(1));
- partFlag = true;
- break;
-
- default:
- showError("Invalid Input: " + songs.get(i)+
- "\nReason: Invalid formatting. Please use the format: URL,START_TIME:END_TIME");
- return;
- }
-
- String info[] = fileUtil.parseInfoJSON(fileUtil.jsonToString(fileUtil.findJsonFile(DOWNLOADED_DIR))); //title,uploader
- String uploader = info[1];
- String title = info[0];
- String urlID = info[2];
- String imageUrl = "https://img.youtube.com/vi/" + urlID + "/";
-
- // Remove blacklisted words if asked to
- if (useBlacklist) {
- System.out.println("Using blacklist. Removing blacklisted words from title and uploader");
- uploader = fileUtil.removeBlacklist(uploader, BLACKLIST);
- title = fileUtil.removeBlacklist(title, BLACKLIST);
- }
-
- // Method downloads as MP4, then converts to MP3. It's faster
- File mp4File = fileUtil.findFileType(DOWNLOADED_DIR ,"mp4");
- mp4Tomp3(mp4File);
-
- boolean taggingSuccessful = tagMp3InDir(uploader, title, imageUrl);
- if(!taggingSuccessful)
- return;
-
- // If user wants to download a part of the video, append the time to the title. Else just move the file
- File mp3Path = fileUtil.findFileType(DOWNLOADED_DIR, "mp3");
- String destinationPath = partFlag ? COMPLETED_DIR+"/" + fileUtil.removeNonAlphaNumeric(title) + "[" + urlID + "]" + timeAppend + ".mp3" :
- COMPLETED_DIR+"/" + fileUtil.removeNonAlphaNumeric(info[0]) + "[" + urlID + "].mp3";
- System.out.println(destinationPath);
- fileUtil.moveFile(mp3Path.getAbsolutePath(), destinationPath);
- outputArea.setText(outputArea.getText() + "\n" + "Moved file to Completed Folder");
- System.out.println("Current Progress " + calculatePercentage(i + 1, songs.size()));
- progressBar.setValue(calculatePercentage(i + 1, songs.size()));
- } catch (Exception e) {
- showError("Error occured while downloading and tagging. Check the logs for more info");
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Tag mp3 with title, uploader, and image
- * @param uploader Uploader of the video
- * @param title Title of the video
- * @param imageUrl URL of to the thumbnail image
- */
- public boolean tagMp3InDir(String uploader, String title, String imageUrl) {//Tag mp3 file in downloaded directory
+ public static ArrayList<String> txtToList(String fileName) {
+ ArrayList<String> lines = new ArrayList<String>();
try {
- AudioFile f = AudioFileIO.read(fileUtil.findFileType(DOWNLOADED_DIR, "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);
- fileUtil.downloadImage(imageUrl, "img.jpg", formats);
- Artwork cover = Artwork.createArtworkFromFile(new File("img.jpg"));
- tag.addField(cover);
- f.commit();
- fileUtil.deleteFile("img.jpg");
- }
- catch(Exception e){
- showError("Error occured while tagging mp3. Check your program version");
- return false;
- }
- return true;
-
- }
-
- /**
- * Download part of YouTube URL in MP3 format
- * @param url Youtube URL
- */
- public static void downloadContentFull(String url) {//Download mp3 of youtube video using yt-dlp.exe. Ran from cmd
- try {
-
- ProcessBuilder builder = new ProcessBuilder(
- "yt-dlp.exe",
- "-vU",
- "--extract-audio",
- "--audio-format", "mp3",
- "--audio-quality", "0",
- "--output", DOWNLOADED_DIR+"/%(title)s_%(id)s.mp3",
- "--ffmpeg-location", "ffmpeg.exe",
- "--write-info-json",
- url
- );
- builder.redirectErrorStream(true);
- Process p = builder.start();
- relayConsole(p);
+ 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) {
- JOptionPane.showMessageDialog(null, "An Error occured while downloading using" +
- " yt-dlp", "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
-
+ return lines;
}
/**
- * Download part of YouTube URL in MP4 format
- * @param url Youtube URL
- * @param stamp Time stamp in format HH:MM:SS-HH:MM:SS
- * @return String of time stamp to be used on filename startTimeInSeconds to endTimeInSeconds
+ * 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
*/
- public static String downloadContentPartial(String url, String stamp) { //Download mp3 of youtube video using yt-dlp.exe. Ran from cmd
- System.out.println(url + " " + stamp);
- ArrayList<String> times = new ArrayList<>(Arrays.asList(stamp.split("-")));
- String startTime = times.get(0);
- String endTime = times.get(1);
+ 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);
+ }
- // Time to start in seconds and time to end in seconds
- int startSec = timestampToSeconds(startTime);
- int endSec = timestampToSeconds(endTime);
- try {
- ProcessBuilder builder = new ProcessBuilder(
- "yt-dlp.exe",
- "-vU",
- "-f","\"(bestvideo+bestaudio/best)[protocol!*=dash]\"",
- "--external-downloader", "ffmpeg.exe",
- "--external-downloader-args", "\"ffmpeg_i:-ss " + startSec + " -to " + endSec + "\"",
- "--output", "downloaded/%(title)s_%(id)s.mp4",
- "--write-info-json",
- url
- );
- builder.redirectErrorStream(true);
- Process p = builder.start();
- relayConsole(p);
- } catch (Exception e) {
- JOptionPane.showMessageDialog(null, "An Error occured while downloading using" +
- " yt-dlp", "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ 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));
}
- return startSec + "to" + endSec;
}
+
/**
* 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);
@@ -248,21 +141,32 @@ public class Main extends JFrame {
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));
- panel.add(useBlacklistBox);
- panel.add(Box.createVerticalStrut(8));
outputArea.setEditable(false);
- // make configureDownloadButton centered
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;
+ }
}
/**
@@ -273,7 +177,7 @@ public class Main extends JFrame {
@Override
public void actionPerformed(ActionEvent e) {
File f = new File("songs.txt");
- if (f.exists() & !f.isDirectory() && !useDefault) {
+ if (f.exists() && !f.isDirectory() && !useDefault) {
System.out.println("songs found");
textPath = "songs.txt";
showWarning("Default File has been set.\nMake sure you add a new line for each URL");
@@ -290,7 +194,7 @@ public class Main extends JFrame {
readyState = false;
outputArea.setText(outputArea.getText() + "\n" + "Cancelled. Please set a .txt file");
System.out.println("Cancelled. Please set a .txt file");
- startButton.setText("Set .txt file");
+ startButton.setText("Set Download File");
}
}
});
@@ -313,7 +217,9 @@ public class Main extends JFrame {
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");
- textPath = fileUtil.showTextFileChooser();
+ String path = showTextFileChooser();
+ textPath = path;
+ COMPLETED_DIR = path.substring(0, path.lastIndexOf("/"));
try {
if (!textPath.equals("")) {
showWarning("File has been set.\nMake sure you add a new line for each URL");
@@ -366,72 +272,11 @@ public class Main extends JFrame {
}
}
- /**
- * Convert mp4 to mp3 using ffmpeg
- * @param mp4File The mp4 file to convert
- */
- public static void mp4Tomp3(File mp4File){
- try {
- String mp4FileName = mp4File.getName();
- String mp3FileName = mp4FileName.substring(0, mp4FileName.length() - 4) + ".mp3";
- ProcessBuilder builder = new ProcessBuilder(
- "cmd.exe", "/c", "ffmpeg -i \"" + mp4File.getAbsolutePath() + "\" \""+DOWNLOADED_DIR+"/" + mp3FileName+"\""
- );
- builder.redirectErrorStream(true);
- Process p = builder.start();
- relayConsole(p);
- p.waitFor();
- System.out.println("Conversion of MP4 to MP3 complete");
-
- }
- catch (Exception e){
- e.printStackTrace();
- }
-
- }
-
- /**
- * Relays the console output from the CMD to the outputArea
- * @param p The process to relay to the outputArea from
- */
- public static void relayConsole(Process p) {
- BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
- String cmd_line;
- while (true) {
- try {
- cmd_line = r.readLine();
- if (cmd_line == null) {
- break;
- }
- outputArea.setText(outputArea.getText() + "\n" + cmd_line);
- System.out.println(cmd_line);
- }
- catch (IOException e) {
- System.out.println("Error while relaying from CMD");
- }
- }
- }
-
- /**
- * 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);
- }
/**
* Create the directories for the downloaded and completed files
*/
public void createDirectories(){
- File f = new File(DOWNLOADED_DIR);
- if (!f.exists()) {
- f.mkdir();
- }
File f2 = new File(COMPLETED_DIR);
if (!f2.exists()) {
f2.mkdir();
diff --git a/src/main/java/TagEditorScreen.java b/src/main/java/TagEditorScreen.java
index 7942912..d102537 100644
--- a/src/main/java/TagEditorScreen.java
+++ b/src/main/java/TagEditorScreen.java
@@ -118,7 +118,7 @@ public class TagEditorScreen extends JFrame {
}
private void populateSongList(){
- songList = fileUtil.getMp3Files(setDirPath); //get arraylist of all files in the directory
+ songList = fileUtil.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory
for (int i = 0; i < songList.size(); i++) {
addSongTable(songList.get(i));
}
@@ -183,9 +183,9 @@ public class TagEditorScreen extends JFrame {
}
f.commit();
clearSongTable();
- songList = fileUtil.getMp3Files(setDirPath); //get arraylist of all files in the directory
- for (int i = 0; i < songList.size(); i++) {
- addSongTable(songList.get(i));
+ songList = fileUtil.getMp3FilesAsList(setDirPath); //get arraylist of all files in the directory
+ for (File file : songList) {
+ addSongTable(file);
}
} catch (Exception ex) {
ex.printStackTrace();
diff --git a/yt-dlp.exe b/yt-dlp.exe
deleted file mode 100644
index 74c4876..0000000
--- a/yt-dlp.exe
+++ /dev/null
Binary files differ
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage