let INFO = teramako BSD

Example: list executing Jetpack feature

:echo jetpack.contexts.map(function(ctx) ctx.feed.title);

Example: access to the sandbox of the feature

:echo jetpack.contexts[0].unsafeSandbox

Example: select and open slidebar

:js jetpack.slideBar.select("featureTitle")

Example: toggle slidebar

:js jetpack.slideBar.toggle()

Example: install a feature form local file

:js jetpack.install("~/var/jetpackScripts/test.js")

Example: refresh the feature

:js jetpack.refresh("test")

Example: uninstall the feature

:js jetpack.uninstall("test")

Example: reinstall the feature

:js jetpack.reinstall("test")

Example: purge the feature

:js jetpack.purge("test")
; let EXT = {}; liberator.modules.jetpack = (function(){ let id = "jetpack@labs.mozilla.com"; if (!Application.extensions.has(id) || !Application.extensions.get(id).enabled){ liberator.echoerr("Jetpack is not enable or installed"); return {}; } Cu.import("resource://jetpack/modules/init.js", EXT); let self = { get jWin() EXT.get("chrome://jetpack/content/index.html"), get JetpackRuntime() this.jWin.JetpackRuntime, get contexts() this.jWin.JetpackRuntime.contexts, get feedManager() this.jWin.JetpackRuntime.FeedPlugin.FeedManager, get slideBar(){ let slideBar = window.slideBar; slideBar.__proto__ = slideBarProto; return slideBar; }, getContextByTitle: function jetpack_getContextByTitle(title){ let contexts = this.contexts.filter(function(ctx){ return ctx.feed.title == title; }); liberator.assert(contexts.length > 0, "no jetpack features"); return contexts[0]; }, getFeedByTitle: function jetpack_getFeedByTitle(title){ return getFeedByTitle(title, FEED_FLAG.ALL); }, install: function jetpack_install(path){ let file = io.File(path); let uri = util.createURI(file.path); let name = file.leafName.replace(/\..*/, "").replace(/-([a-z])/g, function (m, n1) n1.toUpperCase()); this.feedManager.addSubscribedFeed({ canAutoUpdate: false, sourceCode: file.read("UTF-8"), sourceUrl: uri.spec, title: name, type: "jetpack", url: uri.spec }); }, refresh: function jetpack_refresh(title){ let feed = getFeedByTitle(title, FEED_FLAG.SUBSCRIBED | FEED_FLAG.NOT_BUILTIN); this.JetpackRuntime.forceFeedUpdate(feed); }, uninstall: function jetpack_uninstall(title){ let feed = getFeedByTitle(title, FEED_FLAG.SUBSCRIBED | FEED_FLAG.NOT_BUILTIN); feed.remove(); }, reinstall: function jetpack_reinstall(title){ let feed = getFeedByTitle(title, FEED_FLAG.UNSUBSCRIBED); feed.unremove(); }, purge: function jetpack_purge(title){ let feed = getFeedByTitle(title, FEED_FLAG.ALL | FEED_FLAG.NOT_BUILTIN); if (feed.isSubscribed) feed.remove(); feed.purge(); }, }; let slideBarProto = { select: function jetpack_slideBar_select(title){ let features = this.features.filter(function(f){ return f.context.feed.title == title; }); liberator.assert(features.length > 0, "no such jetpack feature"); this.selectFeature(features[0]); } }; const FEED_FLAG= { NOT_BUILTIN: 1 << 0, SUBSCRIBED: 1 << 1, UNSUBSCRIBED: 1 << 2, ALL: 6 }; function getFeedByTitle(title, flag){ let feeds = []; if (flag >= FEED_FLAG.ALL) feeds = getAllFeeds(); else if (flag & FEED_FLAG.UNSUBSCRIBED) feeds = getUnsubscribedFeeds(); else if (flag & FEED_FLAG.SUBSCRIBED) feeds = getSubscribedFeeds(true); if (flag & FEED_FLAG.NOT_BUILTIN) feeds = feeds.filter(function(f) !f.isBuiltIn); feeds = feeds.filter(function(f) f.title == title); liberator.assert(feeds.length > 0, "not such jetpack feature"); return feeds[0]; } function getAllFeeds(includeBuiltin){ return [].concat(getSubscribedFeeds(includeBuiltin), getUnsubscribedFeeds()); } function getSubscribedFeeds(includeBuiltin){ let feeds = self.feedManager.getSubscribedFeeds(); if (includeBuiltin) return feeds; else return feeds.filter(function(f) !f.isBuiltIn); } function getUnsubscribedFeeds(){ return self.feedManager.getUnsubscribedFeeds(); } JavaScript.setCompleter([self.getContextByTitle], [function(){ return getSubscribedFeeds(true).map(function(f) [f.title, f.uri.spec]); }]); JavaScript.setCompleter([self.refresh, self.uninstall], [function(){ return getSubscribedFeeds(false).map(function(f) [f.title, f.uri.spec]); }]); JavaScript.setCompleter([self.purge], [function(){ return getAllFeeds(false).map(function(f) [f.title, f.uri.spec]); }]); JavaScript.setCompleter([self.getFeedByTitle], [function(){ return getAllFeeds(true).map(function(f) [f.title, f.uri.spec]); }]); JavaScript.setCompleter([self.reinstall], [function(){ return getUnsubscribedFeeds().map(function(f) [f.title, f.uri.spec]); }]); JavaScript.setCompleter([self.install], [function (context, obj, args) { context.quote[2] = ""; completion.file(context, true); }]); JavaScript.setCompleter([slideBarProto.select], [function(){ return self.slideBar.features.map(function(f) [f.context.feed.title, f.context.feed.uri.spec]); }]); return self; })(); // vim: sw=2 ts=2 et: 68' href='#n68'>68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
let PLUGIN_INFO =
<VimperatorPlugin>
<name>{NAME}</name>
<description>Show/Open related blog</description>
<description lang="ja">現在ページへリンクしているブログを表示または開くプラグイン</description>
<author email="teramako@gmail.com" homepage="http://vimperator.g.hatena.ne.jp/teramako/">teramako</author>
<version>1.0</version>
<license>MPL 1.1/GPL 2.0/LGPL 2.1</license>
<minVersion>2.0pre</minVersion>
<maxVersion>2.0</maxVersion>
<updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/relatedBlogSearch.js</updateURL>
<detail lang="ja"><![CDATA[
現在開いているページへリンクしているブログを探しだし表示または開くことを目的とするプラグイン

== Command ==

:relatedblog:
  現在ページにリンクしているブログをリストします
:relatedblog -q[uery] {searchTerm}:
  {searchTerm} で検索してブログをりすとします
:relatedblog {URL}:
  {URL} を開きます
  補完から取ってくると良いと思います

>||
tab relatedblog {URL}
||<
とすることで新規タブに開けます
またリストを表示した後";o" などのヒントからも開けるでしょう(historyコマンドに似ている)

== 変数 ==
let コマンドで設定してください(しない場合はデフォルト値が使用されます)

:g:blogSearchHeaderTemplate:
  リストを表示する時のヘッダとなるXML文字列
  省略時は以下が使用されます
  >||
  '<table><tr><th>Title</th><th>Author</th><th>Content</th></tr></table>';
  ||<
:g:blogSearchBodyTemplate:
  リストを表示する時のコンテンツとなるXML文字列
  省略時は以下が使用されます
  >||
  '<tr><td><a highlight="URL" href="%link%">%title%</a></td><td>%author%</td><td>%content%</td></tr>';
  ||<

また%で囲まれた特定の文字列が変数として使用されます
%link%:
  対象ページのURL
%title%:
  対象ページのタイトル
%author%:
  対象ページの著者
%content%:
  対象ページの内容(一部)
%rootURI%:
  対象ページのトップページのURL
%id%:
  不明ドメイン日付パスが含まれる
%published%:
  投稿された日時(%Y-%m-%dT%H:%M:%SZ)
%updated%:
  更新された日時(%Y-%m-%dT%H:%M:%SZ)
]]></detail>
</VimperatorPlugin>;

