Video.mediaset.it native video player and direct links

This script allows you to watch and download videos on Video Mediaset.

נכון ליום 30-01-2018. ראה הגרסה האחרונה.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name        Video.mediaset.it native video player and direct links
// @namespace   http://andrealazzarotto.com
// @description This script allows you to watch and download videos on Video Mediaset.
// @include     http://www.video.mediaset.it/video/*
// @include     http://www.video.mediaset.it/programma/*
// @include     http://*.video.mediaset.it/player/playerIFrame*
// @include     http://www.mediaset.it/*
// @include     http://www.tgcom24.mediaset.it/video/
// @version     6.3.9
// @require     http://code.jquery.com/jquery-latest.min.js
// @grant       GM_xmlhttpRequest
// @grant       GM.xmlHttpRequest
// @connect     mediaset.it
// @connect     video.mediaset.it
// @connect     cdnselector.xuniplay.fdnames.com
// @connect     video.lazza.dk
// @license     GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
// ==/UserScript==

/* Greasemonkey 4 wrapper */
if (typeof GM !== "undefined" && !!GM.xmlHttpRequest)
  GM_xmlhttpRequest = GM.xmlHttpRequest;

var silverlightSupported = function() {
	var unavailable = navigator.platform.indexOf('Win') < 0 && navigator.platform.indexOf('Mac') < 0;
	unavailable = unavailable || navigator.userAgent.indexOf('PPC') > 0;
	return !unavailable;
};

var boxStyle = function(selector, color, textcolor) {
	$(selector).css({
		'padding': '.5em',
		'margin': '1em 4em',
		'text-align': 'center',
		'background-color': color,
		'color': textcolor
	});
	$(selector + ' a').css('color', textcolor);
};

var writeLive = function(stream, highquality) {
	$('<div id="stream-url">').insertAfter('#video-player');
	$('#stream-url').append('<p>Flusso della diretta <strong>da aprire con VLC o <code>ffplay</code>:</strong></p>')
		.append('<pre><code>' + stream + '</code></pre>')
		.append('<p>Flusso a <strong>qualità più alta:</strong></p>')
		.append('<pre><code>' + highquality + '</code></pre>');
	boxStyle('#stream-url', 'rgba(255,255,255,0.5)', 'black');
	$('#stream-url p').css('font-size', '15px');

	// kill login timeout
	unsafeWindow.userNotLogged = function() { return; };
	setTimeout(function() {
        $('.countdown').remove();
    }, 1000);
};

var handleLive = function(playlistUri) {
	GM_xmlhttpRequest({
		method: 'GET',
		url: playlistUri,
		headers: {
			'Accept': 'application/atom+xml,application/xml,text/xml'
		},
		onload: function(responseDetails) {
			var r = responseDetails.responseText;
			var doc = $.parseXML(r);
			var $xml = $( doc );
			var videoID = $xml.find('videoUrl').text();
			GM_xmlhttpRequest({
				method: 'GET',
				url: 'http://cdnselector.xuniplay.fdnames.com/GetCDN.aspx?type=livehls&streamid=' + videoID,
				headers: {
					'Accept': 'application/atom+xml,application/xml,text/xml'
				},
				onload: function(responseDetails) {
					var r = responseDetails.responseText;
					var doc = $.parseXML(r);
					var $xml = $( doc );
					var src = $xml.find('video').attr('src');
					var highquality = src.replace('index.m3u8', 'Stream(04)/index.m3u8');
					writeLive(src, highquality);
				}
			});
		}
	});
};

var fix_videoplayer = function() {
	setTimeout(function() {
		if($('#videoPlayer').length) {
			$('#videoPlayer').remove();
		}
		else {
			setTimeout(arguments.callee, 400);
		}
	}, 400);
};

