// // subscldr.js // // LICENSE: {{{ // Copyright (c) 2009 snaka // // Distributable under the terms of an MIT-style license. // http://www.opensource.jp/licenses/mit-license.html // }}} // // PLUGIN INFO: {{{ var PLUGIN_INFO = {NAME} Adds subscriptions to livedoor Reader/Fastladder in place. ページ遷移なしでlivedoor ReaderやFastladderにフィードを登録します。 2.0pre 2.3 _libly.js http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/subscldr.js snaka MIT style license 0.2.2 || :subscldr :subscfl ||< ]]> || :subscldr :subscfl ||< ]]> ; // }}} liberator.plugins.subscldr = (function() { // PUBLIC {{{ var PUBLICS = { // TODO:Provide API function. // for DEBUG {{{ //getSubscription: getSubscription, //postSubscription: postSubscription, //selectFeed: selectFeed // }}} }; // }}} // COMMAND {{{ addCommand( ["subscldr", "subscrldr"], "livedoor Reader", "http://reader.livedoor.com/subscribe/" ); addCommand( ["subscfl", "subscrfl"], "Fastladder", "http://fastladder.com/subscribe/" ); // }}} // PRIVATE {{{ function addCommand (command, servicename, endpoint) { function handleFeedRequest(opts, redirectUrl, force) { var subscribeInfo = getSubscription(redirectUrl); var availableLinks = subscribeInfo.feedlinks.filter(function(info) info[1]); var alreadySubscribed = availableLinks.length != subscribeInfo.feedlinks.length; if (alreadySubscribed && !force) { liberator.echo("This site has already been subscribed. Are you sure to want to add subscription?"); commandline.input("Add? [y/N]:", function(ans) { if (ans.toLowerCase().indexOf("y") == 0) // /^y(?:es)?$/.test(ans.toLowerCase()) handleFeedRequest(opts, null, true); else liberator.echo("Canceled."); commandline.close(); } ); return; } switch (availableLinks.length) { case 0: if (alreadySubscribed) liberator.echo("The feed of this site has already been subscribed."); else // Maybe never reach here. liberator.echoerr("SITE FEED NOT AVAILABLE!!!"); break; case 1: liberator.log("FEED ONLY ONE!!"); subscribeInfo.feedlinks = [availableLinks[0][0], true]; postSubscription(subscribeInfo, opts); break; default: liberator.log("SOME FEED AVAILABLE"); selectFeed( availableLinks.map(function(i) [i[0], i[2]]), function(sel) { liberator.log("SELECTED FEED:" + sel); liberator.echo("Redirected ..."); var redirectUrl = endpoint + "?url=" + encodeURIComponent(sel); handleFeedRequest(opts, redirectUrl); } ); } } function getSubscription(target) { liberator.echo("Please wait ..."); var subscribeInfo; var uri = target || endpoint + buffer.URL; var req = new libly.Request(uri, null, {asynchronous: false}); req.addEventListener("onSuccess", function(res) { liberator.log(res.responseText); res.getHTMLDocument(); subscribeInfo = getSubscribeInfo(res.doc); liberator.log(subscribeInfo.toSource()); }); req.get(); return subscribeInfo; } function postSubscription(info, opts) { liberator.log("subscribe:" + info.toSource()); var postBody= "url=" + encodeURIComponent(info.target_url) + "&folder_id=0" + "&rate=" + (opts.rate || "0") + "®ister=1" + "&feedlink=" + encodeURIComponent(info.feedlinks[0]) + "&public=1" + "&ApiKey=" + info.apiKey; liberator.log("POST DATA:" + postBody); var req = new libly.Request( endpoint, null, { asyncronus: false, postBody: postBody } ); req.addEventListener("onSuccess", function(data) { liberator.log("Post status: " + data.responseText); liberator.echo("Subscribe feed succeed."); }); req.addEventListener("onFailure", function(data) { liberator.log("POST FAILURE: " + data.responseText); liberator.echoerr("POST FAILURE: " + data.statusText); }); req.post(); } commands.addUserCommand( command, "Register feed subscriptions to " + servicename + ".", function(args) { try { handleFeedRequest({rate: args["-rate"]}); } catch (e) { liberator.echoerr(e); } }, { options: [ [["-rate", "-r"], commands.OPTION_INT] ] }, true // Use in DEVELOP ); } function getSubscribeInfo(htmldoc) { var subscribeInfo = { target_url: null, register: 1, apiKey: null, feedlinks: [] }; $LXs('id("feed_candidates")/xhtml:li', htmldoc).forEach( function(item) { var feedlink = $LX('./xhtml:a[@class="feedlink"]', item); var title = $LX('./xhtml:a[@class="subscribe_list"]', item); var users = $LX('./xhtml:span[@class="subscriber_count"]/xhtml:a', item); var yet = $LX('./xhtml:input[@name="feedlink"]', item); liberator.log("input:" + feedlink.href); subscribeInfo.feedlinks.push([feedlink.href, (yet != null), (title ? title.textContent : '' ) + ' / ' + (users ? users.textContent : '0 user')]); }); var target_url = $LX('id("target_url")', htmldoc); if (!target_url) throw "Cannot find subscribe info about this page!"; subscribeInfo.target_url = target_url.value; liberator.log("target_url:" + subscribeInfo.target_url); subscribeInfo.apiKey = $LX('//*[@name="ApiKey"]', htmldoc).value; if (!subscribeInfo.apiKey) throw "Can't get API key for subscription!"; return subscribeInfo; } function selectFeed(links, next) { liberator.log(links.toSource()); liberator.echo("Following feeds were found on this site. Which are you subscribe?"); commandline.input("Select or input feed URL ", function(selected) { liberator.echo("You select " + selected + "."); commandline.close(); if (next && typeof next == "function") next(selected); else liberator.echoerr("Your selected no is invalid."); },{ completer: function(context) { context.title = ["Available feeds", "Title / users"]; context.completions = links; } }); // Open candidates list forcibly events.feedkeys(""); } // For convenience //function $LXs(a,b) libly.$U.getNodesFromXPath(a,b); //function $LX(a,b) libly.$U.getFirstNodeFromXPath(a,b); function nsResolver(prefix) { var ns = { 'xhtml': 'http://www.w3.org/1999/xhtml' }; return ns[prefix] || null; } function $LXs(a, b) { var ret = []; var res = (b.ownerDocument || b).evaluate(a, b, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < res.snapshotLength; i++) { ret.push(res.snapshotItem(i)); } return ret; } function $LX(a, b) { var res = (b.ownerDocument || b).evaluate(a, b, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return res.singleNodeValue || null; } // }}} return PUBLICS; })(); // vim:sw=2 ts=2 et si fdm=marker: ref='#n152'>152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
var PLUGIN_INFO =
<VimperatorPlugin>
<name>{NAME}</name>
<description>Open URL from a template</description>
<description lang="ja">テンプレートからURLをOpenします</description>
<minVersion>2.0pre</minVersion>
<maxVersion>2.0pre</maxVersion>
<updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/exopen.js</updateURL>
<author homepage="http://vimperator.g.hatena.ne.jp/pekepekesamurai/">pekepekesamurai</author>
<version>0.10</version>
<detail lang="ja"><![CDATA[
== Command ==
:exopen [template_name]
  [template_name] で設定されたURLを開きます

=== Example ===
:exopen http://www.google.co.jp/search?q=%TITLE%:
  %TITLE%を現在開いているWebページのタイトルに展開してURLを開きます
:exopen [title]
  テンプレートで設定されたURLを開きます

== Keyword ==
%TITLE%:
  現在のWebページのタイトル
%URL%:
  現在のWebページのURL
%SEL%:
  選択中の文字列
%HTMLSEL%:
  選択中のHTMLソース

== .vimperatorrc ==
>||
javascript <<EOM
liberator.globalVariables.exopen_templates = [
  {
    label: 'vimpnightly',
    value: 'http://download.vimperator.org/vimperator/nightly/',
    description: 'open vimperator nightly xpi page',
    newtab: true
  }, {
    label: 'vimplab',
    value: 'http://vimperator.org/trac/',
    description: 'open vimperator trac page',
    newtab: true
  }, {
    label: 'vimpscript',
    value: 'http://vimperator.org/trac/wiki/Vimperator/Scripts/',
    description: 'open vimperator trac script page',
    newtab: true
  }, {
    label: 'coderepos',
    value: 'http://coderepos.org/share/browser/lang/javascript/vimperator-plugins/trunk/',
    description: 'open coderepos vimperator-plugin page',
    newtab: true
  }, {
    label: 'sldr',
    value: 'http://reader.livedoor.com/subscribe/%URL%'
  }
];
EOM
||<
label:
  テンプレート名コマンドの引数で指定してください
value:
  OpenするURL
custom:
  関数か配列で指定してください
  関数の場合return された文字列をオープンします
  配列の場合value で指定された文字列を置換します(条件Array[0]置換文字列Array[1])
description:
  補完時に表示する説明文
newtab:
  新規タブで開く場合は true を指定してください
escape:
  URLエンコードする場合true を指定してください
]]></detail>
</VimperatorPlugin>;

