aboutsummaryrefslogtreecommitdiff
path: root/viewtube.js
blob: fbefce8d02e2557822cd1de48992dfcd865d2c62 (plain)
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
  Copyright (C) 2010 - 2017 Sebastian Luncan
  Copyright (C) 2017 Arun Isaac <arunisaac@systemreboot.net>

  This program 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
  (at your option) any later version.

  This program 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 this program. If not, see <http://www.gnu.org/licenses/>.

  Website: http://isebaro.com/viewtube
  Contact: http://isebaro.com/contact
*/

// ==========Variables========== //

(function() {
    // Userscript
    var userscript = 'ViewTube';

    // Page
    var page = {dom: document.documentElement.outerHTML, win: window, url: window.location.href};

    // Player
    var player = {};
    var mimetypes = {
	'MPEG': 'video/mpeg',
	'MP4': 'video/mp4',
	'WebM': 'video/webm',
	'FLV': 'video/x-flv',
	'MOV': 'video/quicktime',
	'M4V': 'video/x-m4v',
	'AVI': 'video/x-msvideo',
	'3GP': 'video/3gpp',
    };

    // Links
    var website = 'https://git.systemreboot.net/youtube-noscript-shim/about';
    var contact = 'mailto:arunisaac@systemreboot.net';

    // ==========Functions========== //

    function createElement (type, attributes, parent) {
	var element = document.createElement(type);
	for (var key in attributes) {
	    if (key == 'innerHTML') element.innerHTML = attributes[key];
	    else element.setAttribute(key, attributes[key]);
	}
	if (parent) parent.appendChild(element);
	return element;
    }

    function createVideoElement (attributes, parent, ...children) {
	return createElement.apply(null, ["video", Object.assign({controls: "controls", autoplay: "autoplay", volume: 0.8}, attributes), parent].concat(children));
    }

    function playDASHwithHTML5() {
	function playAudio (play) {
	    if (play) player["contentAudio"].play();
	    else player["contentAudio"].pause();
	}

	if (player['videoPlay'].indexOf('MP4') != -1) {
	    player["contentVideo"] = createVideoElement({src: player["videoList"][player["videoPlay"].replace(/MP4/, "Video MP4")]});
	    if (player['videoList']['High Bitrate Audio Opus'])
		player["contentAudio"] = createVideoElement({src: player["videoList"]["High Bitrate Audio Opus"]});
	    else if (player['videoList']['Medium Bitrate Audio Opus'])
		player['contentAudio'] = createVideoElement({src: player['videoList']['Medium Bitrate Audio Opus']});
	    else player['contentAudio'] = createVideoElement({src: player['videoList']['Medium Bitrate Audio MP4']});
	}
	else {
	    player["contentVideo"] = createVideoElement({src: player["videoList"][player["videoPlay"].replace(/WebM/, "Video WebM")]});
	    if (player['videoList']['High Bitrate Audio Opus'])
		player["contentAudio"] = createVideoElement({src: player["videoList"]["High Bitrate Audio Opus"]});
	    else if (player['videoList']['Medium Bitrate Audio Opus'])
		player["contentAudio"] = createVideoElement({src: player["videoList"]["Medium Bitrate Audio Opus"]});
	    else player["contentAudio"] = createVideoElement({src: player["videoList"]["Medium Bitrate Audio WebM"]});
	}
	player['contentAudio'].pause();
	player['contentVideo'].addEventListener('play', playAudio.bind(null, true), false);
	player['contentVideo'].addEventListener('pause', playAudio.bind(null, false), false);
	player['contentVideo'].addEventListener('ended', function() {
	    player['contentVideo'].pause();
	    player['contentAudio'].pause();
	}, false);
	player['contentVideo'].addEventListener('timeupdate', function() {
	    if (player['contentAudio'].paused && !player['contentVideo'].paused)
		player['contentAudio'].play();
	    if (Math.abs(player['contentVideo'].currentTime - player['contentAudio'].currentTime) >= 0.30)
		player['contentAudio'].currentTime = player['contentVideo'].currentTime;
	}, false);
	player["contentAudio"].classList.add("hide");
	player['contentVideo'].appendChild(player['contentAudio']);
    }

    function playMyVideo() {
	if (player['videoList'][player['videoPlay']] == 'DASH')
	    playDASHwithHTML5();
	else player["contentVideo"] = createVideoElement({src: player["videoList"][player["videoPlay"]],
							  poster: player["videoThumb"]});
	player['playerWindow'].appendChild(player['contentVideo']);
    }

    function cleanMyContent(content, unesc) {
	var myNewContent = content;
	if (unesc) myNewContent = unescape(myNewContent);
	return myNewContent.replace(/\\u0025/g,'%').replace(/\\u0026/g,'&').replace(/\\/g,'').replace(/\n/g,'');
    }

    function getMyContent(url, pattern, clean) {
	var myPageContent, myVideosParse;
	// Get content
	if (url == page.url) myPageContent = page.dom;
	else {
	    var xmlHTTP = new XMLHttpRequest();
	    xmlHTTP.open('GET', url, false);
	    xmlHTTP.send();
	    myPageContent = xmlHTTP.responseText;
	}
	// Match pattern
	if (pattern == "TEXT") return myPageContent;
	else {
	    if (clean) myPageContent = cleanMyContent(myPageContent, true);
	    myVideosParse = myPageContent.match(pattern);
	    return myVideosParse ? myVideosParse[1] : null;
	}
    }

    // =====YouTube===== //

    // Add stylesheet
    createElement("link", {rel: "stylesheet",
			   type: "text/css",
			   href: browser.extension.getURL("viewtube.css")},
		  document.head);

    /* Video Availability */
    var ytVideoUnavailable = document.querySelector("#player-unavailable");
    if (ytVideoUnavailable && (ytVideoUnavailable.className.indexOf('hid') == -1)) {
	var ytAgeGateContent = document.querySelector("#watch7-player-age-gate-content");
	if ((!ytAgeGateContent) || (ytAgeGateContent.indexOf('feature=private_video') != -1)) return;
    }

    /* Decrypt Signature */
    var ytScriptSrc;
    function ytDecryptSignature(s) {return null;}
    function ytDecryptFunction() {
	var ytSignFuncName, ytSignFuncBody, ytSwapFuncName, ytSwapFuncBody, ytFuncMatch;
	ytScriptSrc = ytScriptSrc.replace(/(\r\n|\n|\r)/gm, '');
	if (ytSignFuncName = (ytScriptSrc.match(/"signature"\s*,\s*([^\)]*?)\(/) || [])[1]) {
	    ytFuncMatch = ytSignFuncName.replace(/\$/, '\\$') + '\\s*=\\s*function\\s*' + '\\s*\\(\\w+\\)\\s*\\{(.*?)\\}';
	    if (ytSignFuncBody = (ytScriptSrc.match(ytFuncMatch) || [])[1]) {
		if (ytSwapFuncName = (ytSignFuncBody.match(/((\$|_|\w)+)\.(\$|_|\w)+\(\w,[0-9]+\)/) || [])[1]) {
		    ytFuncMatch = 'var\\s+' + ytSwapFuncName.replace(/\$/, '\\$') + '=\\s*\\{(.*?)\\};';
		    ytSwapFuncBody = (ytScriptSrc.match(ytFuncMatch) || [])[1];
		}
		if (ytSwapFuncBody) ytSignFuncBody = 'var ' + ytSwapFuncName + '={' + ytSwapFuncBody + '};' + ytSignFuncBody;
		ytSignFuncBody = 'try {' + ytSignFuncBody + '} catch(e) {return null}';
		ytDecryptSignature = new Function('a', ytSignFuncBody);
	    }
	}
    }

    /* Get Player Window */
    var ytPlayerWindow = document.querySelector("#player");
    if (!ytPlayerWindow) console.log("Couldn't get the player element.");
    else {
	/* Get Video Thumbnail */
	var ytVideoThumb = getMyContent(page.url, 'link\\s+itemprop="thumbnailUrl"\\s+href="(.*?)"', false)
	    || getMyContent(page.url, 'meta\\s+property="og:image"\\s+content="(.*?)"', false)
	    || ('https://img.youtube.com/vi/' + page.url.match(/(\?|&)v=(.*?)(&|$)/)[2] + '/0.jpg');

	/* Get Videos Content */
	var ytVideosEncodedFmts, ytVideosAdaptiveFmts, ytVideosContent, ytHLSVideos, ytHLSContent, ytVideoID, ytVideosInfo;
	ytVideosAdaptiveFmts = getMyContent(page.url, '"adaptive_fmts":\\s*"(.*?)"', false)
	    || getMyContent(page.url, '\\\\"adaptive_fmts\\\\":\\s*\\\\"(.*?)\\\\"', false);
	if (ytVideosEncodedFmts = getMyContent(page.url, '"url_encoded_fmt_stream_map":\\s*"(.*?)"', false)
	    || getMyContent(page.url, '\\\\"url_encoded_fmt_stream_map\\\\":\\s*\\\\"(.*?)\\\\"', false))
	    ytVideosContent = ytVideosEncodedFmts;
	else if (ytHLSVideos = getMyContent(page.url, '"hlsvp":\\s*"(.*?)"', false)
		 || getMyContent(page.url, '\\\\"hlsvp\\\\":\\s*\\\\"(.*?)\\\\"', false)) {
	    ytHLSVideos = cleanMyContent(ytHLSVideos, false);
	    if (ytHLSVideos.indexOf('keepalive/yes/') != -1)
		ytHLSVideos = ytHLSVideos.replace('keepalive/yes/', '');
	}
	else if (ytVideoID = page.url.match(/(\?|&)v=(.*?)(&|$)/)[2]) {
	    var ytVideoSts = getMyContent(page.url.replace(/watch.*?v=/, 'embed/').replace(/&.*$/, ''), '"sts"\\s*:\\s*(\\d+)', false);
	    var ytVideosInfoURL = page.win.location.protocol + '//' + page.win.location.hostname + '/get_video_info?video_id=' + ytVideoID + '&eurl=https://youtube.googleapis.com/v/' + ytVideoID + '&sts=' + ytVideoSts;
	    if ((ytVideosInfo = getMyContent(ytVideosInfoURL, 'TEXT', false)) &&
		(ytVideosEncodedFmts = ytVideosInfo.match(/url_encoded_fmt_stream_map=(.*?)&/)[1]))
		ytVideosContent = cleanMyContent(ytVideosEncodedFmts, true);
	    if (!ytVideosAdaptiveFmts && (ytVideosAdaptiveFmts = ytVideosInfo.match(/adaptive_fmts=(.*?)&/)[1]))
		ytVideosAdaptiveFmts = cleanMyContent(ytVideosAdaptiveFmts, true);
	}

	if (ytVideosAdaptiveFmts && !ytHLSVideos) {
	    if (ytVideosContent) ytVideosContent += ',' + ytVideosAdaptiveFmts;
	    else ytVideosContent = ytVideosAdaptiveFmts;
	}

	function removeElements (selector) {
	    document.querySelectorAll(selector).forEach(function (element) { element.remove(); });
	}

	/* Remove Player Window */
	removeElements("#placeholder-player");

	/* Remove Sidebar Ads */
	removeElements("#watch7-sidebar-ads");

	/* Playlist */
	var ytPlaylist, ytPlaceholderPlaylist;
	if ((ytPlaylist = document.querySelector("#player-playlist"))
	    && (ytPlaceholderPlaylist = document.querySelector("#placeholder-playlist")))
	    ytPlaceholderPlaylist.appendChild(ytPlaylist);

	/* Create Player */
	var ytDefaultVideo = 'Low Definition MP4';
	function ytPlayer() {
	    player = {
		'playerSocket': ytPlayerWindow,
		'playerWindow': document.querySelector("#player-api"),
		'videoList': ytVideoList,
		'videoPlay': ytDefaultVideo,
		'videoThumb': ytVideoThumb
	    };
	    playMyVideo();
	}

	/* Parse Videos */
	function ytVideos() {
	    var ytVideoFormats = {
		'5': 'Very Low Definition FLV',
		'17': 'Very Low Definition 3GP',
		'18': 'Low Definition MP4',
		'22': 'High Definition MP4',
		'34': 'Low Definition FLV',
		'35': 'Standard Definition FLV',
		'36': 'Low Definition 3GP',
		'37': 'Full High Definition MP4',
		'38': 'Ultra High Definition MP4',
		'43': 'Low Definition WebM',
		'44': 'Standard Definition WebM',
		'45': 'High Definition WebM',
		'46': 'Full High Definition WebM',
		'82': 'Low Definition 3D MP4',
		'83': 'Standard Definition 3D MP4',
		'84': 'High Definition 3D MP4',
		'85': 'Full High Definition 3D MP4',
		'100': 'Low Definition 3D WebM',
		'101': 'Standard Definition 3D WebM',
		'102': 'High Definition 3D WebM',
		'135': 'Standard Definition Video MP4',
		'136': 'High Definition Video MP4',
		'137': 'Full High Definition Video MP4',
		'138': 'Ultra High Definition Video MP4',
		'139': 'Low Bitrate Audio MP4',
		'140': 'Medium Bitrate Audio MP4',
		'141': 'High Bitrate Audio MP4',
		'171': 'Medium Bitrate Audio WebM',
		'172': 'High Bitrate Audio WebM',
		'244': 'Standard Definition Video WebM',
		'247': 'High Definition Video WebM',
		'248': 'Full High Definition Video WebM',
		'249': 'Low Bitrate Audio Opus',
		'250': 'Medium Bitrate Audio Opus',
		'251': 'High Bitrate Audio Opus',
		'266': 'Ultra High Definition Video MP4',
		'272': 'Ultra High Definition Video WebM',
		'298': 'High Definition Video MP4',
		'299': 'Full High Definition Video MP4',
		'302': 'High Definition Video WebM',
		'303': 'Full High Definition Video WebM',
		'313': 'Ultra High Definition Video WebM'
	    };
	    var ytVideoParse, ytVideoCode, myVideoCode;
	    for (var ytVideo of ytVideosContent.split(',')) {
		if ((!ytVideo.match(/^url/)) && (ytVideoParse = ytVideo.match(/(.*)(url=.*$)/)))
		    ytVideo = ytVideoParse[2] + '&' + ytVideoParse[1];
		if ((ytVideoCode = (ytVideo.match(/itag=(\d{1,3})/) || [])[1])
		    && (myVideoCode = ytVideoFormats[ytVideoCode])) {
		    ytVideo = cleanMyContent(ytVideo, true);
		    ytVideo = ytVideo.replace(/url=/, "");
		    if ((ytVideo.match(/itag=/g) || []).length > 1)
			ytVideo = ytVideo.replace(/itag=\d{1,3}/, "");
		    if ((ytVideo.match(/clen=/g) || []).length > 1)
			ytVideo = ytVideo.replace(/clen=\d+/, "");
		    if ((ytVideo.match(/lmt=/g) || []).length > 1)
			ytVideo = ytVideo.replace(/lmt=\d+/, "");
		    ytVideo = ytVideo.replace(/type=(video|audio).*?/, "").replace(/xtags=[^%=]*?/, "");
		    ytVideo = ytVideo.replace(/&&/g, "&").replace(/^&/, "").replace(/&$/, "");
		    if (ytVideo.match(/&sig=/)) ytVideo = ytVideo.replace(/&sig=/, '&signature=');
		    else if (ytVideo.match(/&s=/))
			if ((ytSig = ytVideo.match(/&s=(.*?)(&|$)/)) &&
			    (s = ytDecryptSignature(ytSig[1])))
			    ytVideo = ytVideo.replace(/&s=.*?(&|$)/, '&signature=' + s + '$1');
			else ytVideo = '';
		    ytVideo = cleanMyContent(ytVideo, true);
		    if (ytVideo.indexOf('ratebypass') == -1) ytVideo += '&ratebypass=yes';
		    if (ytVideo && ytVideo.indexOf('http') == 0)
			ytVideoList[myVideoCode] = ytVideo;
		}
	    }

	    if (Object.keys(ytVideoList).length > 0) {
		for (var container of ["Standard", "High", "Full High", "Ultra High"])
		    for (var definition of ["MP4", "WebM"])
			if (!ytVideoList[definition + " Definition " + container] &&
			    ytVideoList[definition + " Definition Video " + container])
			    ytVideoList[definition + " Definition " + container] = "DASH";
		ytPlayer();
	    }
	    else if (ytVideosContent.indexOf("conn=rtmp") != -1)
		console.log("This video uses the RTMP protocol and is not supported.");
	    else console.log("Couldn't get any video.");
	}

	/* Parse HLS */
	function ytHLS() {
	    var ytHLSFormats = {
		'92': 'Very Low Definition MP4',
		'93': 'Low Definition MP4',
		'94': 'Standard Definition MP4',
		'95': 'High Definition MP4',
		'96': 'Full High Definition MP4'
	    };
	    ytVideoList["Any Definition MP4"] = ytHLSVideos;
	    if (ytHLSContent) {
		var ytHLSVideo, ytVideoCodeParse, myVideoCode;
		if (ytHLSVideos = ytHLSContent.match(/(http.*?m3u8)/g))
		    for (var ytHLSVideo in ytHLSVideos)
			if (ytVideoCode = (ytHLSVideo.match(/\/itag\/(\d{1,3})\//) || [])[1]) {
			    myVideoCode = ytHLSFormats[ytVideoCode];
			    if (myVideoCode && ytHLSVideo)
				ytVideoList[myVideoCode] = ytHLSVideo;
			}
	    }
	    ytDefaultVideo = 'Any Definition MP4';
	    ytPlayer();
	}

	/* Get Videos */
	var ytVideoList = {}, ytScriptURL;
	if (ytVideosContent) {
	    if (ytVideosContent.match(/&s=/) || ytVideosContent.match(/,s=/) || ytVideosContent.match(/u0026s=/)) {
		if (ytScriptURL = getMyContent(page.url, '"js":\\s*"(.*?)"', true)
		    || getMyContent(page.url.replace(/watch.*?v=/, 'embed/').replace(/&.*$/, ''), '"js":\\s*"(.*?)"', true)) {
		    ytScriptURL = page.win.location.protocol + ytScriptURL;
		    try {
			if (ytScriptSrc = getMyContent(ytScriptURL, 'TEXT', false)) ytDecryptFunction();
			ytVideos();
		    }
		    catch(e) {
			try {
			    var oReq = new XMLHttpRequest();
			    oReq.open("GET", ytScriptURL);
			    oReq.onload = function(response) {
				if (response.readyState === 4 && response.status === 200 && response.responseText) {
				    ytScriptSrc = response.responseText;
				    ytDecryptFunction();
				    ytVideos();
				}
				else console.log("Couldn't get the signature content.");
			    };
			    oReq.onerror = console.log.bind(null, "Couldn't make the request. Make sure your browser user scripts extension supports cross-domain requests.");
			    oReq.send();
			}
			catch(e) {
			    console.log("Couldn't make the request. Make sure your browser user scripts extension supports cross-domain requests.");
			}
		    }
		}
		else console.log("Couldn't get the signature link.");
	    }
	    else ytVideos();
	}
	else if (ytHLSVideos) {
	    try {
		ytHLSContent = getMyContent(ytHLSVideos, 'TEXT', false);
		ytHLS();
	    }
	    catch(e) {
		try {
		    var oReq = new XMLHttpRequest();
		    oReq.open("GET", ytHLSVideos);
		    oReq.onload = function(response) {
			if (response.readyState === 4 && response.status === 200 && response.responseText)
			    ytHLSContent = response.responseText;
			ytHLS();
		    };
		    oReq.onerror = ytHLS;
		    oReq.send();
		}
		catch(e) {
		    ytHLS();
		}
	    }
	}
	else console.log("Couldn't get the videos content.");
    }

})();