Support RaiReplay
[GM_direct_download_links.git] / direct_download_links.user.js
1 // direct_download_links - Add direct download links
2 // version 0.2
3 // 2011-11-14
4 // Copyright (C) 2011  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 // ==/UserScript==
32 //
33
34 /*
35  * TODO:
36  *  - find a way to use the same string as in the @include lines to match the
37  *    current window.location. Look for something like GM_testUrl() which builds
38  *    the regexp starting from a glob line.
39  *  - use xpath instead of regexp like in http://a32.me/2009/11/greasemonkey/
40  *  - use jquery, like shown in http://a32.me/2009/11/greasemonkey/
41  */
42
43 /* Fields supported by the "site" object.
44  *
45  * Manadatory fields:
46  *   pageURL: the URL of the page we are modifying
47  *   urlContainer: the element containing the URL to link
48  *   urlRegexp: the regular expression for finding the URL, the first
49  *              sub-pattern is taken as the URL
50  *   linkDest: the element where to place the Direct Download link
51  *
52  *
53  * Optional fields:
54  *
55  *   initCommand: a function called before the regExp is matched, this can
56  *                be useful in cases when some action needs to be done in
57  *                order to make the element containing the regExp be actually
58  *                rendered. It must accept  a 'site' parameter.
59  *
60  *   onEvent: used to delay the urlRegexp matching to a certain event like
61  *            'DOMNodeInserted' useful when the URL is added by some javascript
62  *            library. It has two fields:
63  *
64  *              evt: the event we want to wait for (e.g. 'DOMNodeInserted')
65  *
66  *              targetElement: the element in the event handler we want the
67  *                urlRegexp is performed on.
68  *
69  *  processURL: a function to process the URL before adding the Direct
70  *              Downdload Link to the page, it must accept  a 'site' and a
71  *              'URL' parameters and dispatch the UrlFetched to pass the
72  *              modified URL to _add_link().
73  *
74  */
75 var supported_sites = [
76   {
77     locationRegexp: /^http:\/\/video\.repubblica\.it\/.*$/,
78     urlContainer: 'contA',
79     urlRegexp: /'pcUrl', '((http|mms):\/\/[^']*)'/,
80     linkDest: 'contA',
81   },
82   {
83     locationRegexp: /^http:\/\/tv\.repubblica\.it\/.*$/,
84     urlContainer: 'boxPlayer',
85     urlRegexp: /'pcUrl', '((http|mms):\/\/[^']*)'/,
86     linkDest: 'box_embed',
87   },
88   {
89     locationRegexp: /^http:\/\/trovacinema\.repubblica\.it\/.*$/,
90     urlContainer: 'col-center',
91     urlRegexp: /'flvUrl', '((http|mms):\/\/[^']*)'/,
92     linkDest: 'col-center',
93   },
94   {
95     locationRegexp: /^http:\/\/www\.kataweb\.it\/tvzap\/.*$/,
96     urlContainer: 'tvzap_video',
97     urlRegexp: /'pcUrl', '((http|mms):\/\/[^']*)'/,
98     linkDest: 'playerCont',
99   },
100   {
101     locationRegexp: /^http:\/\/www\.rai\.tv\/.*$/,
102       initCommand: function(site) {
103         unsafeWindow.Silverlight.isInstalled = function(version) {
104           return true;
105         };
106     },
107     urlContainer: 'Player',
108     urlRegexp: /mediaUri=(http:\/\/[^,]*)/,
109     onEvent: { evt: 'DOMNodeInserted', targetElement: 'object' },
110     processURL: _rai_get_actual_url,
111     linkDest: 'Player',
112   },
113 ];
114
115 /* Apply different rules to different sites */
116 for (i = 0; i < supported_sites.length; i++) {
117   var site = supported_sites[i];
118
119   var result = window.location.href.match(site.locationRegexp);
120   if (result) {
121     if (site.initCommand) {
122       site.initCommand(site);
123     }
124     direct_download_link_add(window.location.href, site);
125   }
126 }
127
128 /**
129  * Add a Direct Download link on the page for the specified URL
130  *
131  * @param: a 'site' object described above.
132  *
133  * @return: null on error, true on success
134  */
135 function direct_download_link_add(pageURL, site) {
136   var element = document.getElementById(site.urlContainer);
137   if (!element) {
138     DDL_log('DirectDL (' + site.pageURL  + '): Cannot find the element ' + site.urlContainer + ' containing the URL.');
139     return null;
140   }
141
142   document.addEventListener('UrlFetched', _add_link, true);
143
144   // This is used for sites adding the URL to the DOM after DOMContentLoaded,
145   // for example by some javascript library (like Silverlight.js on rai.tv).
146   if (site.onEvent) {
147     element.addEventListener(site.onEvent.evt, function(e) {
148       if (site.onEvent.targetElement &&
149           e.target.tagName.toLowerCase() != site.onEvent.targetElement) {
150         DDL_log('DirectDL (' + site.pageURL  + '): skipping element ' + e.target.tagName);
151         return;
152       }
153      _get_URL(site, element);
154     }, false);
155     return;
156   }
157
158   _get_URL(site, element);
159 }
160
161 function _get_URL(site, element) {
162   var content = element.innerHTML;
163   if (!content) {
164     DDL_log('DirectDL (' + site.pageURL + '): content is null, cannot find URL.');
165     return;
166   }
167
168   var matches = content.match(site.urlRegexp);
169   if (!matches || matches.length < 2 || !matches[1]) {
170       DDL_log('DirectDL (' + site.pageURL + '): URL not found, check the urlRegexp');
171       return;
172   }
173   var URL = matches[1];
174   if (!URL) {
175     DDL_log('DirectDL (' + site.pageURL + '): cannot get the URL.');
176     return;
177   }
178
179   if (site.processURL) {
180     site.processURL(site, URL);
181     return;
182   }
183
184   var evt = document.createEvent('Event');
185   evt.initEvent('UrlFetched', true, true);
186   evt.site = site;
187   evt.URL = URL;
188   document.dispatchEvent(evt);
189 }
190
191 function _add_link(e) {
192   var site = e.site;
193   var URL = e.URL;;
194
195   var destination = document.getElementById(site.linkDest);
196   if (!destination) {
197     DDL_log('DirectDl (' + site.pageURL + '): Cannot add the direct download link.');
198     return;
199   }
200
201   // Check if we added the link already, if so just update the href attribute.
202   // This is useful when _get_URL() is called on async events.
203   var download_link = document.getElementById('GM_direct_downaload_link');
204   if (download_link) {
205     download_link.setAttribute('href', URL);
206   } else {
207     download_link = document.createElement('a');
208     download_link.textContent = 'Direct Link';
209     download_link.setAttribute('id', 'GM_direct_downaload_link');
210     download_link.setAttribute('href', URL);
211     var style = 'background-color: white; color: blue;';
212     style += ' border: 2px solid red;'
213     style += ' float: right; font-size: large;';
214     style += ' padding: .5em; margin: 1em;'
215     download_link.setAttribute('style', style);
216
217     destination.insertBefore(download_link, destination.firstChild);
218   }
219 }
220
221 function DDL_log(message) {
222   var debug = false;
223   if (debug) {
224     alert(message)
225   } else {
226     GM_log(message);
227   }
228 }
229
230 function _rai_get_actual_url(site, URL) {
231
232   // SmoothStreaming manifest files get added without processing, for now:
233   if (URL.match(/.*\.csm$/)) {
234     var evt = document.createEvent('Event');
235     evt.initEvent('UrlFetched', true, true);
236     evt.site = site;
237     evt.URL = URL;
238     document.dispatchEvent(evt);
239     return;
240   }
241
242   // http://www.neaveru.com/wordpress/index.php/2008/05/09/greasemonkey-bug-domnodeinserted-event-doesnt-allow-gm_xmlhttprequest/
243   setTimeout( function() {
244     GM_xmlhttpRequest({
245       method: "GET",
246       // XXX A custom header. This is the "clever" trick Rai uses to ensure
247       // the content is accessed by www.rai.tv only...
248       headers: {'viaurl': 'www.rai.tv'},
249       url: URL,
250       onload: function(response) {
251         text = response.responseText;
252         text = text.replace(/&/g, '&amp;')
253         parser = new DOMParser();
254         xmlDoc = parser.parseFromString(text, "text/xml");
255
256         ref = xmlDoc.getElementsByTagName('REF');
257         if (ref.length > 0) {
258           href = ref[0].getAttribute('HREF');;
259
260           var evt = document.createEvent('Event');
261           evt.initEvent('UrlFetched', true, true);
262           evt.site = site;
263           evt.URL = href;
264           document.dispatchEvent(evt);
265         }
266       }
267     });
268   }, 0);
269 }