Download Manager

Download videos from various sites

// ==UserScript==
// @name         Download Manager
// @description  Download videos from various sites
// @namespace    http://mathiasnervik.no
// @version      0.4.4
// @author       Mathias Nervik
// @match        http*://hanime.tv/hentai-videos/*
// @match        http://hentaihaven.org/*/
// @match        http://ma.brazzers.com/scene/view/*/
// @match        http://ma.brazzers.com/series/*/
// @match        http://ma.brazzers.com/scene/preview/*/
// @match        http://ma.brazzers.com/scene/hqpics/*/
// @match        http://members.naughtyamerica.com/scene/*
// @match        http://members2.mofos.com/scene/view/*/
// @match        http://members.bangbros.com/*/movie/*
// @match        http://members6342abn.killergram.com/*.asp?page=*&id=*&model=*&site=*
// @match        http://mz.cumlouder.com/video/*
// @exclude      http://mz.cumlouder.com/video/*/download/*
// @require      https://code.jquery.com/jquery-3.1.0.min.js
// @grant        GM_download
// @grant        GM_setClipboard
// @grant        window.close
// @grant        GM_xmlhttpRequest
// @connect      *
// ==/UserScript==
$(document).ready(function(){
    var video = $('video').attr('src');
    var fname = 'video.mp4';

	var url = window.location.href;
	var domain = url.split('/')[2];

	function onBlur_closeWindow(){
		if(document.hasFocus()){
			setTimeout(onBlur_closeWindow, 100);
			return;
		}
		window.close();
	}
    
    function onFocus_setClipboard(){
        if(!document.hasFocus()){
            setTimeout(onFocus_setClipboard, 100);
            return;
        }
        console.log('clipboard: ' + title);
        GM_setClipboard(title);
    }
	
	function onDelay_closeWindow(){
		setTimeout(window.close, 1000);
	}
	
	function fileExists_closeWindow(filename, site, url = null){
		if(url === null) var network_url = "http://downloads/" + site + "/" + filename;
		else var network_url = url;
		
		GM_xmlhttpRequest({
			method: "head",
			url: network_url,
			onload: function(response){
				if(response.status == 200){
					console.log('close_window');
					window.close();
				}else{
					console.log('no_action_required');
				}
			},
			onerror: function(response){
				console.log('An error occured!');
				console.log(response.status);
			}
		});
	}
    
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

	switch(domain){
		case 'hanime.tv':
			var title_str = $('h1.title').text().replace(':', '').replace('?', '').replace(' Ep ' , ' ');
            
            var episode_nr = 1;
            var isNumeric = false;
            for(var i = 0; i < title_str.length; i++){
                if(!isNaN(title_str[i]) && title_str[i] != ' '){
                    console.log(title_str[i]);
                    isNumeric = true;
                    break;
                }
            }
            
            if(isNumeric){
                episode_nr = title_str.match(/\d+$/)[0]; // find a better way, as this will ignore numbers with more than one digit
                
                /*var length = title_str.split(episode_nr).length;
                if(length == 1){*/
                    var title = title_str.replace(episode_nr, 'Episode ' + episode_nr) + '.mp4';
                /*}else if(length > 1){
                    var title = title_str.replace(episode_nr);
                }*/
            }else{
                var title = title_str + ' Episode ' + episode_nr + '.mp4';
            }
            
            console.log(title);
            console.log(isNumeric);
            console.log(episode_nr);
			for(var i = 0; i < $('a.download-link').length; i++){ // remove btn's without MP4
				if($('a.download-link > span > span:nth-of-type(3)').eq(i).text() != 'mp4') $('a.download-link').eq(i).remove();
			}
			for(var i = $('a.download-link').length-1; i >= 0; i--){ // keep only one btn
				if(i) $('a.download-link').eq(i).remove();
			}
			
			var DL_link = $('a.download-link').first().attr('href');
			
			$('a.download-link').first().attr('download', title);
			$('a.download-link').removeAttr('href');
			
			$('h1.title').click(function(){
				var query = prompt("Specify Title", $('a.download-link').first().attr('download'));
				if(query != null) $('a.download-link').first().attr('download', query);
				else $('a.download-link').first().attr('download', title);
			});
			
            //onFocus_setClipboard();
            
			$('a.download-link').click(function(){
				var DL_title = $('a.download-link').first().attr('download');
				GM_download(DL_link, DL_title);
				GM_setClipboard(DL_title);
				//onDelay_closeWindow();
				onBlur_closeWindow();
			});
			break;
		case 'hentaihaven.org':
			var title = $('h1.long-title').text().trim().replace(' – Episode', '');
			$('.slide-toggle').click(function(){
				GM_setClipboard(title + '.mp4');
				GM_download(video, fname);
				onBlur_closeWindow();
			});
			break;
		case 'ma.brazzers.com':
			var base = 'http://ma.brazzers.com';
			var domain_str = 'brazzers.com';

			// Video can be downloaded
			if($('.scene-nav-tab').length){
				var tab = $('a[tab="video"]');
				if(tab.not('.open').length) window.location.href = base + tab.first().attr('href');
				else if(!tab.length) window.close();
			}else{
				window.location.reload();
			}
			// Video can be downloaded

			// Actors
			var actors = $('header > h2 > a');
			if(actors.length > 2) window.close();
			else var actor = actors.first().text().trim();
			// Actors

			var site = $('a.scene-view-label > .label-text').first().text().trim();

			// Title
			var title_element = $('header > h1');
			title_element.find('span').remove();
			var title = title_element.first().text().replace('?', '').replace(' : ', ' ').replace(' :', ' ').replace(': ', ' ').replace(':', ' ').trim();
			// Title

			var location = 'D:\\' + actor + '\\' + domain_str + '\\' + site;


			/*if($('.download-full:contains("HD")').length){
				var link = $('.download-full:contains("HD")').first().attr('href');
				var extension = $('.download-full:contains("HD") span').first().text().split(' ')[1].toLowerCase();
			}else if($('.download-full:contains("MP4")').length){
				var link = $('.download-full:contains("MP4")').first().attr('href');
				var extension = 'mp4';
			}else if($('.download-full:contains("MPEG")').length){
				var link = $('.download-full:contains("MPEG")').first().attr('href');
				var extension = 'mp4';
			}else{*/
				var link = $('.download-full').first().attr('href');
				var extension =  'mp4'; /*$('.download-full span').first().text().split(' ')[1].toLowerCase();*/
			/*}*/

			var fname = '[' + site + '] ' + actor + '_' + title + '.' + extension;
			var link = 'http://ma.brazzers.com' + link;
			
			$('#download').click(function(){
				GM_download(link, fname);
				GM_setClipboard(fname);
				onDelay_closeWindow();
			});
/*
			$('header > h1').click(function(){
				GM_setClipboard(title + '.' + extension.toLowerCase());
				onBlur_closeWindow();
			});
*/
			break;
		case 'members.naughtyamerica.com':
			var base = 'http://members.naughtyamerica.com';
			var domain_str = 'naughtyamerica.com';
            
            // reCreate basic functions
            // :contains -> case inSensitive
            $.expr[":"].contains = $.expr.createPseudo(function(arg) {
                return function( elem ) {
                    return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
                };
            });
            // reCreate basic functions
            
            // Functions
            function checkCategory_closeWindow(){
                if(!$('.categories').length){
                    setTimeout(checkCategory_closeWindow, 100);
                }else{
                    for(var i = 0; i < $('.categories > a').length; i++){
                        if($('.categories > a').eq(i).text().trim() == 'GG')
                            window.close();
                    }
                }
            }
            // Functions
			
			// Actors & window.close-events
			var actors = $('.new_title > p:first() > a');
			if(actors.length > 2 || $('.vr-help').length) window.close();
			else var actor = actors.first().text().trim();
			// Actors
			
			var site = $('.scene_site_title a').first().text().trim();
			if(site == 'Lesbian Girl on Girl') window.close();
            
            checkCategory_closeWindow();
			
			var location = 'D:\\' + actor + '\\' + domain_str + '\\' + site;
            var videoID = url.split('-')[url.split('-').length - 1];
			// Link
			$('#video_download > div:nth-of-type(3)').remove(); // remove on the go
			
			// Sort Links
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("4k")').parent().parent().parent().addClass('0'); // enable 4k download
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("HD 1080p")').parent().parent().parent().addClass('1');
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("HD 720p")').parent().parent().parent().addClass('2');
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("HD 480p")').parent().parent().parent().addClass('3');
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("HD  f4v 480")').parent().parent().parent().addClass('3');
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("DVD")').parent().parent().parent().addClass('4'); // 2000k
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("High")').parent().parent().parent().addClass('5'); // 1000k
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("700")').parent().parent().parent().addClass('6'); // 700k
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("FULL")').parent().parent().parent().addClass('7'); // Full
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("full")').parent().parent().parent().addClass('7'); // Full
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Full")').parent().parent().parent().addClass('7'); // Full
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Normal")').parent().parent().parent().addClass('8'); // 512k
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Low")').parent().parent().parent().addClass('9'); // 56k
            $('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("low")').parent().parent().parent().addClass('9'); // 56k
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("56k")').parent().parent().parent().addClass('9'); // 56k

			
			// Remove Links
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("MPEG")').parent().parent().parent().addClass('remove'); // disable MPEG download           
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Apple")').parent().parent().parent().addClass('remove'); // disable apple downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("QuickTime")').parent().parent().parent().addClass('remove'); // disable apple downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Mobile")').parent().parent().parent().addClass('remove'); // disable mobile downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("iPod")').parent().parent().parent().addClass('remove'); // disable mobile downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("3gp")').parent().parent().parent().addClass('remove'); // disable mobile downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("On the go")').parent().parent().parent().addClass('remove'); // disable partial downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("SD clip")').parent().parent().parent().addClass('remove'); // disable partial downloads
			$('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("Unknown")').parent().parent().parent().addClass('remove'); // disable unknown downloads
            $('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr > td > div > div:nth-of-type(2):contains("mpg")').parent().parent().parent().addClass('remove'); // disable mpg download

            
            $('tr.remove').remove(); // removes invalid formats
                        
			// Sort
			$(function(){
				$('table').append($('tr').get().sort(function(a, b){
					return parseInt($(a).attr('class')) - parseInt($(b).attr('class'));
				}));
			});
			// Sort
			
			var noClass = $('#video_download > div:nth-of-type(2) > table.media_table > tbody > tr:not("[class]")').length;
			
			// Categiries
			$('.site-name > strong:contains("Categories: ")').parent().addClass('categories');
			if($('.categories > a:contains("Threesome")').length || $('.categories > a:contains("Girl on Girl")').length) window.close();
            
            var link_tmp = $('#video_download > div:nth-of-type(2) > table.media_table a:contains("Full Movie")').first().attr('href');
            var filename_tmp = link_tmp.split('/')[link_tmp.split('/').length - 1].split('?')[0];
            var extension_tmp = filename_tmp.split('.')[filename_tmp.split('.').length - 1];
            var newFilename_tmp = '[' + site + '] ' + actor + '_' + videoID + '.' + extension_tmp;
            
            //fileExists_closeWindow(newFilename_tmp, domain_str);
            
			// Link
			$('.streaming_not').text('Download');
			$('.download_button, .streaming_not').click(function(){
				var link = $('#video_download > div:nth-of-type(2) > table.media_table a:contains("Full Movie")').first().attr('href');
				var filename = link.split('/')[link.split('/').length - 1].split('?')[0];
                var extension = filename.split('.')[filename.split('.').length - 1];
                var newFilename = '[' + site + '] ' + actor + '_' + videoID + '.' + extension;
                if(noClass === 0){
					GM_download(link, 'file.mp4');
					GM_setClipboard(newFilename);
					onBlur_closeWindow();
				}else{
					alert('An unsorted object was caught!');
				}
			});
			break;
		case 'members2.mofos.com':
			var domain_str = 'mofos.com';
            
            var videoID = url.split('/view/')[1].split('/')[0];
            
			var actor = $('a.model-name').first().text().trim();
			var title = $('.release-header-title').text().replace('?', '').replace(':', '').trim();
            //var title = videoID;
			var site = $('div.site-name > a').text().trim();
			
			
			$('.user-options-menu__download-frame-options > a').addClass('download');
			
			var link = $('.download').attr('href');
			var extension = $('.download').attr('href').split('/')[3].split('_')[0];
			
			if($('.tag-link:contains("Threesome")').length) window.close();

			var fname = '[' + site + '] ' + actor + '_' + title + '.' + extension;
            console.log(fname);
			
			$('.user-options-menu__download').click(function(){
				GM_download(link, fname);
				GM_setClipboard(fname);
				onBlur_closeWindow();
			});
            
			break;
		case 'members6342abn.killergram.com':
			var killergram_short = [
				'get shafted', 'booty packers', 'brown sugar', 'college babes', 'office antics',
				'gloryhole girls', 'chain smokers', 'dogging missions', 'club babes',
				'space hoppers', 'tattooed sluts', 'kinky couples', 'porn stars utd', 'street walkers',
				'hard-fi sex', 'voyeur cams', 'wife sluts',
				
				'anal rehab', 'burlesque xxx', 'cream my cunt', 'fetish sex clinic', 'girly riders', 'nylon cum sluts',
				'rock chicks', 'ru 4 hire', 'the handy man', 'the lady pimp', 'wishes cum true',
				
				'killergram platinum', 'lets get slippy', 'pornostatic'
			];
			var killergram_long = [
				'Baby Loves The Shaft', 'Booty Back Packers', 'Brown Sugar Rush', 'College Babes Exposed', 'Cum Into My Office',
				'Gloryhole Gaggers', 'Chain Smokers', 'On A Dogging Mission', 'Sexy Club Babes',
				'Space Hoppers', 'Tattooed Fuck Sluts', 'UK Reality Swingers', 'UK Soccer Babes', 'UK Street Walkers',
				'Urban Perversions', 'Voyeur Cam Sluts', 'Wife Slut Adventures',
				
				'Anal Rehab', 'Burlesque XXX', 'Cream My Cunt', 'Fetish Sex Clinic', 'Girly Riders', 'Nylon Cum Sluts',
				'Rock Chicks', 'Are You For Hire', 'The Handy Man', 'The Lady Pimp', 'Wishes Cum True',
				
				'Platinum', 'Lets Get Slippy', 'Pornostatic'
			];
			
		    var domain_str = 'killergram.com';
		    // Actor
		    var actors = $('span.modelstarring a');
		    if(actors.length > 1) window.close();
		    else var actor = actors.first().text().trim();
		    // Actor
			
			// Site
		    var site = decodeURIComponent(url.split('site=')[1]);
			
			for(var i = 0; i < killergram_short.length; i++){
				if(site == killergram_short[i]) site = killergram_long[i];
			}
			// Site
			
			//var location = 'D:\\' + domain_str + '\\' + actor + '\\' + site;
			
			$('span.episodeupdateevent:contains("Download Episode")').parent().find('a').addClass('download');
			
			for(var i = $('.download').length-1; i > 0; i--){
				$('.download').eq(i).remove();
			}
			
			var fname = $('.download').attr('href').split('/')[5];
			var title = fname.split('_')[1];
			var extension = fname.split('.')[1];
			
			var clipboard = '[' + site + '] ' + actor + '_' + title + '.' + extension;

			
			$('.download').attr('download', '');
			$('.download').click(function(){
				GM_setClipboard(clipboard);
				onBlur_closeWindow();
			});
			break;
		case 'members.bangbros.com':	
			// Model
			var starring = $('.profile-image');
			if(starring.length > 1) window.close();
			else starring = $('span.tag:contains("Cast:")').find('a.tagB').first().text().trim();
            starring = capitalizeFirstLetter(starring);
			// Model
			
			// Title
			var title = $('.vdo-hdd1').first().text().replace(':', '').replace('?', '').replace('w/', 'with ').replace('W/', 'with ').replace(/  /g, ' ').replace(/"/g, "'").trim();
			// Title
			
			// Link
			var link = $('.dropM:not(".dropMN") a').first().addClass('download').attr('href');
			// Link
			
			// Extension
			var extension = $('.download').text().split(' ')[1].toLowerCase().trim();
			// Extension
			
			var site = $('span.tag:contains("Website:")').find('a.tagB').first().text().replace(':', '').replace('?', '').trim();
			console.log(site);
			
			// Tags
			var tags = $('.tag:contains("Tags") > a.tagB');
			for(var i = 0; i < tags.length; i++){
				var tag = tags.eq(i).text().trim();
				if(tag == 'threesome') window.close();
			}
			// Tags
			
			console.log(starring);
			
			$('a:contains("Download video")').click(function(){
				var fname = '[' + site + '] ' +  starring + '_' + title + '.' + extension;
				console.log(fname);
				GM_setClipboard(fname);
				GM_download(link, fname);
				onBlur_closeWindow();
			});
			break;
		case 'mz.cumlouder.com':
			$('a.link-download').removeAttr('target');
			
			// Title
			var title = $('#titulo-escena > h2').text().trim().replace(':', '').replace('?', '');
			
			// Actor
			var actors = $('a#nombre-sitio');
			if(actors.length > 2) window.close();
			actor = localStorage.actor;
			
			
			var actor_element = $('div > a#nombre-sitio');
			
			var actor_error = true;
			for(var i = 0; i < actor_element.length; i++){
				var element_str = actor_element.eq(i).text().trim();
				if(actor == element_str) actor_error = false;
			}
			
			if(actor) console.log(actor);
			
			// Site
			var site = $('#btnSiteScenes').parent().find('#nombre-sitio').text().trim();
			
			// Extension
			var extension = 'mp4';
			
			$('#descargar').click(function(){
				if(actor_error){
					actor = prompt('Please enter name of actor');
					localStorage.actor = actor;
				}
				if(actor != null){
					$('a.link-download')[0].click();
					var fname = '[' + site + ']' + ' ' + actor + '_' + title + '.' + extension;
					GM_setClipboard(fname);
					onBlur_closeWindow();
				}else{
					$('div > a#nombre-sitio').removeAttr('href');
					$('div > a#nombre-sitio').click(function(){
						actor_error = false;
						actor = $(this).text().trim();
						localStorage.actor = actor;
					});
				}
			});
			
			var check_file = '[' + site + ']' + ' ' + actor + '_' + title + '.' + extension;
			var check_site = 'cumlouder.com';
			fileExists_closeWindow(check_file, check_site);
			fileExists_closeWindow(check_file, 'int_' + check_site);
			fileExists_closeWindow(check_file, 'error_' + check_site);
			
			check_file = '[' + site + ']' + ' ' + actor + '_' + title + '.log';
			fileExists_closeWindow(check_file, check_site); // placeholder for success
			fileExists_closeWindow(check_file, 'error_' + check_site); // placeholder for error
			fileExists_closeWindow('', '', 'http://error/Won\'t Start/' + title + '.url');
			break;
		default: console.log(domain);
	}
});