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