Fix doc about pageURL field which no longer exists
[GM_direct_download_links.git] / direct_download_links.user.js
index eac46c9..8421b49 100644 (file)
@@ -1,6 +1,6 @@
 // direct_download_links - Add direct download links
-// version 0.2
-// 2011-11-14
+// version 0.3
+// 2011-12-23
 // Copyright (C) 2011  Antonio Ospite <ospite@studenti.unina.it>
 // Released under the GPL license
 // http://www.gnu.org/copyleft/gpl.html
 // @include        http://trovacinema.repubblica.it/*
 // @include        http://www.kataweb.it/tvzap/*
 // @include        http://www.rai.tv/*
+// @include        http://soundcloud.com/*
 // ==/UserScript==
 //
-// NOTE, for rai.tv to work you need to install a script like:
-// http://git.ao2.it/smooth-dl.git/blob_plain/HEAD:/scripts/SilverSpoof.user.js
 
 /*
  * TODO:
  *    the regexp starting from a glob line.
  *  - use xpath instead of regexp like in http://a32.me/2009/11/greasemonkey/
  *  - use jquery, like shown in http://a32.me/2009/11/greasemonkey/
+ *  - Support the "download" attribute for anchors:
+ *    http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#downloading-resources
  */
 
 /* Fields supported by the "site" object.
  *
  * Manadatory fields:
- *   pageURL: the URL of the page we are modifying
+ *   locationRegExp: the regexp describing the URL of the page we are modifying
  *   urlContainer: the element containing the URL to link
  *   urlRegexp: the regular expression for finding the URL, the first
  *              sub-pattern is taken as the URL
  *
  *
  * Optional fields:
+ *
+ *   initCommand: a function called before the regExp is matched, this can
+ *                be useful in cases when some action needs to be done in
+ *                order to make the element containing the regExp be actually
+ *                rendered. It must accept  a 'site' parameter.
+ *
  *   onEvent: used to delay the urlRegexp matching to a certain event like
  *            'DOMNodeInserted' useful when the URL is added by some javascript
  *            library. It has two fields:
  *              targetElement: the element in the event handler we want the
  *                urlRegexp is performed on.
  *
+ *  processURL: a function to process the URL before adding the Direct
+ *              Downdload Link to the page, it must accept  a 'site' and a
+ *              'URL' parameters and dispatch the UrlFetched to pass the
+ *              modified URL to _add_link().
+ *
  */
 var supported_sites = [
   {
@@ -90,11 +102,23 @@ var supported_sites = [
   },
   {
     locationRegexp: /^http:\/\/www\.rai\.tv\/.*$/,
+      initCommand: function(site) {
+        unsafeWindow.Silverlight.isInstalled = function(version) {
+          return true;
+        };
+    },
     urlContainer: 'Player',
     urlRegexp: /mediaUri=(http:\/\/[^,]*)/,
     onEvent: { evt: 'DOMNodeInserted', targetElement: 'object' },
+    processURL: _rai_get_actual_url,
     linkDest: 'Player',
   },
+  {
+    locationRegexp: /^http:\/\/soundcloud.com\/.*$/,
+    urlContainer: 'main-content-inner',
+    urlRegexp: /"streamUrl":"([^"]*)"/,
+    linkDest: 'main-content-inner',
+  },
 ];
 
 /* Apply different rules to different sites */
@@ -103,10 +127,10 @@ for (i = 0; i < supported_sites.length; i++) {
 
   var result = window.location.href.match(site.locationRegexp);
   if (result) {
-    var ret = direct_download_link_add(window.location.href, site);
-    if (!ret) {
-      DDL_log('Cannot add the link');
+    if (site.initCommand) {
+      site.initCommand(site);
     }
+    direct_download_link_add(window.location.href, site);
   }
 }
 
@@ -124,6 +148,8 @@ function direct_download_link_add(pageURL, site) {
     return null;
   }
 
+  document.addEventListener('UrlFetched', _add_link, true);
+
   // This is used for sites adding the URL to the DOM after DOMContentLoaded,
   // for example by some javascript library (like Silverlight.js on rai.tv).
   if (site.onEvent) {
@@ -133,58 +159,73 @@ function direct_download_link_add(pageURL, site) {
         DDL_log('DirectDL (' + site.pageURL  + '): skipping element ' + e.target.tagName);
         return;
       }
-    var URL = _get_URL(site, element);
-    return _add_link(site, URL);
+     _get_URL(site, element);
     }, false);
-    return true;
+    return;
   }
 