var initialize = function(id) {
	$('#myVideoContainer').remove();
	$('.video-player')
		.prepend('<div id="myVideoContainer" class="pf-container"></div>')
		.prepend(
			'<script type="text/javascript">' +
			'var initializer;' +
			'var id = "' + id + '"; initializer = ' +
			'new PlayerFramework.Initializer({ "containerElement":' +
			'document.getElementById("myVideoContainer"), "id": id });' +
			'</script>'
		);
	fix_videoplayer();
	console.debug('Initialized.');
};

$(document).ready(function(){
	// handle live stream
	var playlistUri = (unsafeWindow.playlistUri || null);
	if (playlistUri !== null)
		return handleLive('http://www.mediaset.it' + playlistUri);

	// check if it contains a video
	if (unsafeWindow.CDN_SELECTOR_URL === null)
		return;

 	var base_selector = "https://video.lazza.dk/mediaset?id=";
 	var is_abroad = document.cookie.indexOf("countryCode=") > 0 && document.cookie.indexOf("countryCode=IT") < 0;

	if (is_abroad || (!silverlightSupported())) {
		unsafeWindow.CDN_SELECTOR_URL = base_selector;
		unsafeWindow.CDN_SELECTOR_SECURE_URL = base_selector;
	}

  $('.contenitoreMed_Italia').remove();

	// kill ads
	unsafeWindow.adsEnabled = false;

	var loc = window.location;
	var isIframe = (loc.href.indexOf("playerIFrame") > 0);
	var id = (unsafeWindow.videoMetadataId) || 0;
	if (!id) {
		if(isIframe)
			id = loc.href.split("id=")[1].split("&")[0];
		else {
			var chunks = loc.pathname.replace(/[\._]/g, "/").split("/");
			id = parseInt(chunks[chunks.length - 2]);
		}
	}

	// kill registration request
	if (!!unsafeWindow.trafficlight)
		initialize(id);

	GM_xmlhttpRequest({
		method: 'GET',
		url: base_selector + id,
		headers: {
			'Accept': 'application/atom+xml,application/xml,text/xml'
		},
		onload: function(responseDetails) {
			var r = responseDetails.responseText;
			var doc = $.parseXML(r);
			var $xml = $( doc );
			var videos = $xml.find("video");
			var vlinks = [];

			// parse video URLs
			videos.each(function (i) {
				var url = $( videos.get(i) ).attr("src");
				var type = url.slice(-3);
				var name = "";
				switch(type) {
					case "est": name = "Smooth streaming"; break;
					case "pl)": name = "Apple streaming"; break;
					case "flv": name = "Video FLV"; break;
					case "f4v": name = "Video F4V"; break;
					case "mp4": name = "Video MP4"; break;
					case "wmv": name = "Video WMV"; break;
				}
				vlinks.push( { na: name, url: url } );
			});

			// display video URLs
			var num = vlinks.length;

			if(isIframe)
				$('<div id="video-links">').appendTo('body');
			else {
				$('#box-apertura').css('padding-top', 0).after('<div id="video-links">');
			}
			for(var i=0; i<num; i++) {
				var o = vlinks[i];
				var s = '<a href="'+o.url+'">'+o.na+'</a>';
				$(s).appendTo('#video-links');
				if(i!=num-1)
					$('<span>&nbsp;|&nbsp;</span>').appendTo('#video-links');
			}
			boxStyle('#video-links', 'rgba(0,0,0,0.5)', 'white');

			if(isIframe) {
				$('#video-links').css({
					'position': 'absolute',
					'bottom': '1.5em',
					'left': '10%',
					'right': '10%',
					'font-size': '.9em',
					'z-index': '9999'
				})
				.append("<span id='close'>&times;</span>");
				$("#close").css({
					'font-weight': 'bold',
					'position': 'absolute',
					'right': '1em',
					'cursor': 'pointer'
				}).click(function() {
					$("#video-links").fadeOut();
				});
				boxStyle('#video-links', 'rgba(255,255,255,0.5)', 'black');
			}

			$("#spinner").remove();
		}
	});
});