aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorsuVene2008-12-06 20:43:44 +0000
committersuVene2008-12-06 20:43:44 +0000
commit0b17746bf15614537c8a70e4fc4b636a82e8bb2f (patch)
treef15c1742fc7d032bf051d7167d0781952425b999
parent70c18a8e46ceae197184d28c41682ba908e23da0 (diff)
downloadvimperator-plugins-0b17746bf15614537c8a70e4fc4b636a82e8bb2f.tar.bz2
library is moved to a libly.js
git-svn-id: http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk@26020 d0d07461-0603-4401-acd4-de1884942a52
-rw-r--r--libly.js4
-rw-r--r--multi_requester.js279
2 files changed, 24 insertions, 259 deletions
diff --git a/libly.js b/libly.js
index 13dc034..5878e9a 100644
--- a/libly.js
+++ b/libly.js
@@ -1,6 +1,6 @@
/**
* ==VimperatorPlugin==
- * @name _libly.js
+ * @name libly.js
* @description suvene's library
* @description-ja 適当なライブラリっぽいものたち
* @author suVene suvene@zeromemory.info
@@ -27,7 +27,7 @@ lib.$U = {//{{{
};
this.echo = function(msg, flg) {
flg = flg || commandline.FORCE_MULTILINE;
- this.log(msg);
+ // this.log(msg);
liberator.echo(msg, flg);
};
this.echoerr = function(msg) {
diff --git a/multi_requester.js b/multi_requester.js
index cf739a9..4a9b00d 100644
--- a/multi_requester.js
+++ b/multi_requester.js
@@ -4,10 +4,10 @@
* @description request, and the result is displayed to the buffer.
* @description-ja リクエストの結果をバッファに出力する。
* @author suVene suvene@zeromemory.info
- * @version 0.4.1
+ * @version 0.4.2
* @minVersion 2.0pre
* @maxVersion 2.0pre
- * Last Change: 02-Dec-2008.
+ * Last Change: 07-Dec-2008.
* ==/VimperatorPlugin==
*
* HEAD COMMENT {{{
@@ -69,7 +69,12 @@
* }}}
*/
(function() {
-
+io.sourceFromRuntimePath(['libly.js']);
+if (!liberator.plugins.libly) {
+ liberator.log('multi_requester: needs libly.js');
+ return;
+}
+
// global variables {{{
var DEFAULT_COMMAND = ['mr'];
var SITEINFO = [
@@ -88,75 +93,12 @@ var SITEINFO = [
urlEncode: 'UTF-8'
},
];
+var lib = liberator.plugins.libly;
+var $U = lib.$U;
+var logger = $U.getLogger('multi_requester');
var mergedSiteinfo = {};
//}}}
-// utility class {{{
-var $U = {
- log: function(msg, level) {
- liberator.log(msg, (level || 0));
- },
- echo: function(msg, flg) {
- flg = flg || commandline.FORCE_MULTILINE
- liberator.echo(msg, flg);
- },
- echoerr: function(msg) {
- liberator.log(msg, 5);
- liberator.echoerr(msg);
- },
- extend: function(dst, src) {
- for (let prop in src)
- dst[prop] = src[prop];
- return dst;
- },
- A: function(hash) {
- var ret = [];
- for each (let item in hash) ret.push(item);
- return ret;
- },
- bind: function(obj, func) {
- return function() {
- return func.apply(obj, arguments);
- }
- },
- stripTags: function(str, tags) {
- var ignoreTags = [].concat(tags);
- ignoreTags = '(?:' + ignoreTags.join('|') + ')';
- return str.replace(new RegExp('<' + ignoreTags + '(?:[ \\t\\n\\r][^>]*|/)?>([\\S\\s]*?)<\/' + ignoreTags + '[ \\t\\r\\n]*>', 'ig'), '');
- },
- eval: function(text) {
- var fnc = window.eval;
- var sandbox;
- try {
- sandbox = new Components.utils.Sandbox(window);
- if (Components.utils.evalInSandbox('true', sandbox) === true) {
- fnc = function(text) { return Components.utils.evalInSandbox(text, sandbox); };
- }
- } catch (e) { $U.log('warning: multi_requester.js is working with unsafe sandbox.'); }
-
- return fnc(text);
- },
- // via. sbmcommentsviwer.js
- evalJson: function(str, toRemove) {
- var json;
- try {
- json = Components.classes['@mozilla.org/dom/json;1'].getService(Components.interfaces.nsIJSON);
- if (toRemove) str = str.substring(1, str.length - 1);
- return json.decode(str);
- } catch (e) { return null; }
- },
- getSelectedString: function() {
- return (new XPCNativeWrapper(window.content.window)).getSelection().toString();
- },
- pathToURL: function(path) {
- if (/^https?:\/\//.test(path)) return path;
- var link = document.createElement('a');
- link.href= path;
- return link.href;
- }
-};
-//}}}
-
// Vimperator plugin command register {{{
var CommandRegister = {
register: function(cmdClass, siteinfo) {
@@ -216,183 +158,6 @@ var CommandRegister = {
};
//}}}
-// Request and Response class. like the Prototype JavaScript framework {{{
-var Request = function() {
- this.initialize.apply(this, arguments);
-};
-Request.EVENTS = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
-Request.requestCount = 0;
-Request.prototype = {
- initialize: function(url, headers, options) {
- this.url = url;
- this.headers = headers || {};
- this.options = $U.extend({
- asynchronous: true,
- encoding: 'UTF-8'
- }, options || {});
- this.observers = {};
- },
- addEventListener: function(name, func) {
- try {
- if (typeof this.observers[name] == 'undefined') this.observers[name] = [];
- this.observers[name].push(func);
- } catch (e) {
- if (!this.fireEvent('onException', e)) throw e;
- }
- },
- fireEvent: function(name, args, asynchronous) {
- if (!(this.observers[name] instanceof Array)) return false;
- this.observers[name].forEach(function(event) {
- if (asynchronous) {
- setTimeout(event, 10, args);
- } else {
- event(args);
- }
- });
- return true;
- },
- _complete: false,
- _request: function(method) {
-
- Request.requestCount++;
-
- this.transport = new XMLHttpRequest();
- this.transport.open(method, this.url, this.options.asynchronous);
-
- this.transport.onreadystatechange = $U.bind(this, this._onStateChange);
- this.setRequestHeaders();
- this.transport.overrideMimeType('text/html; charset=' + this.options.encoding);
-
- this.body = this.method == 'POST' ? this.options.postBody : null;
-
- this.transport.send(this.body);
-
- // Force Firefox to handle ready state 4 for synchronous requests
- if (!this.options.asynchronous && this.transport.overrideMimeType)
- this._onStateChange();
- },
- _onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState > 1 && !(readyState == 4 && this._complete))
- this.respondToReadyState(this.transport.readyState);
- },
- getStatus: function() {
- try {
- return this.transport.status || 0;
- } catch (e) { return 0; }
- },
- isSuccess: function() {
- return !status || (status >= 200 && status < 300);
- },
- respondToReadyState: function(readyState) {
- var state = Request.EVENTS[readyState];
- var response = new Response(this);
-
- if (state == 'Complete') {
- Request.requestCount--;
- try {
- this._complete = true;
- this.fireEvent('on' + (this.isSuccess() ? 'Success' : 'Failure'), response, this.options.asynchronous);
- } catch (e) {
- if (!this.fireEvent('onException', e, this.options.asynchronous)) throw e;
- }
- }
- },
- setRequestHeaders: function() {
- var headers = {
- 'Accept': 'text/javascript, application/javascript, text/html, application/xhtml+xml, application/xml, text/xml, */*;q=0.1'
- };
-
- if (this.method == 'POST') {
- headers['Content-type'] = 'application/x-www-form-urlencoded' +
- (this.options.encoding ? '; charset=' + this.options.encoding : '');
-
- if (this.transport.overrideMimeType) {
- let year = parseInt((navigator.userAgent.match(/\bGecko\/(\d{4})/) || [0, 2005])[1], 10);
- if (0 < year && year < 2005)
- headers['Connection'] = 'close';
- }
- }
-
- for (let key in this.headers)
- if (this.headers.hasOwnProperty(key)) headers[key] = this.headers[key];
-
- for (let name in headers)
- this.transport.setRequestHeader(name, headers[name]);
-
- },
- get: function() {
- this._request('GET');
- },
- post: function() {
- this._request('POST');
- }
-};
-
-var Response = function() {
- this.initialize.apply(this, arguments);
-};
-Response.prototype = {
- initialize: function(req) {
- this.req = req;
- this.transport = req.transport;
- this.isSuccess = req.isSuccess();
- this.readyState = this.transport.readyState;
-
- if (this.readyState == 4) {
- this.status = this.getStatus();
- this.statusText = this.getStatusText();
- this.responseText = (this.transport.responseText == null) ? '' : this.transport.responseText;
- }
-
- this.doc = null;
- this.htmlFragmentstr = '';
- },
- status: 0,
- statusText: '',
- getStatus: Request.prototype.getStatus,
- getStatusText: function() {
- try {
- return this.transport.statusText || '';
- } catch (e) { return ''; }
- },
- getHTMLDocument: function(xpath, xmlns) {
- if (!this.doc) {
- this.htmlFragmentstr = this.responseText.replace(/^[\s\S]*?<html(?:[ \t\n\r][^>]*)?>|<\/html[ \t\r\n]*>[\S\s]*$/ig, '').replace(/[\r\n]+/g, ' ');
- let ignoreTags = ['script'];
- if (this.req.options.siteinfo.ignoreTags) {
- ignoreTags.concat(this.req.options.siteinfo.ignoreTags.split(','));
- }
- this.htmlStripScriptFragmentstr = $U.stripTags(this.htmlFragmentstr, 'script');
- this.doc = this._createHTMLDocument(this.htmlStripScriptFragmentstr, xmlns);
- }
-
- var ret = this.doc;
- if (xpath) {
- ret = this.getNodeFromXPath(xpath, this.doc);
- }
- return ret;
- },
- _createHTMLDocument: function(str) {
- var htmlFragment = document.implementation.createDocument(null, 'html', null);
- var range = document.createRange();
- range.setStartAfter(window.content.document.body);
- htmlFragment.documentElement.appendChild(htmlFragment.importNode(range.createContextualFragment(str), true));
- return htmlFragment;
- },
- getNodeFromXPath: function(xpath, doc, parentNode) {
- if (!xpath || !doc) return doc;
- var node = doc || document;
- var nodesSnapshot = (node.ownerDocument || node).evaluate(xpath, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
-
- if (nodesSnapshot.snapshotLength == 0) return parentNode;
- parentNode = parentNode || document.createElementNS(null, 'div');
- for (let i = 0, l = nodesSnapshot.snapshotLength; i < l; parentNode.appendChild(nodesSnapshot.snapshotItem(i++)));
- return parentNode;
- }
-};
-//}}}
-
// initial data access class {{{
var DataAccess = {
getCommand: function() {
@@ -434,7 +199,7 @@ var DataAccess = {
});
if (useWedata) {
- $U.log('use Wedata');
+ logger.log('use Wedata');
this.getWedata(function(site) {
if (mergedSiteinfo[site.name]) return;
mergedSiteinfo[site.name] = {};
@@ -445,7 +210,7 @@ var DataAccess = {
return $U.A(mergedSiteinfo);
},
getWedata: function(func) {
- var req = new Request(
+ var req = new lib.Request(
'http://wedata.net/databases/Multi%20Requester/items.json'
);
req.addEventListener('onSuccess', function(res) {
@@ -502,12 +267,12 @@ var MultiRequester = {
let ttbu = Components.classes['@mozilla.org/intl/texttosuburi;1']
.getService(Components.interfaces.nsITextToSubURI);
url = url.replace(/%s/g, ttbu.ConvertAndEscape(urlEncode, parsedArgs.str));
- $U.log(url + '[' + srcEncode + '][' + urlEncode + ']::' + info.xpath);
+ logger.log(url + '[' + srcEncode + '][' + urlEncode + ']::' + info.xpath);
if (bang) {
liberator.open(url, liberator.NEW_TAB);
} else {
- let req = new Request(url, null, {
+ let req = new lib.Request(url, null, {
encoding: srcEncode,
siteinfo: info,
args: {
@@ -525,7 +290,7 @@ var MultiRequester = {
}
if (MultiRequester.requestCount) {
- $U.echo('Loading ' + parsedArgs.names + ' ...', commandline.FORCE_SINGLELINE);
+ logger.echo('Loading ' + parsedArgs.names + ' ...', commandline.FORCE_SINGLELINE);
} else {
MultiRequester.doProcess = false;
}
@@ -574,7 +339,7 @@ var MultiRequester = {
if (!el) throw 'extract link failed.: extractLink -> ' + extractLink;
var a = el.firstChild;
var url = $U.pathToURL((a.href || a.action || a.value));
- var req = new Request(url, null, $U.extend(res.req.options, {extractLink: true}));
+ var req = new lib.Request(url, null, $U.extend(res.req.options, {extractLink: true}));
req.addEventListener('onException', $U.bind(this, this.onException));
req.addEventListener('onSuccess', $U.bind(this, this.onSuccess));
req.addEventListener('onFailure', $U.bind(this, this.onFailure));
@@ -590,7 +355,7 @@ var MultiRequester = {
return;
}
- $U.log('success!!!:' + res.req.url);
+ logger.log('success!!: ' + res.req.url);
MultiRequester.requestCount--;
if (MultiRequester.requestCount == 0) {
MultiRequester.doProcess = false;
@@ -624,7 +389,7 @@ var MultiRequester = {
MultiRequester.echoHash[res.req.options.siteinfo.name] = html;
} catch (e) {
- $U.log('error!!: ' + e);
+ logger.log('error!!: ' + e);
MultiRequester.echoHash[res.req.options.siteinfo.name] =
'<span style="color: red;">error!!: ' + e + '</span>';
}
@@ -637,17 +402,17 @@ var MultiRequester = {
html = '<div style="white-space:normal;"><base href="' + escapedUrl + '"/>' +
echoList.join('') +
'</div>';
- try { $U.echo(new XMLList(html)); } catch (e) { $U.log(e); $U.echo(html); }
+ try { logger.echo(new XMLList(html)); } catch (e) { logger.log(e); logger.echo(html); }
}
},
onFailure: function(res) {
MultiRequester.doProcess = false;
- $U.echoerr('request failure!!: ' + res.statusText);
+ logger.echoerr('request failure!!: ' + res.statusText);
},
onException: function(e) {
MultiRequester.doProcess = false;
- $U.echoerr('exception!!: ' + e);
+ logger.echoerr('exception!!: ' + e);
}//}}}
};
//}}}