-  var URL = _get_URL(site, element);
-  if (!URL) {
-    DDL_log('DirectDL (' + site.pageURL + '): cannot get the URL.');
-    return null;
-  }
-
-  return _add_link(site, URL);
+  _get_URL(site, element);
 }
 
 function _get_URL(site, element) {
   var content = element.innerHTML;
   if (!content) {
     DDL_log('DirectDL (' + site.pageURL + '): content is null, cannot find URL.');
-    return null;
+    return;
   }
 
   var matches = content.match(site.urlRegexp);
   if (!matches || matches.length < 2 || !matches[1]) {
       DDL_log('DirectDL (' + site.pageURL + '): URL not found, check the urlRegexp');
-      return null;
+      return;
   }
   var URL = matches[1];
+  if (!URL) {
+    DDL_log('DirectDL (' + site.pageURL + '): cannot get the URL.');
+    return;
+  }
 
-  return URL;
+  if (site.processURL) {
+    site.processURL(site, URL);
+    return;
+  }
+
+  var evt = document.createEvent('Event');
+  evt.initEvent('UrlFetched', true, true);
+  evt.site = site;
+  evt.URL = URL;
+  document.dispatchEvent(evt);
 }
 
-function _add_link(site, URL) {
+function _add_link(e) {
+  var site = e.site;
+  var URL = e.URL;;
 
-  var links = document.getElementById(site.linkDest);
-  if (!links) {
+  var destination = document.getElementById(site.linkDest);
+  if (!destination) {
     DDL_log('DirectDl (' + site.pageURL + '): Cannot add the direct download link.');
-    return null;
+    return;
   }
 
-  var download_link = document.createElement('a');
-  download_link.textContent = 'Direct Link';
-  download_link.setAttribute('href', URL);
-  var style = 'background-color: white; color: blue;';
-  style += ' border: 2px solid red;'
-  style += ' float: right; font-size: large;';
-  style += ' padding: .5em; margin: 1em;'
-  download_link.setAttribute('style', style);
-
-  links.insertBefore(download_link, links.firstChild);
+  // Check if we added the link already, if so just update the href attribute.
+  // This is useful when _get_URL() is called on async events.
+  var download_link = document.getElementById('GM_direct_downaload_link');
+  if (download_link) {
+    download_link.setAttribute('href', URL);
+  } else {
+    download_link = document.createElement('a');
+    download_link.textContent = 'Direct Link';
+    download_link.setAttribute('id', 'GM_direct_downaload_link');
+    download_link.setAttribute('href', URL);
+    var style = 'background-color: white; color: blue;';
+    style += ' border: 2px solid red;'
+    style += ' float: right; font-size: large;';
+    style += ' padding: .5em; margin: 1em;'
+    style += ' position: relative; z-index: 1000;'
+    download_link.setAttribute('style', style);
 
-  return true;
+    destination.insertBefore(download_link, destination.firstChild);
+  }
 }
 
 function DDL_log(message) {
@@ -195,3 +236,44 @@ function DDL_log(message) {
     GM_log(message);
   }
 }
+
+function _rai_get_actual_url(site, URL) {
+
+  // SmoothStreaming manifest files get added without processing, for now:
+  if (URL.match(/.*\.csm$/)) {
+    var evt = document.createEvent('Event');
+    evt.initEvent('UrlFetched', true, true);
+    evt.site = site;
+    evt.URL = URL;
+    document.dispatchEvent(evt);
+    return;
+  }
+
+  // http://www.neaveru.com/wordpress/index.php/2008/05/09/greasemonkey-bug-domnodeinserted-event-doesnt-allow-gm_xmlhttprequest/
+  setTimeout( function() {
+    GM_xmlhttpRequest({
+      method: "GET",
+      // XXX A custom header. This is the "clever" trick Rai uses to ensure
+      // the content is accessed by www.rai.tv only...
+      headers: {'viaurl': 'www.rai.tv'},
+      url: URL,
+      onload: function(response) {
+        text = response.responseText;
+        text = text.replace(/&/g, '&amp;')
+        parser = new DOMParser();
+        xmlDoc = parser.parseFromString(text, "text/xml");
+
+        ref = xmlDoc.getElementsByTagName('REF');
+        if (ref.length > 0) {
+          href = ref[0].getAttribute('HREF');;
+
+          var evt = document.createEvent('Event');
+          evt.initEvent('UrlFetched', true, true);
+          evt.site = site;
+          evt.URL = href;
+          document.dispatchEvent(evt);
+        }
+      }
+    });
+  }, 0);
+}