Check if the Direct Download Link has been added already
[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   }
144
145   _get_URL(site, element);
146 }
147
148 function _get_URL(site, element) {
149   var content = element.innerHTML;
150   if (!content) {
151     DDL_log('DirectDL (' + site.pageURL + '): content is null, cannot find URL.');
152     return;
153   }
154
155   var matches = content.match(site.urlRegexp);
156   if (!matches || matches.length < 2 || !matches[1]) {
157       DDL_log('DirectDL (' + site.pageURL + '): URL not found, check the urlRegexp');
158       return;
159   }
160   var URL = matches[1];
161   if (!URL) {
162     DDL_log('DirectDL (' + site.pageURL + '): cannot get the URL.');
163     return;
164   }
165
166   if (site.processURL) {
167     site.processURL(site, URL);
168     return;
169   }
170
171   var evt = document.createEvent('Event');  
172   evt.initEvent('UrlFetched', true, true);  
173   evt.site = site;
174   evt.URL = URL;
175   document.dispatchEvent(evt);
176 }
177
178 function _add_link(e) {
179   var site = e.site;
180   var URL = e.URL;;
181
182   var destination = document.getElementById(site.linkDest);
183   if (!destination) {
184     DDL_log('DirectDl (' + site.pageURL + '): Cannot add the direct download link.');
185     return;
186   }
187
188   // Check if we added the link already, if so just update the href attribute.
189   // This is useful when _get_URL() is called on async events.
190   var download_link = document.getElementById('GM_direct_downaload_link');
191   if (download_link) {
192     download_link.setAttribute('href', URL);
193   } else {
194     download_link = document.createElement('a');
195     download_link.textContent = 'Direct Link';
196     download_link.setAttribute('id', 'GM_direct_downaload_link');
197     download_link.setAttribute('href', URL);
198     var style = 'background-color: white; color: blue;';
199     style += ' border: 2px solid red;'
200     style += ' float: right; font-size: large;';
201     style += ' padding: .5em; margin: 1em;'
202     download_link.setAttribute('style', style);
203
204     destination.insertBefore(download_link, destination.firstChild);
205   }
206 }
207
208 function DDL_log(message) {
209   var debug = false;
210   if (debug) {
211     alert(message)
212   } else {
213     GM_log(message);
214   }
215 }
216
217 function _rai_get_actual_url(site, URL) {
218   // http://www.neaveru.com/wordpress/index.php/2008/05/09/greasemonkey-bug-domnodeinserted-event-doesnt-allow-gm_xmlhttprequest/
219   setTimeout( function() {
220     GM_xmlhttpRequest({
221       method: "GET",
222       // XXX A custom header. This is the "clever" trick Rai uses to ensure
223       // the content is accessed by www.rai.tv only...
224       headers: {'viaurl': 'www.rai.tv'},
225       url: URL,
226       onload: function(response) {
227         text = response.responseText;
228         text = text.replace(/&/g, '&amp;')
229         parser = new DOMParser();
230         xmlDoc = parser.parseFromString(text, "text/xml");
231
232         ref = xmlDoc.getElementsByTagName('REF');
233         if (ref.length > 0) {
234           href = ref[0].getAttribute('HREF');;
235
236           var evt = document.createEvent('Event');  
237           evt.initEvent('UrlFetched', true, true);  
238           evt.site = site;
239           evt.URL = href;
240           document.dispatchEvent(evt);
241         }
242       }
243     });
244   }, 0);
245 }