Skip to content

Instantly share code, notes, and snippets.

@littlefolk
Created July 19, 2010 14:30
Show Gist options
  • Save littlefolk/481471 to your computer and use it in GitHub Desktop.
Save littlefolk/481471 to your computer and use it in GitHub Desktop.
// Util {{{1
let toggleDisplay = function (elem) elem && (elem.style.display = ((elem.style.display == "none")? "": "none"));
let Logger = libly.$U.getLogger("pixiv_tools.js");
let $ = function (a) window.content.document.getElementById(a);
let $LX = function (a, b) libly.$U.getFirstNodeFromXPath(a, b);
let $LXs = function (a, b) libly.$U.getNodesFromXPath(a, b);
let toQuery = function (so) [encodeURIComponent(i) + "=" + encodeURIComponent(so[i]) for (i in so)].join("&");
let checkInput = function (input) commandline.close() || (input && /^y(es)?/i.test(input));
// }}}1
let PixivTools = Class("PixivTools",
{ // base {{{1
init: function () { // {{{2
this.addCommands();
this.tomblooService = Cc["@brasil.to/tombloo-service;1"].getService().wrappedJSObject.Tombloo.Service;
},
// }}}
},
{ // prototype {{{1
_store: storage.newMap("pixiv_tools_dev", {store: true}),
_setting: { // {{{2
expire: 60 * 60 * 24 * 1000,
addPublic: {
// "0" : true
// "1" : false
user: "0",
illust: "1",
},
completion: {
// CompletionTags Show
// "both" : Bookmark && Illust
// "illust" : Illust - Bookmark
// "illust-full" : Illust
// "bookmark" : Bookmark - Illust
// "bookmark-full" : Bookmark
// "sep" : Separator Space
tag: ["both", "bookmark", "illust"],
// Descending Order of Bookmark Count
sort: true,
},
},
_message: { // {{{2
page: {
success: "\u8ffd\u52a0\u3057\u307e\u3057\u305f", // # 追加しました
bookmark: "\u3042\u306a\u305f\u306e\u30d6\u30c3\u30af\u30de\u30fc\u30af", // # あなたのブックマーク
toppage: "\u307f\u3093\u306a\u306e\u65b0\u7740\u30a4\u30e9\u30b9\u30c8", // # みんなの新着イラスト
},
echo: {
add: "\u304a\u6c17\u306b\u5165\u308a\u306b\u8ffd\u52a0\u3057\u307e\u3057\u305f", // # お気に入りに追加しました
error: "\u5931\u6557\u3057\u307e\u3057\u305f", // # 失敗しました
reqtag: "\u767b\u9332\u30bf\u30b0", // # 登録タグ
},
},
_cache: { // {{{2
bookmarkTags: null,
completeTags: {},
TT: "",
},
_check: { // {{{2
get currentLocation ()
window.content.document.location.href,
get inPixiv ()
this.currentLocation.match(/^http:\/\/[^\.\/]+\.pixiv\.net\//i),
get inFront ()
this.inPixiv && this.currentLocation.match(/member\.php\?id=\d+/),
get inList ()
this.inPixiv && this.currentLocation.match(/member_illust\.php\?id=\d+/),
get inManga ()
this.inPixiv && this.currentLocation.match(/member_illust\.php\?mode=manga/),
get inIllust ()
this.inPixiv && this.currentLocation.match(/member_illust\.php\?mode=medium&illust_id=\d+/),
get isFavIllust ()
this.inPixiv && !$LX("id('bookmark_btn')/ul[@class='bookmark_bt']/li/a[contains(@href, 'bookmark_add')]"),
get isFavUser ()
this.inPixiv && !$LX("id('leftcolumn')/div/ul[@class='profile_bt']/li/a[contains(@href, 'bookmark_add')]"),
input: function (str)
commandline.close() || (str && /^y(es)?/i.test(str)),
},
_dom: { // {{{2
get content ()
$("content2"),
get middleImage ()
$LX("id('content2')/div/a/img"),
get mangaViewer ()
$LX("id('content2')/div/a[contains(@href, 'mode=manga')]"),
get bigImage ()
$("BigImage"),
get imgTags ()
$LXs("id('tags')/a[not(img)]").map(function (e) e.text),
get vicinityImages ()
[null].concat($LXs("id('content2')/div/a[contains(@href, 'medium&illust_id=')]")).slice(-2),
},
// getter {{{2
get _dataBookmarkTags () {
if (!this._cache.bookmarkTags)
this._setBookmarkTags();
return this._cache.bookmarkTags;
},
set _dataBookmarkTags (obj)
this._cache.bookmarkTags = obj,
get _dataCompleteTags ()
this._cache.completeTags,
set _dataCompleteTags (obj)
this._cache.completeTags = obj,
get _id () {
return {
illust:
let (e = $("rpc_i_id") || $LX("//input[@name='illust_id']"))
e && (e.textContent || e.value),
user:
let (e = $("rpc_u_id") || $LX("//div[@id='profile']/div/a"))
e && (e.textContent || e.getAttribute("href").replace(/^.*id=/, "")),
};
},
get TT ()
let (e = $LX("//input[@name='tt']")) e && e.value || this._cache.TT,
set TT (str)
this._cache.TT = str,
// }}}
_addBigImage: function (_tomblooFlag) { // {{{2
let self = this;
let Body = window.content.document.documentElement;
let Content = this._dom.content;
let MiddleImage = this._dom.middleImage;
let BigImage = new Image();
MiddleImage.setAttribute("style", "border: 1px ridge #B7B7B7;");
BigImage.onload = function () {
BigImage.setAttribute("style", "position: absolute; border : 3px ridge #B7B7B7; z-index : 999; opacity: 1; background-color : #fff;");
BigImage.style.display = (_tomblooFlag)? "none": "";
[BigImage.style.left, BigImage.style.top] = self._calcInsertPosition(Body, Content, MiddleImage, BigImage);
};
BigImage.id = "BigImage";
BigImage.style.display = "none";
BigImage.src = MiddleImage.src.replace("_m.", ".");
Body.appendChild(BigImage);
return BigImage;
},
_calcInsertPosition: function (Body, Content, MiddleImage, BigImage) { // {{{2
// x: 中画像の中心(中画像の左端 + 中画像の半分) - 大画像の半分 = 大画像の中心と中画像の中心を同じに
// 大画像が画面右にはみ出したら、はみ出た分だけ左に寄せて、
// 大画像が画面左にはみ出したら、左端から始める。
// y: 中画像の上辺
let x = (MiddleImage.offsetLeft + Content.offsetLeft) + (MiddleImage.width / 2) - (BigImage.naturalWidth / 2);
x = let (drop = (x + BigImage.naturalWidth + 2) - Body.clientWidth) (drop > 0)? x - drop - 2: x;
x = (x <= 0)? 0: x - 2;
let y = MiddleImage.offsetTop + Content.offsetTop - 2;
return [x + "px", y + "px"];
},
_setBookmarkTags: function (_getFlag) { // {{{2
let self = this;
let store = this._store.get("data", null);
let now = new Date().getTime();
if (!store || _getFlag || ((now - this._store.get("time", 0)) >= this._setting.expire))
{
let req = new libly.Request("http://www.pixiv.net/bookmark.php", {Referrer: "http://www.pixiv.net/"});
req.addEventListener("onSuccess", function (res) {
let tagList = res.getHTMLDocument("id('bookmark_list')/ul/li[@class!='level0']/a");
if (tagList)
{
let obj = util.Array.toObject(tagList.map(function (e) [$LX("./text()", e).textContent, $LX("./span/text()", e).textContent]));
self._dataBookmarkTags = obj;
self._store.set("data", obj);
self._store.set("time", now);
self._store.save();
Logger.log("_setBookmarkTags.Success(" + tagList.length + ")");
}
else
{
self._dataBookmarkTags = store;
Logger.echoerr("_setBookmarkTags.Error(" + res.req.body + ")");
};
});
req.addEventListener("onFailure", function (res) Logger.echoerr("_setBookmarkTags.Failure" ));
req.addEventListener("onException", function (res) Logger.echoerr("_setBookmarkTags.Exception"));
req.get();
}
else
{
Logger.log("_setBookmarkTags.Cache");
this._dataBookmarkTags = store;
};
},
_getCompleteTags: function (_imgID, _imgTags) { // {{{2
let self = this;
let bookmarkTags = this._dataBookmarkTags;
let key = _imgID || "_";
if (!this._dataCompleteTags[key] && bookmarkTags)
{
let _dict = {};
_dict["sep"] = [["", ""]];
_dict["both"] = _imgTags.filter(function (t) bookmarkTags[t]).map(function (t) [t, bookmarkTags[t] + " + " + self._message.echo["reqtag"]]);
_dict["illust-full"] = _imgTags.map(function (s) [s, self._message.echo["reqtag"]]);
_dict["bookmark-full"] = [[k, bookmarkTags[k]] for (k in bookmarkTags)];
let (both = util.Array.toObject(_dict["both"]))
{
_dict["illust"] = _dict["illust-full"].filter(function ([t, d]) !both[t]);
_dict["bookmark"] = _dict["bookmark-full"].filter(function ([t, d]) !both[t]);
};
this._dataCompleteTags[key] = this._sortCompleteTags(this._setting.completion.tag || ["illust-full", "bookmark-full"], _dict);
};
return this._dataCompleteTags[key];
},
_sortCompleteTags: function (keys, dict) { // {{{2
let self = this;
let _calc = function ([t, d]) (d == self._message.echo["reqtag"])? t: d.match(/\d+/g).map(parseFloat).reduce(function (a, b) a + b);
let _sort = (this._setting.completion.sort)? function (arr) arr.sort(function (a, b) CompletionContext.Sort.number(_calc(a), _calc(b))): util.identity;
return util.Array.flatten(keys.map(function (key) _sort(dict[key] || [])));
},
_postBookmark: function (_type, _tag, _limit) { // {{{2
liberator.assert(!(_limit && _limit > 3), "Accessed Limit");
let self = this;
let options = {
mode: "add",
type: _type,
id: this._id[_type],
tag: (_tag && _tag.replace(/,(\s+|\s?)/g, " ").replace(/^\s+|\s+$/, "")) || "",
restrict: this._setting.addPublic[_type],
tt: this.TT,
};
let req = new libly.Request("http://www.pixiv.net/bookmark_add.php", {Referrer: liberator.modules.buffer.URL}, {postBody: toQuery(options)});
req.addEventListener("onSuccess", function (res) {
let limit = _limit || 0;
let status = [options.type, options.id, options.tag, _limit].join(", ");
let responseIs = function (text) [message for (message in self._message.page) if (~text.indexOf(self._message.page[message]))][0];
switch (responseIs(res.responseText)) {
case "success":
Logger.log("_postBookmark.Success(" + status + ")");
break;
case "bookmark":
Logger.log("_postBookmark.reSuccess(" + status + ")");
break;
case "toppage":
Logger.log("_postBookmark.SessionOut(" + status + ")");
self._postBookmark(_type, _tag, ++limit);
break;
default:
if (!self.TT)
{
Logger.log("_postBookmark.MoreTry(" + status + res.req.body + ")");
self._setTT(function () self._postBookmark(_type, _tag, ++limit));
}
else
Logger.echoerr("_postBookmark.Error(" + status + res.req.body + ")");
break;
};
});
req.addEventListener("onFailure", function (res) Logger.echoerr("_postBookmark.Failure" ));
req.addEventListener("onException", function (res) Logger.echoerr("_postBookmark.Exception"));
req.post();
},
_postTombloo: function () { // {{{2
let getContext = function (elem)
{
let doc = window.content.document;
let win = window.content.wrappedJSObject;
let context = {
document : doc,
window : win,
title : doc.title,
selection : win.getSelection().toString(),
target : elem,
};
for (let p in win.location)
context[p] = win.location[p];
return context;
};
let ctx = getContext(
this._dom.bigImage || (this._dom.mangaViewer && $LX("img", this._dom.mangaViewer).src.replace("_m.", "_p0.")) || this._addBigImage(true)
);
let ext = this.tomblooService.check(ctx)[0];
this.tomblooService.share(ctx, ext, !/^Photo/.test(ext.name)).addCallback(function ()
Logger.log("_postTombloo.Success(" + ctx.href + ")")
).addErrback(function (err)
Logger.log("_postTombloo.Error(" + err + ")")
);
},
_setTT: function (_callback) { // {{{2
let self = this;
let req = new libly.Request("http://www.pixiv.net/mypage.php", {Referrer: "http://www.pixiv.net/"});
req.addEventListener("onSuccess", function (res) {
let e = res.getHTMLDocument("//input[@name='tt']");
if (e && e[0])
{
self.TT = e[0].value;
Logger.log("_setTT.Success(" + self.TT + ")");
if (_callback && typeof _callback == 'function')
_callback.call(self);
}
else
Logger.log("_setTT.Error(" + res.req.body + ")");
});
req.addEventListener("onFailure", function (res) Logger.echoerr("_setTT.Failure" ));
req.addEventListener("onException", function (res) Logger.echoerr("_setTT.Exception"));
req.get();
},
// }}}
},
{ // classProperties {{{1
toggleIllust: function () { // {{{2
liberator.assert(PixivTools._check.inIllust, "This Page is not Illust Page");
let BigImage = PixivTools._dom.bigImage;
let MangaViewer = PixivTools._dom.mangaViewer;
if (BigImage)
toggleDisplay(BigImage);
else if (!BigImage && MangaViewer)
liberator.open(MangaViewer.href);
else if (!BigImage && !MangaViewer)
PixivTools._addBigImage();
},
postBookmark: function (_addUserFlag) { // {{{2
if (PixivTools._check.inFront || PixivTools._check.inList || _addUserFlag)
{
liberator.assert(!PixivTools._check.isFavUser, "This User is Bookmarked");
commandline.input(
"Add User Bookmark? [Y/n]: ",
function (input) checkInput(input) && PixivTools._postBookmark("user")
);
}
else if (PixivTools._check.inIllust)
{
commandline.input(
(PixivTools._check.isFavIllust? "Update": "Add") + " Illust Bookmark [Tags]: ",
function (input) checkInput("y") && PixivTools._postBookmark("illust", input),
{
completer: function (context) {
if (context.filter)
{
let resep = RegExp("^(" + context.filter.replace(/^\s+|\s+$/, "").split(/\s+/).join("|") + ")$", "i");
context.filters.push(function(item) !resep.test(item.text));
};
context.completions = PixivTools._getCompleteTags(PixivTools._id.illust, PixivTools._dom.imgTags);
context.title.push((new Date(PixivTools._store.get("time", 0))).toISOString());
let (skip = context.filter.match(/^.*\s+/))
skip && context.advance(skip[0].length);
}
}
);
}
else
Logger.echoerr("postBookmark.Error");
},
postTombloo: function () { // {{{2
liberator.assert(PixivTools._check.inIllust, "This Page is not Illust Page");
commandline.input(
"Post Tombloo? [Y/n]: ",
function (input) checkInput(input) && PixivTools._postTombloo()
);
},
update: function () { // {{{2
PixivTools._dataCompleteTags = {};
PixivTools._setTT();
PixivTools._setBookmarkTags(true);
},
addCommands: function () { // {{{2
let self = this;
let add = function (_name, _lambda, _option)
commands.addUserCommand(["Pixiv" + _name], _name.replace(/\W/g, "").replace(/\B[A-Z]/g, " $&"), _lambda, _option || {}, true);
[
["UserFr[ont]" , function () "http://www.pixiv.net/member.php?id=" + PixivTools._id.user],
["UserL[ist]" , function () "http://www.pixiv.net/member_illust.php?id=" + PixivTools._id.user],
["UserBb[s]" , function () "http://www.pixiv.net/member_board.php?id=" + PixivTools._id.user],
["UserBo[okmark]" , function () "http://www.pixiv.net/bookmark.php?id=" + PixivTools._id.user],
["UserI[llustTag]" , function () "http://www.pixiv.net/member_tag_all.php?id=" + PixivTools._id.user],
["UserR[esponse]" , function () "http://www.pixiv.net/response.php?mode=all&id=" + PixivTools._id.user],
["UserM[yPic]" , function () "http://www.pixiv.net/mypixiv_all.php?id=" + PixivTools._id.user],
["UserFa[vUser]" , function () "http://www.pixiv.net/bookmark.php?type=user&id=" + PixivTools._id.user],
["Illust" , function () "http://www.pixiv.net/member_illust.php?mode=medium&illustid=" + PixivTools._id.illust],
["IllustB[ookmark]" , function () "http://www.pixiv.net/bookmark_illust_user.php?illustid=" + PixivTools._id.illust],
["IllustP[rev]" , function () PixivTools._get.vicinityImages[1].href],
["IllustN[ext]" , function () PixivTools._get.vicinityImages[0].href],
].forEach(function ([_name, _url])
add("Cd" + _name, function (args) PixivTools._check.inPixiv && liberator.open(_url(), args.bang? liberator.NEW_TAB: liberator.CURRENT_TAB), {bang: true})
);
add("FavA[uto]" , function () PixivTools._check.inPixiv && self.postBookmark());
add("FavI[llust]" , function () PixivTools._check.inIllust && self.postBookmark(false));
add("FavU[ser]" , function () PixivTools._check.inPixiv && self.postBookmark(true));
add("ToggleI[llust]" , function () PixivTools._check.inIllust && self.toggleIllust());
add("ToggleC[omment]", function () PixivTools._check.inIllust && window.content.wrappedJSObject.one_comment_view());
add("Post[Tombloo]" , function () PixivTools._check.inIllust && self.postTombloo());
add("U[pdate]" , function () self.update());
},
} // }}}1
);
liberator.plugins.pixiv_tools_class = PixivTools();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment