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
|
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);
try {
ProcessBuilder builder = new ProcessBuilder(
"yt-dlp",
"-vU","--force-keyframes",
"-f", "bestaudio[ext=webm]",
"--download-sections","*"+startSec+"-"+endSec,
"-o", "%(title)s[%(id)s].%(ext)s",
"--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 downloadedWebm = fileUtil.findFileWithType(outputDirectory, "webm");
try{
ProcessBuilder builder = new ProcessBuilder(
"ffmpeg",
"-i", downloadedWebm.getAbsolutePath(),
"-vn",
"-ab", "128k",
"-ar", "44100",
"-y",
downloadedWebm.getAbsolutePath().replace(".webm", ".mp3")
);
builder.directory(new File(outputDirectory));
builder.redirectErrorStream(true);
Process p = builder.start();
relayConsole(p);
} catch(Exception e){
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(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 + "_"+stamp+".mp3";
File oldFile = new File(outputDirectory + "/" + title + "[" + urlID + "].mp3");
File newFile = new File(outputDirectory + "/" + newFileName);
oldFile.renameTo(newFile);
}
tagMp3InDir(uploader, title, imageUrl, outputDirectory);
fileUtil.deleteFile(downloadedWebm.getAbsolutePath());
fileUtil.deleteFile(fileUtil.findJsonFile(outputDirectory));
File downloadedMp3 = fileUtil.findFileWithType(outputDirectory, "mp3");
downloadedMp3.renameTo(new File(outputDirectory+"/"+downloadedMp3.getName()));
return true;
}
public boolean download(String url){
String ytDlpExecutable = "yt-dlp" + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
try {
String[] command = {ytDlpExecutable, "-f", "bestaudio[ext=webm]", "-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;
}
}
|