liberator.plugins.relatedBlogSearch = (function(){
const LANG = window.navigator.language;
const BLOGSEARCH_URL = 'http://blogsearch.google.com/blogsearch_feeds?output=atom&hl=' + LANG + '&q=';

/**
 * Serach with Google blogsearch and get entries
 * @param {String} name query string
 */
function BlogSearch() { this._init.apply(this, arguments); }
BlogSearch.prototype = {
  _init: function(name){
    if (!name)
      throw Components.results.NS_ERROR_XPC_NOT_ENOUGH_ARGS;

    this.date = new Date();
    this.name = name;
    this.query = BLOGSEARCH_URL + this.name;
    let self = this;
    this.items = Array.map(
      util.httpGet(this.query).responseXML.getElementsByTagName("entry"),
      function(entry) self._parse(entry)
    );
  },
  /**
   * @param {Element} entryElm Atom entry element
   * @return {Object}
   */
  _parse: function(entryElm){
    let entry = {};
    Array.forEach(entryElm.childNodes, function(elm){
      let tagName = elm.localName;
      switch(tagName){
        case 'link':
          entry.link = elm.getAttribute('href'); break;
        case 'author':
          entry.author = elm.childNodes[0].textContent;
          entry.rootURI = elm.childNodes[1].textContent;
          break;
        default:
          entry[tagName] = elm.textContent;
      }
    });
    return entry;
  },
  /**
   * @param {RegExp} reg
   * @param {String[]} itemNames item's property names
   * @return {Object[]} item list
   */
  search: function(reg, itemNames){
    if (!itemNames) itemNames = [name for (name in this.items[0])];
    return this.items.filter(function(item) itemNames.some(function(name) reg.test(item[name])));
  },
  /**
   * @param {String} template
   * @param {XMLList} xml header XML
   * @param {Object[]} items if omitted, used all items
   * template e.g.)
   *  '<tr><td><a href="link">%title%</a></td><td>%author%</td><td>%content%</td></tr>'
   */
  toXMLByTemplate: function(template, xml, items){
    if (!items) items = this.items;

    function entryToXML(item){
      function replacer(all, name) name in item ? item[name] : all;
      return new XMLList(template.replace(/%(\w+?)%/g, replacer).replace(/&/g,"&amp;"));
    }
    items.forEach(function(item){xml.* += entryToXML(item);});
    return xml;
  },
};

/**
 * -query option completion list
 * e.g.)
 * return [
 *  ["link:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects", "-"],
 *  ["link:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference", "-"],
 *  ["link:https://developer.mozilla.org/en", "-"],
 *  ["link:https://developer.mozilla.org", "-"],
 * ]
 * when current url is "https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects"
 * @return {String[][]}
 */
function getQueryList(){
  return buffer.URL.split(/\/(?!\/)/).reduce(function(p,c){
    p.length == 0 ? p.push(c) : p.push(p[p.length-1]+"/"+c);
    return p;
  },[]).splice(1).map(function(url) ["link:" + url, "-"]).reverse();
}

// ----------------------------------------------
// command
// ----------------------------------------------
commands.addUserCommand(["relatedblog"], "search linked blog from google blogsearch",
function(args){
  let query = args["-query"] ? args["-query"] : "link:" + buffer.URL;
  let entry = manager.getCache(query);
  let header = new XMLList(manager.headerTemplate);
  if (args.length == 0){
    let xml  = entry.toXMLByTemplate(manager.bodyTemplate, header);
    liberator.echo(xml, true);
  } else {
    let reg = new RegExp(args[0], "i");
    let items = entry.search(reg);
    if (items.length > 1){
      liberator.echo(entry.toXMLByTemplate(manager.bodyTemplate, header, items),true);
    } else if (items.length == 1){
      let url = items[0].link;
      liberator.open(url);
    } else {
      liberator.echomsg("related blog is none",5);
    }
  }
},{
  options: [
    [["-query", "-q"], commands.OPTION_STRING, null, getQueryList]
  ],
  argCount: "?",
  completer: function(context, args){
    manager.completer(context, args);
  },
},true);

// ----------------------------------------------
// public
// ----------------------------------------------
var manager = {
  get bodyTemplate(){
    return liberator.globalVariables.blogSearchBodyTemplate ?
      liberator.globalVariables.blogSearchBodyTemplate :
      '<tr><td><a highlight="URL" href="%link%">%title%</a></td><td>%author%</td><td>%content%</td></tr>';
  },
  get headerTemplate(){
    return liberator.globalVariables.blogSearchHeaderTemplate ?
      liberator.globalVariables.blogSearchHeaderTemplate :
      '<table><tr><th>Title</th><th>Author</th><th>Content</th></tr></table>';
  },
  /**
   * @type {BlogSerach[]}
   */
  cache: [],
  /**
   * キャッシュからエントリを取得
   * キャッシュがないまたは期限切れの場合は新たに取得
   * キャッシュのリストは10個まで XXX: 外だししたほうが良いかもしれない
   * XXX: 有効期限を変数に持たせた方が良いかもしれない
   * @param {String} name query string
   * @return {BlogSearch}
   */
  getCache: function(name){
    let cache = this.cache.filter(function(entry) entry.name == name);
    if (cache.length == 0){
      let entry = new BlogSearch(name);
      if(this.cache.push(entry) > 10)
        this.cache.shift();

      return entry;
    } else if (cache[0].date < Date.now() - 5*60*1000){
      cache[0]._init(name);
    }
    return cache[0];
  },
  /**
   * relatedblog コマンド用の補完関数
   * @param {CompletionContext} context
   * @param {String[]} args
   */
  completer: function(context, args){
    let query = args["-query"] ? args["-query"] : "link:" + buffer.URL;
    let entry = this.getCache(query)
    context.title = ["URL", "Title"];
    if (args.length == 0){
      context.completions = entry.items.map(function(item) [item.link, item.title]);
    } else {
      let reg = new RegExp(context.filter, "i");
      context.completions = entry.search(reg).map(function(item) [item.link, item.title]);
    }
  },
};
return manager;
})();
// vim: sw=2 ts=2 et: