Add support for telecinco.es
[GM_direct_download_links.git] / direct_download_links.user.js
1 // direct_download_links - Add direct download links
2 // version 0.4
3 // 2012-02-12
4 // Copyright (C) 2011,2012  Antonio Ospite <ospite@studenti.unina.it>
5 // Released under the GPL license
6 // http://www.gnu.org/copyleft/gpl.html
7 //
8 // --------------------------------------------------------------------
9 //
10 // This is a Greasemonkey user script.
11 //
12 // To install, you need Greasemonkey: https://addons.mozilla.org/en-US/firefox/addon/748
13 // Then restart Firefox and revisit this script.
14 // Under Tools, there will be a new menu item to "Install User Script".
15 // Accept the default configuration and install.
16 //
17 // To uninstall, go to Tools/Manage User Scripts,
18 // select "Direct Download Links", and click Uninstall.
19 //
20 // --------------------------------------------------------------------
21 //
22 // ==UserScript==
23 // @name           Direct Download Links
24 // @namespace      http://git.ao2.it/GM_direct_download_links.git
25 // @description    Add direct download links
26 // @include        http://video.repubblica.it/*
27 // @include        http://tv.repubblica.it/*
28 // @include        http://trovacinema.repubblica.it/*
29 // @include        http://www.kataweb.it/tvzap/*
30 // @include        http://www.rai.tv/*
31 // @include        http://soundcloud.com/*
32 // @include        http://www.telecinco.es/*
33 // ==/UserScript==
34 //
35
36 /*
37  * TODO:
38  *  - find a way to use the same string as in the @include lines to match the
39  *    current window.location. Look for something like GM_testUrl() which builds
40  *    the regexp starting from a glob line.
41  *  - use jquery, like shown in http://a32.me/2009/11/greasemonkey/
42  *  - Support the "download" attribute for anchors:
43  *    http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#downloading-resources
44  */
45
46 /* Fields supported by the "site" object.
47  *
48  * Manadatory fields:
49  *   locationRegExp: the regexp describing the URL of the page we are modifying
50  *   urlContainerXPath: the XPath of the element containing the URL to link
51  *   urlRegexp: the regular expression for finding the URL, the first
52  *              sub-pattern is taken as the URL
53  *   linkDestXPath: the XPath of the element where to place the Direct Download link
54  *
55  *
56  * Optional fields:
57  *
58  *   initCommand: a function called before the regExp is matched, this can
59  *                be useful in cases when some action needs to be done in
60  *                order to make the element containing the regExp be actually
61  *                rendered. It must accept  a 'site' parameter.
62  *
63  *   onEvent: used to delay the urlRegexp matching to a certain event like
64  *            'DOMNodeInserted' useful when the URL is added by some javascript
65  *            library. It has two fields:
66  *
67  *              evt: the event we want to wait for (e.g. 'DOMNodeInserted')
68  *
69  *              targetElement: the element in the event handler we want the
70  *                urlRegexp is performed on.
71  *
72  *  processURL: a function to process the URL before adding the Direct
73  *              Downdload Link to the page, it must accept  a 'site' and a
74  *              'URL' parameters and dispatch the UrlFetched to pass the
75  *              modified URL to _add_link().
76  *
77  */
78 var supported_sites = [
79   {
80     locationRegexp: /^http:\/\/video\.repubblica\.it\/.*$/,
81     urlContainerXPath: '//div[@id="contA"]',
82     urlRegexp: /[^\/]addParam\('format', '[^']*', '((http|mms):\/\/[^']*)'/,
83     linkDestXPath: '//div[@id="contA"]',
84   },
85   {
86     locationRegexp: /^http:\/\/tv\.repubblica\.it\/.*$/,
87     urlContainerXPath: '//div[@id="boxPlayer"]',
88     urlRegexp: /'pcUrl', '((http|mms):\/\/[^']*)'/,
89     linkDest: 'box_embed',
90     linkDestXPath: '//div[@id="box_embed"]',
91   },
92   {
93     locationRegexp: /^http:\/\/trovacinema\.repubblica\.it\/.*$/,
94     urlContainerXPath: '//div[@id="col-center"]',
95     urlRegexp: /'flvUrl', '((http|mms):\/\/[^']*)'/,
96     linkDestXPath: '//div[@id="col-center"]',
97   },
98   {
99     locationRegexp: /^http:\/\/www\.kataweb\.it\/tvzap\/.*$/,
100     urlContainerXPath: '//div[@id="tvzap_video"]',
101     urlRegexp: /'pcUrl', '((http|mms):\/\/[^']*)'/,
102     linkDestXPath: '//div[@id="tvzap_video"]',
103   },
104   {
105     locationRegexp: /^http:\/\/www\.rai\.tv\/.*$/,
106     initCommand: function(site) {
107       unsafeWindow.Silverlight.isInstalled = function(version) {
108         return true;
109       };
110     },
111     urlContainerXPath: '//div[@id="silverlightControlHost" or @id="SilverlightPlayer"]',
112     urlRegexp: /mediaUri=(http:\/\/[^,]*)/,
113     onEvent: { evt: 'DOMNodeInserted', targetElement: 'object' },
114     processURL: _rai_get_actual_url,
115     linkDestXPath: '//div[@id="silverlightControlHost" or @id="SilverlightPlayer"]',
116   },
117   {
118     locationRegexp: /^http:\/\/soundcloud.com\/.*$/,
119     urlContainerXPath: '//div[@id="main-content-inner"]',
120     urlRegexp: /"streamUrl":"([^"]*)"/,
121     linkDestXPath: '//div[@id="main-content-inner"]',
122   },
123   {
124     locationRegexp: /^http:\/\/www\.telecinco.es\/.*$/,
125     urlContainerXPath: '//video[@class="video-js"]',
126     urlRegexp: /src="([^"]*)"/,
127     linkDestXPath: '//div[@class="pg-bd"]',
128   },
129 ];
130
131 /* Apply different rules to different sites */
132 for (i = 0; i < supported_sites.length; i++) {
133   var site = supported_sites[i];
134
135   var result = window.location.href.match(site.locationRegexp);
136   if (result) {
137     if (site.initCommand) {
138       site.initCommand(site);
139     }
140     direct_download_link_add(window.location.href, site);
141   }
142 }
143
144 function getElementByXPath(query, root) {
145   return document.evaluate(query, root || document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
146 }
147
148 /* from http://stackoverflow.com/questions/1912501 */
149 function htmlDecode(input){
150   var e = document.createElement('div');
151   e.innerHTML = input;
152   return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
153 }
154
155 /**
156  * Add a Direct Download link on the page for the specified URL
157  *
158  * @param: a 'site' object described above.
159  *
160  * @return: null on error, true on success
161  */
162 function direct_download_link_add(pageURL, site) {
163   site.pageURL = pageURL;
164   var element = getElementByXPath(site.urlContainerXPath);
165   if (!element) {
166     DDL_log('DirectDL (' + site.pageURL  + '): Cannot find the element ' + site.urlContainerXPath + ' containing the URL.');
167     return null;
168   }
169
170   document.addEventListener('UrlFetched', _add_link, true);
171
172   // This is used for sites adding the URL to the DOM after DOMContentLoaded,
173   // for example by some javascript library (like Silverlight.js on rai.tv).
174   if (site.onEvent) {
175     element.addEventListener(site.onEvent.evt, function(e) {
176       if (site.onEvent.targetElement &&
177           e.target.tagName.toLowerCase() != site.onEvent.targetElement) {
178         DDL_log('DirectDL (' + site.pageURL  + '): skipping element ' + e.target.tagName);
179         return;
180       }
181      _get_URL(site, element);
182     }, false);
183     return;
184   }
185
186   _get_URL(site, element);
187 }
188
189 function _get_URL(site, element) {
190   var content = element.innerHTML;
191   if (!content) {
192     DDL_log('DirectDL (' + site.pageURL + '): content is null, cannot find URL.');
193     return;
194   }
195
196   var matches = content.match(site.urlRegexp);
197   if (!matches || matches.length < 2 || !matches[1]) {
198       DDL_log('DirectDL (' + site.pageURL + '): URL not found, check the urlRegexp');
199       return;
200   }
201   var URL = matches[1];
202   if (!URL) {
203     DDL_log('DirectDL (' + site.pageURL + '): cannot get the URL.');
204     return;
205   }
206
207   if (site.processURL) {
208     site.processURL(site, URL);
209     return;
210   }
211
212   var evt = document.createEvent('Event');
213   evt.initEvent('UrlFetched', true, true);
214   evt.site = site;
215   evt.URL = htmlDecode(URL);
216   document.dispatchEvent(evt);
217 }
218
219 function _add_link(e) {
220   var site = e.site;
221   var URL = e.URL;;
222
223   var destination = getElementByXPath(site.linkDestXPath);
224   if (!destination) {
225     DDL_log('DirectDl (' + site.pageURL + '): Cannot add the direct download link.');
226     return;
227   }
228
229   // Check if we added the link already, if so just update the href attribute.
230   // This is useful when _get_URL() is called on async events.
231   var download_link = document.getElementById('GM_direct_downaload_link');
232   if (download_link) {
233     download_link.setAttribute('href', URL);
234   } else {
235     download_link = document.createElement('a');
236     download_link.textContent = 'Direct Link';
237     download_link.setAttribute('id', 'GM_direct_downaload_link');
238     download_link.setAttribute('href', URL);
239     var style = 'background-color: white; color: blue;';
240     style += ' border: 2px solid red;'
241     style += ' float: right; font-size: large;';
242     style += ' padding: .5em; margin: 1em;'
243     style += ' position: relative; z-index: 1000;'
244     download_link.setAttribute('style', style);
245
246     destination.insertBefore(download_link, destination.firstChild);
247   }
248 }
249
250 function DDL_log(message) {
251   var debug = false;
252   if (debug) {
253     alert(message)
254   } else {
255     GM_log(message);
256   }
257 }
258
259 function _rai_get_actual_url(site, URL) {
260
261   // SmoothStreaming manifest files get added without processing, for now:
262   if (URL.match(/.*\.csm$/)) {
263     var evt = document.createEvent('Event');
264     evt.initEvent('UrlFetched', true, true);
265     evt.site = site;
266     evt.URL = URL;
267     document.dispatchEvent(evt);
268     return;
269   }
270
271   // http://www.neaveru.com/wordpress/index.php/2008/05/09/greasemonkey-bug-domnodeinserted-event-doesnt-allow-gm_xmlhttprequest/
272   setTimeout( function() {
273     GM_xmlhttpRequest({
274       method: "GET",
275       // XXX A custom header. This is the "clever" trick Rai uses to ensure
276       // the content is accessed by www.rai.tv only...
277       headers: {'viaurl': 'www.rai.tv'},
278       url: URL,
279       onload: function(response) {
280         text = response.responseText;
281         text = text.replace(/&/g, '&amp;')
282         parser = new DOMParser();
283         xmlDoc = parser.parseFromString(text, "text/xml");
284
285         // MMS streams
286         elems = xmlDoc.getElementsByTagName('REF');
287         if (elems.length > 0) {
288           href = elems[0].getAttribute('HREF');;
289
290           var evt = document.createEvent('Event');
291           evt.initEvent('UrlFetched', true, true);
292           evt.site = site;
293           evt.URL = href;
294           document.dispatchEvent(evt);
295         }
296         // SmoothStreaming streams
297         elems = xmlDoc.getElementsByTagName('playListItem');
298         if (elems.length > 0) {
299           href = elems[0].getAttribute('mediaSource');;
300
301           var evt = document.createEvent('Event');
302           evt.initEvent('UrlFetched', true, true);
303           evt.site = site;
304           evt.URL = href;
305           document.dispatchEvent(evt);
306         }
307       }
308     });
309   }, 0);
310 }