-
Notifications
You must be signed in to change notification settings - Fork 25
/
YouTube.java
383 lines (307 loc) · 15 KB
/
YouTube.java
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* This file is part of VidSnap.
*
* VidSnap is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* VidSnap is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VidSnap. If not, see <https://www.gnu.org/licenses/>.
*/
package com.mugames.vidsnap.extractor;
import android.util.Log;
import com.mugames.vidsnap.network.HttpRequest;
import com.mugames.vidsnap.utility.JSInterpreter;
import com.mugames.vidsnap.utility.MIMEType;
import com.mugames.vidsnap.utility.Statics;
import com.mugames.vidsnap.utility.UtilityClass;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.mugames.vidsnap.utility.UtilityClass.JSONGetter.*;
import static com.mugames.vidsnap.utility.UtilityInterface.*;
public class YouTube extends Extractor {
static final String get_video_Info = "https://www.youtube.com/get_video_info?html5=1&video_id=";
static final String embed_Info = "https://www.youtube.com/embed/";
static final String YT_URL = "https://www.youtube.com";
boolean webScratch;
String TAG = Statics.TAG + ":YouTube";
String[] PLAYER_REGEXS = new String[]{
"<script[^>]+\\bsrc=(\"[^\"]+\")[^>]+\\bname=[\"\\']player_ias\\/base",
"\"jsUrl\"\\s*:\\s*(\"[^\"]+\")",
"\"assets\":.+?\"js\":\\s*(\"[^\"]+\")"
};
String[] FUNCTION_REGEX = new String[]{
"\\b[cs]\\s*&&\\s*[adf]\\.set\\([^,]+\\s*,\\s*encodeURIComponent\\s*\\(\\s*([a-zA-Z0-9$]+)\\(",
"\\b[a-zA-Z0-9]+\\s*&&\\s*[a-zA-Z0-9]+\\.set\\([^,]+\\s*,\\s*encodeURIComponent\\s*\\(\\s*([a-zA-Z0-9$]+)\\(",
"(?:\\b|[^a-zA-Z0-9$])([a-zA-Z0-9$]{2})\\s*=\\s*function\\(\\s*a\\s*\\)\\s*\\{\\s*a\\s*=\\s*a\\.split\\(\\s*\"\"\\s*\\)",
"([a-zA-Z0-9$]+)\\s*=\\s*function\\(\\s*a\\s*\\)\\s*\\{\\s*a\\s*=\\s*a\\.split\\(\\s*\"\"\\s*\\)",
"([\"\\'])signature\\1\\s*,\\s*([a-zA-Z0-9$]+)\\(",
"\\.sig\\|\\|([a-zA-Z0-9$]+)\\(",
"yt\\.akamaized\\.net\\/\\)\\s*\\|\\|\\s*.*?\\s*[cs]\\s*&&\\s*[adf]\\.set\\([^,]+\\s*,\\s*(?:encodeURIComponent\\s*\\()?\\s*([a-zA-Z0-9$]+)\\(",
"\\b[cs]\\s*&&\\s*[adf]\\.set\\([^,]+\\s*,\\s*([a-zA-Z0-9$]+)\\(",
"\\b[a-zA-Z0-9]+\\s*&&\\s*[a-zA-Z0-9]+\\.set\\([^,]+\\s*,\\s*([a-zA-Z0-9$]+)\\(",
"\\bc\\s*&&\\s*a\\.set\\([^,]+\\s*,\\s*\\([^)]*\\)\\s*\\(\\s*([a-zA-Z0-9$]+)\\(",
"\\bc\\s*&&\\s*[a-zA-Z0-9]+\\.set\\([^,]+\\s*,\\s*\\([^)]*\\)\\s*\\(\\s*([a-zA-Z0-9$]+)\\(",
"\\bc\\s*&&\\s*[a-zA-Z0-9]+\\.set\\([^,]+\\s*,\\s*\\([^)]*\\)\\s*\\(\\s*([a-zA-Z0-9$]+)\\("
};
public String videoID;
static final String _URL_REGEX = ".+((?<=\\/).+)$";
static final String _URL_SHORTS_REGEX = "watch\\?v=(?:(.*)&|(.*))|(.*)\\?";
String jsFunctionName;
String jsCode;
int attempt = 0;
final boolean[] gotMedia = new boolean[]{false, false};//0-audio ;1-video
boolean isVideoDecrypted;
boolean isAudioDecrypted;
public YouTube(){
super("YouTube");
}
@Override
public void analyze(String url) {
getDialogueInterface().show("Analysing URL");
videoID = getId(url);
if (videoID == null) {
getDialogueInterface().error("URL Seems to be wrong", null);
return;
}
HttpRequest request = new HttpRequest(get_video_Info + videoID, getDialogueInterface(), response -> videoInfo(UtilityClass.decodeHTML(response)));
request.setType(HttpRequest.GET);
request.start();
}
private String getId(String url) {
String id;
Matcher m = Pattern.compile(_URL_REGEX).matcher(url);
if (m.find()) {
id = m.group(1);
if (id != null && id.contains("?")) {
m = Pattern.compile(_URL_SHORTS_REGEX).matcher(id);
if (m.find()) {
if (m.group(1) != null) return m.group(1);
if (m.group(2) != null) return m.group(2);
if (m.group(3) != null) return m.group(3);
}
} else return id;
}
return null;
}
int got = 0;
void analyzeCompleted() {
Log.d(TAG, "video updateVideoSize: ");
fetchDataFromURLs();
}
public void videoInfo(String info) {
if (info == null) {
fetchFromWebPage();
return;
}
getDialogueInterface().show("Downloading Player");
if (jsFunctionName == null || jsFunctionName.isEmpty())
getJSFile(new JSDownloaded() {
@Override
public void onDone() {
getDialogueInterface().show("Analysing data");
ExtractInfo(info);
}
});
else ExtractInfo(info);
}
private void fetchFromWebPage() {
webScratch = true;
String YT_INITIAL_BOUNDARY_RE = "(?:var\\s+meta|</script|\\n)";
String YT_INITIAL_PLAYER_RESPONSE_RE = "ytInitialPlayerResponse\\s*=\\s*(\\{.+?\\})\\s*;";
HttpRequest request = new HttpRequest("https://www.youtube.com/watch?v=" + videoID + "&bpctr=9999999999&has_verified=1", getDialogueInterface(), response -> {
Matcher matcher = Pattern.compile(String.format("%s\\s*%s", YT_INITIAL_PLAYER_RESPONSE_RE, YT_INITIAL_BOUNDARY_RE)).matcher(response);
if (matcher.find()) videoInfo(matcher.group(1));
});
request.setType(HttpRequest.GET);
request.start();
}
void ExtractInfo(String decoded) {
try {
JSONObject jsonObject = new JSONObject(UtilityClass.parseQueryString(decoded));
JSONObject player_response = getObj_or_Null(jsonObject, "player_response");
if (!webScratch && player_response == null) {
alternateURLs(attempt++);
return;
} else player_response = new JSONObject(decoded);
JSONObject streamingData = getObj_or_Null(player_response, "streamingData");
if (streamingData == null || streamingData.toString().equals("{}")) {
JSONObject playabilityStatus = getObj_or_Null(player_response, "playabilityStatus");
if (playabilityStatus != null) {
String status = playabilityStatus.getString("status");
if (status.equals("LOGIN_REQUIRED")) {
//playabilityStatus.getString("reason")
getDialogueInterface().error("Age restricted videos can't be downloaded", null);
return;
} else if (status.equals("UNPLAYABLE")) {
getDialogueInterface().error("Movies can't be downloaded", null);
return;
}
} else alternateURLs(attempt++);
return;
}
JSONArray formatsObj = getArray_or_Null(streamingData, "adaptiveFormats");//formats
for (int i = 0; i < formatsObj.length(); i++) {
JSONObject selectedJSON = new JSONObject(String.valueOf(formatsObj.getJSONObject(i)));
String unsupported = getString_or_Null(selectedJSON, "type");
if (unsupported != null) continue;
String mime = selectedJSON.getString("mimeType").split(";")[0];
String urlField = getString_or_Null(selectedJSON, "url");
final boolean isWebmAudio = mime.equals(MIMEType.AUDIO_WEBM);
final boolean isAudio = isWebmAudio || mime.equals(MIMEType.AUDIO_MP4);
if (!isAudio) {
String qual = selectedJSON.getString("qualityLabel");
if (formats.qualities.contains(qual))
continue;
formats.qualities.add(qual);
}
if (urlField == null) {
String signatureCipher = getString_or_Null(selectedJSON, "signatureCipher");
String z = UtilityClass.parseForSig(UtilityClass.decodeHTML(signatureCipher));
JSONObject signatureCipherObj = new JSONObject(z);
String sp = getString_or_Null(signatureCipherObj, "sp");
String s = signatureCipherObj.getString("s");
urlField = signatureCipherObj.getString("url");
if (isWebmAudio) {
if (formats.audioURLs.size() == 0) {
formats.audioSP = sp;
formats.audioURLs.add(urlField);
formats.audioSIG = s;
formats.audioMime.add(mime);
}
} else {
formats.videoSPs.add(sp);
formats.mainFileURLs.add(urlField);
formats.videoSIGs.add(s);
formats.fileMime.add(mime);
}
} else if (isAudio) {
if (isWebmAudio && formats.audioURLs.isEmpty()) {
formats.audioURLs.add(urlField);
formats.audioMime.add(mime);
}
} else {
formats.mainFileURLs.add(urlField);
formats.fileMime.add(mime);
}
}
JSONObject videoDetails = player_response.getJSONObject("videoDetails");
formats.title = videoDetails.getString("title").replaceAll("[\\\\/:*?\"<>|]+", "_");
JSONObject thumbnail = videoDetails.getJSONObject("thumbnail");
JSONArray thumbnails = thumbnail.getJSONArray("thumbnails");
JSONObject thumbIndex = getObj_or_Null(thumbnails, 3);
if (thumbIndex == null)
thumbIndex = getObj_or_Null(thumbnails, thumbnails.length() - 1);
formats.thumbNailsURL.add(thumbIndex.getString("url"));
tryDecrypt();
} catch (JSONException e) {
e.printStackTrace();
getDialogueInterface().error("Sorry this video can't be downloaded", e);
}
}
void tryDecrypt() {
if (formats.audioSIG == null) {
analyzeCompleted();
return;
}
new Thread(() -> decryptSignature(0,formats.audioSIG, formats.audioURLs.get(0), (index, decryptedSign, url) -> {
if (formats.audioSP == null) url += ("&signature=" + decryptedSign);
else url += ("&" + formats.audioSP + "=" + decryptedSign);
Log.d(TAG, "Video_Info Au: \n" + url);
formats.audioURLs.set(0, url);
isAudioDecrypted = true;
checkCompletion();
})).start();
for (int i = 0; i < formats.mainFileURLs.size(); i++) {
String urlRaw = formats.mainFileURLs.get(i);
String s = formats.videoSIGs.get(i);
String sp = formats.videoSPs.get(i);
int finalI = i;
new Thread(() -> decryptSignature(finalI,s, urlRaw, (index, decryptedSign, url) -> {
got++;
if (sp == null) url += "&signature=" + decryptedSign;
else url += ("&" + sp + "=" + decryptedSign);
Log.d(TAG, "Video_Info: \n" + url);
formats.mainFileURLs.set(index, url);
boolean isLast = got == formats.mainFileURLs.size();
if (isLast) {
got = 0;
isVideoDecrypted = true;
checkCompletion();
}
})).start();
}
}
private void checkCompletion() {
if (isVideoDecrypted && isAudioDecrypted) analyzeCompleted();
}
String validUrlWithSign(String url, String sp, String decryptedSign) {
if (sp == null) url += ("&signature=" + decryptedSign);
else url += ("&" + sp + "=" + decryptedSign);
return url;
}
void alternateURLs(int attempts) {
webScratch = false;
String[] dataURL = new String[]{String.format("https://www.youtube.com/get_video_info?html5=1&video_id=%s&el=embedded&ps=default&eurl=", videoID),
String.format("https://www.youtube.com/get_video_info?html5=1&video_id=%s&el=detailpage&ps=default&eurl=", videoID),
String.format("https://www.youtube.com/get_video_info?html5=1&video_id=%s&el=vevo&ps=default&eurl=", videoID)
};
Log.d(TAG, "alternateURLs: " + (attempts));
getDialogueInterface().show("Attempt " + (attempts + 1));
if (attempts >= 3) {
getDialogueInterface().error("URL Seems to be wrong", null);
return;
}
HttpRequest request = new HttpRequest(dataURL[attempts], getDialogueInterface(), response -> videoInfo(UtilityClass.decodeHTML(response)));
request.setType(HttpRequest.GET);
request.start();
}
void getJSFile(JSDownloaded jsDownloaded) {
ResponseCallBack responseCallBack = embedResponse -> {
for (String i : PLAYER_REGEXS) {
Pattern pattern = Pattern.compile(i);
Matcher matcher = pattern.matcher(embedResponse);
if (matcher.find()) {
String player_url = matcher.group(1);
player_url = player_url==null?"":player_url.replaceAll("\"", "");
HttpRequest request = new HttpRequest(YT_URL+player_url,getDialogueInterface(),response -> {
for (String j : FUNCTION_REGEX) {
Pattern funPattern = Pattern.compile(j);
Matcher funMatcher = funPattern.matcher(response);
if (funMatcher.find()) {
jsFunctionName = funMatcher.group(1);
jsCode = response;
jsDownloaded.onDone();
break;
}
}
});
request.setType(HttpRequest.GET);
request.start();
break;
}
}
};
HttpRequest request = new HttpRequest(embed_Info+videoID,getDialogueInterface(),responseCallBack);
request.setType(HttpRequest.GET);
request.start();
}
void decryptSignature(int index, String signature, String url, SignNotifier notifier) {
JSInterpreter jsInterpreter = new JSInterpreter(jsCode, null);
JSInterface jsInterface = jsInterpreter.Extract_Function(jsFunctionName);
char[] o = (char[]) jsInterface.resf(new String[]{signature});
notifier.onDecrypted(index, UtilityClass.charArrayToSting(o), url);
}
public interface JSDownloaded {
void onDone();
}
}