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