liberator.plugins.exOpen = (function() {
  var global = liberator.globalVariables.exopen_templates;
  if (!global) {
    global = [{
      label: 'vimpnightly',
      value: 'http://download.vimperator.org/vimperator/nightly/',
      description: 'open vimperator nightly xpi page',
      newtab: true
    }, {
      label: 'vimplab',
      value: 'http://vimperator.org/trac/',
      description: 'open vimperator trac page',
      newtab: true
    }, {
      label: 'vimpscript',
      value: 'http://vimperator.org/trac/wiki/Vimperator/Scripts/',
      description: 'open vimperator trac script page',
      newtab: true
    }, {
      label: 'coderepos',
      value: 'http://coderepos.org/share/browser/lang/javascript/vimperator-plugins/trunk/',
      description: 'open coderepos vimperator-plugin page',
      newtab: true
    }, {
      label: 'sldr',
      value: 'http://reader.livedoor.com/subscribe/%URL%'
    }];
  }

  function openTabOrSwitch(url) {
    var tabs = gBrowser.mTabs;
    for (let i=0, l=tabs.length; i<l; i++)
      if (tabs[i].linkedBrowser.contentDocument.location.href == url) return (gBrowser.tabContainer.selectedIndex = i);
    return liberator.open(url, liberator.NEW_TAB);
  }

  function replacer(str, isEscape) {
    if (!str) return '';
    var win = new XPCNativeWrapper(window.content.window);
    var sel = '', htmlsel = '';
    var selection = win.getSelection();
    function __replacer(val) {
      switch (val) {
        case '%TITLE%':
          return buffer.title;
        case '%URL%':
          return buffer.URL;
        case '%SEL%':
          if (sel) return sel;
          else if (selection.rangeCount < 1) return '';
          for (let i=0, c=selection.rangeCount; i<c;
            sel += selection.getRangeAt(i++).toString());
          return sel;
        case '%HTMLSEL%':
          if (htmlsel) return sel;
          if (selection.rangeCount < 1) return '';

          let serializer = new XMLSerializer();
          for (let i=0, c=selection.rangeCount; i<c;
            htmlsel += serializer.serializeToString(selection.getRangeAt(i++).cloneContents()));
          return htmlsel;
      }
      return '';
    }
    var _replacer = __replacer;
    if (isEscape) _replacer = function(val) escape( __replacer(val) );

    return str.replace(/%(TITLE|URL|SEL|HTMLSEL)%/g, _replacer);
  }

  var ExOpen = function() this.initialize.apply(this, arguments);
  ExOpen.prototype = {
    initialize: function() {
      this.createCompleter();
      this.registerCommand();
    },
    createCompleter: function() {
        this.completer = global.map(
          function(t) [t.label, util.escapeString((t.description ? t.description + ' - ' : '') + t.value)]
        );
    },
    registerCommand: function() {
      var self = this;
      commands.addUserCommand(['exopen'], 'Open byextension URL',
        function(args) self.open(args.string, args.bang), {
          completer: function(context, args) {
            context.title = ['Template', 'Description - Value'];
            if (!context.filter) {
              context.completions = self.completer;
              return;
            }
            var filter = context.filter.toLowerCase();
            context.completions = self.completer.filter( function( t ) t[0].toLowerCase().indexOf(filter) == 0 );
          }
      });
    },
    find: function(label) {
      var ret = null;
      global.some(function(template) (template.label == label) && (ret = template));
      return ret;
    },
    open: function(arg) {
      var url = '';
      if (!arg) return;
      var template = this.find(arg) || {value: arg};
      if (typeof template.custom == 'function') {
        url = template.custom.call(this, template.value);
      } else if (template.custom instanceof Array) {
        url = replacer(template.value).replace(template.custom[0], template.custom[1], template.escape);
      } else {
        url = replacer(template.value, template.escape);
      }
      if (!url) return;
      if (template.newtab) openTabOrSwitch(url);
      else liberator.open(url);
    }
  };
  return new ExOpen();
})();