Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var downloadedFilesCounter = 0;
- var numOfChunksToDownload;
- var downloadQueue = [];
- var currentDownloadName;
- var status = "idle";
- var theWindow = null;
- var firstTimeOpenWindow = 1;
- var chunksBaseUrl, quality, chunksURLQuery;
- function updataStatus(){
- downloadedFilesCounter++;
- let completedPercentage = (downloadedFilesCounter / (numOfChunksToDownload+1) ) ;
- let fullWidth = $("#progressBar"+downloadQueue[0].playlistid).width();
- let percentageDivWidth = $("#progressBarPercent"+downloadQueue[0].playlistid).width();
- let updatedWidth = parseInt(completedPercentage*fullWidth);
- if ( updatedWidth > percentageDivWidth)
- $("#progressBarPercent"+downloadQueue[0].playlistid).css("width", updatedWidth);
- if ( downloadedFilesCounter == (numOfChunksToDownload+1) )
- $("#progressBarPercent"+downloadQueue[0].playlistid).css({"background-color": "#e91e63", "width":"100%"}).text("ההורדה הושלמה!");
- else
- $("#progressBarPercent"+downloadQueue[0].playlistid).text("בהורדה: " + parseInt(completedPercentage*100) + "%");
- }
- var tmrCheckPlaylistLoad;
- var currentOpenCollectionId = $("#ovc_collections_list").find("li.active").find("a").attr("c-value");
- addDownloadButtons(currentOpenCollectionId);
- // add click event for all download buttons
- $(document).on("click", ".downloadButton", function(){
- var url = "https://opal.openu.ac.il/mod/ouilvideocollection/actions.php";
- var context = $(this).attr('context');
- var playlistId = $(this).attr('playlistid');
- downloadQueue.push( { context: context, playlistid: playlistId } );
- // add progress bar
- let videoTop = $("#playlist"+playlistId).find(".ovc_playlist_border");
- let progressBarDiv = $("<div id='progressBar"+playlistId+"'></div>").css({"background-color": "#01579B"});
- let progressBarPercentDiv = $("<div id='progressBarPercent"+playlistId+"'>ממתין להתחלת הורדה... <a href='javascript:void(0);' class='cancelDownload' context="+context+" playlistid="+playlistId+" style='color:lightgreen;font-size: 120%;margin-right:10px;'><b>בטל</b></a></div>").css({"color": "white"});
- progressBarDiv.append(progressBarPercentDiv);
- videoTop.prepend(progressBarDiv);
- $(".downloadButton[playlistid="+playlistId+"]").hide();
- getVideosOnQueue();
- });
- // add click event for all cancel download buttons
- $(document).on("click", ".cancelDownload", function(){
- var playlistId = $(this).attr('playlistid');
- downloadQueue = downloadQueue.filter(video => video.playlistid !== playlistId );
- $("#progressBar"+playlistId).remove();
- $(".downloadButton[playlistid="+playlistId+"]").show();
- });
- // automatically add download buttons when a new collection is loaded
- function onPlaylistLoad(){
- $(".collection_link").each(function(){
- $(this).on("click", function(){
- var cValue = $(this).attr("c-value");
- tmrCheckPlaylistLoad = setInterval(function(){handleCollectionChange(cValue)}, 300);
- });
- });
- }
- onPlaylistLoad();
- function handleCollectionChange (cValue) {
- if( $('#collection'+cValue).is(':visible') ){
- addDownloadButtons(cValue);
- clearInterval(tmrCheckPlaylistLoad);
- }
- }
- // adds download buttons to an open collection( a collection that has been loaded )
- function addDownloadButtons(collectionId) {
- // add buttons only if not been added before
- if ( $( "#collection"+collectionId ).find("button").length == 0 ) {
- var collectionDiv = $("#collection"+collectionId);
- var currentContext = collectionDiv.attr("cid");
- var videoCount = 0;
- collectionDiv.children().each(function(i) {
- let videoDescription = $(this).find("span.instructor_row");
- let currentPlaylistId = $(this).attr("id").substring(8);
- let buttonElement = $("<button></button>").text("הורד סרטון").attr('class','downloadButton').attr('context',currentContext).attr('playlistid',currentPlaylistId);
- buttonElement.css({"margin-right":"10px","background":"rgb(202, 60, 60)","color":"white","borderRadius":"4px","textShadow":"0 1px 1px rgba(0, 0, 0, 0.2)"});
- videoDescription.append(buttonElement);
- });
- }
- }
- function getPlaylistFile(context, playlistid){
- var courseIdStart = $('.coursename_header').children()[0].href.indexOf("id=");
- var courseIdNum = $('.coursename_header').children()[0].href.substring(courseIdStart+3);
- jQuery.ajax({
- type: "POST",
- url: "https://opal.openu.ac.il/mod/ouilvideocollection/actions.php",
- data: {action: "getplaylist", context: context, playlistid: playlistid, course: courseIdNum},
- success: function(data) {
- let anotherURL = "https://opal.openu.ac.il/local/ouil_video/player.php?mediaid=" + data.media.cipher;
- currentDownloadName = data.title;
- $.get(anotherURL, function(data) {
- let mediaStart = data.indexOf("media: ");
- let mediaEnd = data.indexOf("\"", mediaStart+11);
- let myMedia = data.substring(mediaStart+8, mediaEnd);
- let url = myMedia;
- $.get(url, function(data) {
- let playlistStart = data.indexOf("file=")+5;
- let playlistEnd = data.indexOf("\"", playlistStart+8);
- var playlistURL = data.substring(playlistStart+1, playlistEnd).replace("&", "&");
- let url = playlistURL;
- $.get(url, function(data) {
- let baseURL = playlistURL.substring(0, playlistURL.indexOf("playlist."))
- let quality_list = data.match(/BANDWIDTH=\d+/g).map(function(n){return parseInt(n.replace("BANDWIDTH=", ""))}).sort(function(a,b){ return a-b; });
- let highestQuality = quality_list[quality_list.length-1];
- let URLQuery = playlistURL.substring(playlistURL.indexOf("?"));
- chunksBaseUrl = baseURL;
- quality = highestQuality;
- chunksURLQuery = URLQuery;
- let url = chunksBaseUrl+"chunklist_b"+quality+".m3u8"+chunksURLQuery;
- $.get(url, function(data) {
- data = data.split("\n");
- let lastChunkLine = data[data.length-3];
- let lastChunkStart = lastChunkLine.indexOf("_", lastChunkLine.indexOf(quality));
- let lastChunkEnd = lastChunkLine.indexOf(".ts");
- let lastChunkNum = lastChunkLine.substring(lastChunkStart+1, lastChunkEnd);
- numOfChunksToDownload = parseInt(lastChunkNum);
- startVideoDownload();
- });
- });
- }, "text");
- });
- }
- });
- }
- function getVideosOnQueue(){
- if ( downloadQueue.length > 0 && status === "idle" ){
- status = "downloading";
- $("#progressBar"+downloadQueue[0].playlistid).css({"background-color": "#ddd"});
- $("#progressBarPercent"+downloadQueue[0].playlistid).css({"background-color": "#4CAF50", "display": "inline-block", "font-weight": "bold"}).html("בהורדה: 0%");
- getPlaylistFile(downloadQueue[0].context, downloadQueue[0].playlistid);
- }
- }
- function startVideoDownload(){
- if ( theWindow === null ){
- theWindow = window.open('https://opal.openu.ac.il/'+new Date().getTime(), "", 'toolbar=no,status=no,width=250,height=100');
- if (theWindow == null || typeof(theWindow)=='undefined') {
- alert('יש לאפשר פתיחת חלון נוסף (popup). ליד שורת הכתובת בדפדפן מופיע סימן קטן של אפשרות לאפשר popup,\n יש ללחוץ עליו ולבחור ב "Always allow pop-ups from. לאחר מכאן לרענן את הדף ולהפעיל שוב את הסקריפט. אחרי פעולה זה הסקריפט יפעל כהלכה.');
- }
- }
- var theDoc = theWindow.document,
- theScript = document.createElement('script');
- function injectThis() {
- var fileData = [];
- function addData(data, index){
- fileData[index] = data;
- window.opener.updataStatus();
- if ( window.opener.downloadedFilesCounter == (window.opener.numOfChunksToDownload+1) ){
- saveDownloadedFile();
- setTimeout(function(){window.opener.windowFinishedDownloading()}, 200);
- }
- }
- function startVideoDownload(chunksBaseUrl, quality, chunksURLQuery){
- for (i = 0; i <= window.opener.numOfChunksToDownload; i++) {
- let currentIndex = i;
- let xhr = new XMLHttpRequest();
- let url=chunksBaseUrl+"media_b"+quality+"_"+i+".ts"+chunksURLQuery;
- xhr.open('GET', url, true);
- xhr.responseType = 'blob';
- xhr.onload = function(e) {
- addData(xhr.response, currentIndex);
- }
- xhr.addEventListener("error", function(){ retryFailedRequest(chunksBaseUrl, quality, chunksURLQuery, currentIndex); });
- xhr.send();
- }
- }
- function retryFailedRequest(chunksBaseUrl, quality, chunksURLQuery, chunkNumber){
- let currentIndex = chunkNumber;
- let xhr = new XMLHttpRequest();
- let url = chunksBaseUrl+"media_b"+quality+"_"+currentIndex+".ts"+chunksURLQuery;
- xhr.open('GET', url, true);
- xhr.responseType = 'blob';
- xhr.onload = function(e) {
- addData(xhr.response, currentIndex);
- }
- xhr.addEventListener("error", function(){ setTimeout(function(){ retryFailedRequest(chunkStartUrl, chunkEndNameWithoutExtension, chunkNumber); }, 5000); });
- xhr.send();
- }
- function saveDownloadedFile() {
- let blob = new Blob(fileData, {type: "video/mp2t"});
- let a = document.body.appendChild(document.createElement('a'));
- let objectURL2 = URL.createObjectURL(blob);
- a.href = objectURL2;
- a.download = window.opener.currentDownloadName+".ts";
- a.click();
- a.remove(a);
- URL.revokeObjectURL(objectURL2);
- blob = null;
- a = null;
- // reset data for next download
- fileData = [];
- window.opener.downloadedFilesCounter = 0;
- window.opener.status = "idle";
- window.opener.downloadQueue.shift();
- }
- startVideoDownload(window.opener.chunksBaseUrl, window.opener.quality, window.opener.chunksURLQuery);
- }
- if ( firstTimeOpenWindow ){
- theScript.innerHTML = 'window.onload = ' + injectThis.toString() + ';';
- firstTimeOpenWindow = 0;
- }
- else {
- theScript.innerHTML = injectThis.toString() + 'injectThis();';
- }
- theDoc.body.appendChild(theScript);
- }
- function windowFinishedDownloading(){
- if ( downloadQueue.length === 0 ){
- theWindow.close();
- theWindow = null;
- firstTimeOpenWindow = 1;
- }
- else {
- theWindow.location.reload();
- getVideosOnQueue();
- }
- }
Add Comment
Please, Sign In to add comment