-
-
Save mywarr/b1eb99204e396ec401113851d470d614 to your computer and use it in GitHub Desktop.
自動為 PTT 網頁版的文章代碼加上連結的 userscript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name PTT Web Auto AID Link | |
// @description 自動為 PTT 網頁版的文章代碼加上連結 | |
// @namespace https://www.ptt.cc/bbs | |
// @author Shao-Chung Chen | |
// @license MIT (http://opensource.org/licenses/MIT) | |
// @version 1.3.0 | |
// @include http://www.ptt.cc/* | |
// @include https://www.ptt.cc/* | |
// | |
// @history 1.3 support post share syntax such as "※ [本文轉錄自 share 看板 #1Kx_iESk ]" | |
// @history 1.2 support board name syntax such as "#1ItZvO1L (C_and_CPP)" | |
// @history 1.1 recursively traverse all textNodes to prevent breaking <a> tags | |
// @history 1.0 initial commmit | |
// ==/UserScript== | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat | |
if (!String.prototype.repeat) { | |
String.prototype.repeat = function(count) { | |
'use strict'; | |
if (this == null) { | |
throw new TypeError('can\'t convert ' + this + ' to object'); | |
} | |
var str = '' + this; | |
count = +count; | |
if (count != count) { | |
count = 0; | |
} | |
if (count < 0) { | |
throw new RangeError('repeat count must be non-negative'); | |
} | |
if (count == Infinity) { | |
throw new RangeError('repeat count must be less than infinity'); | |
} | |
count = Math.floor(count); | |
if (str.length == 0 || count == 0) { | |
return ''; | |
} | |
// Ensuring count is a 31-bit integer allows us to heavily optimize the | |
// main part. But anyway, most current (august 2014) browsers can't handle | |
// strings 1 << 28 chars or longer, so: | |
if (str.length * count >= 1 << 28) { | |
throw new RangeError('repeat count must not overflow maximum string size'); | |
} | |
var rpt = ''; | |
for (;;) { | |
if ((count & 1) == 1) { | |
rpt += str; | |
} | |
count >>>= 1; | |
if (count == 0) { | |
break; | |
} | |
str += str; | |
} | |
return rpt; | |
} | |
} | |
String.prototype.rjust = function (width, padding) { | |
padding = (padding || " ").substr(0, 1); | |
if (this.length < width) { | |
return padding.repeat(width - this.length) + this; | |
} | |
else { | |
return this; | |
} | |
}; | |
var pttArticleUrlFromAidc = (function() { | |
// 1. https://github.com/ptt/pttbbs/blob/master/mbbsd/aids.c | |
// 2. https://github.com/ptt/pttbbs/blob/master/docs/aids.txt | |
// 3. JavaScript bitwise operations are restricted in lower 32 bits | |
var aid_base64_table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; | |
var aidc2aidu = function (aidc) { | |
var aidu = 0; | |
for (var i = 0; i < aidc.length; i++) { | |
var ch = aidc.charAt(i); | |
var v = aid_base64_table.indexOf(ch); | |
aidu = aidu * Math.pow(2, 6); // aidu <<= 6 | |
aidu = aidu - (aidu & 0x3f) + ((aidu & 0x3f) | (v & 0x3f)) // aidu |= (v & 0x3f); | |
} | |
return aidu; | |
}; | |
var aidu2fn = function (aidu) { | |
var type = ((aidu / Math.pow(2, 44)) & 0xf); // type = ((aidu >> 44) & 0xf); | |
var v1 = ((aidu / Math.pow(2, 12)) & 0xffffffff); // v1 = ((aidu >> 12) & 0xffffffff); | |
var v2 = (aidu & 0xfff); | |
var filename = (type == 0 ? "M" : "G") + "." + v1.toString(10) + ".A." + v2.toString(16).toUpperCase().rjust(3, "0"); | |
return filename; | |
}; | |
var buildUrl = function(boardName, fileName) { | |
var protocol = window.location.protocol; | |
var hostname = window.location.hostname; | |
var port = window.location.port; | |
var url = protocol + "//" + hostname + port + "/bbs/" + boardName + "/" + fileName + ".html"; | |
return url; | |
}; | |
var boardNameFromUrl = window.location.pathname.match(/\/bbs\/([^\/]+)/)[1]; | |
return function (aidc, boardName) { | |
// aidc should match [0-9a-zA-Z_\-]{8} | |
var aidu = aidc2aidu(aidc); | |
var fileName = aidu2fn(aidu); | |
var articleUrl = buildUrl(boardName||boardNameFromUrl, fileName); | |
console.log("aidc =", aidc, "boardName =", boardName); | |
return articleUrl; | |
}; | |
})(); | |
var linkifyAllAidsInContainer = function(containerDomObj) { | |
var buildLinkNode = function (aid, url) { | |
var a = document.createElement("a"); | |
a.href = url; | |
a.target = "_blank"; | |
a.text = aid; | |
return a; | |
} | |
// example: "share 看板 #1Kx_iESk" => [..., "share", "#1Kx_iESk"] | |
// test: https://www.ptt.cc/bbs/Little-Games/M.1425013836.A.CDF.html | |
var aidc_regexp1 = /(\S+)\s看板\s(#[0-9a-zA-Z_\-]{8})/; | |
// example #1: "#1Kx_iESk" => [..., "#1Kx_iESk"] | |
// example #2: "#1Kx_iESk (share)" => [..., "#1Kx_iESk", "share"] | |
// text: https://www.ptt.cc/bbs/C_Chat/M.1411662330.A.526.html | |
var aidc_regexp2 = /(#[0-9a-zA-Z_\-]{8})(?:\s?\((\S+)\))?/; | |
// 1. "share 看板 #1Kx_iESk" | |
// 2. "#1Kx_iESk" | |
// 3. "#1Kx_iESk (share)" | |
var aidc_regexp_split = /((?:\S+\s看板\s)?#[0-9a-zA-Z_\-]{8}(?:\s?\(\S+\))?)/; | |
var linkifyAllAidsInTextNode = function(parentNode, textNode) { | |
// split text node to "text node + <a> node + text node + ..." and insert back | |
var originalText = textNode.nodeValue; | |
if (aidc_regexp2.test(originalText)) { | |
var newNodeList = [document.createTextNode(originalText)]; | |
while (true) { | |
var lastNode = newNodeList.pop(); | |
if (lastNode.nodeType != Node.TEXT_NODE) { | |
newNodeList.push(lastNode); | |
break; | |
} | |
var textSegments = lastNode.nodeValue.split(aidc_regexp_split); | |
if (textSegments.length == 1) { | |
newNodeList.push(lastNode); | |
break; | |
} | |
textSegments.forEach(function(textSegment, index) { | |
if (m=textSegment.match(aidc_regexp1)) { | |
var aidc = m[2].substr(1); // remove starting # | |
var boardName = m[1]; // must exists | |
var url = pttArticleUrlFromAidc(aidc, boardName); | |
var linkNode = buildLinkNode(textSegment, url); | |
newNodeList.push(linkNode); | |
} | |
else if (m=textSegment.match(aidc_regexp2)) { | |
var aidc = m[1].substr(1); // remove starting # | |
var boardName = m[2]; // undefined if not specified | |
var url = pttArticleUrlFromAidc(aidc, boardName); | |
var linkNode = buildLinkNode(textSegment, url); | |
newNodeList.push(linkNode); | |
} | |
else { | |
newNodeList.push(document.createTextNode(textSegment)); | |
} | |
}); | |
}; | |
var jobFunc = function() { | |
newNodeList.forEach(function(newNode, index) { | |
parentNode.insertBefore(newNode, textNode); | |
}); | |
parentNode.removeChild(textNode); | |
}; | |
return jobFunc; | |
}; | |
return undefined; | |
}; | |
// cannot manipulate NodeList[] during iteration | |
// hence we use a job queue to perform all replacements at last | |
var jobFuncQueue = []; | |
var linkifyAllAidsInAllTextNodesRecursively = function (parentNode) { | |
var childNodes = parentNode.childNodes; | |
[].forEach.call(childNodes, function(node, index) { | |
switch(node.nodeType) { | |
case Node.ELEMENT_NODE: | |
// don't touch <a>, otherwise we may break links containing /#[0-9a-zA-Z_\-]{8}/ | |
if (node.tagName.toLowerCase() != "a") { | |
linkifyAllAidsInAllTextNodesRecursively(node, node.childNodes); | |
} | |
break; | |
case Node.TEXT_NODE: | |
var jobFunc = linkifyAllAidsInTextNode(parentNode, node); | |
if (jobFunc) { | |
jobFuncQueue.push(jobFunc); | |
} | |
break; | |
}; | |
}); | |
}; | |
linkifyAllAidsInAllTextNodesRecursively(containerDomObj); | |
jobFuncQueue.forEach(function(jobFunc, index) { | |
jobFunc(); | |
}); | |
}; | |
var linkifyAllAidsInPage = function() { | |
var mainContent = document.querySelector('#main-content'); | |
linkifyAllAidsInContainer(mainContent); | |
}; | |
if (window.location.host.toLowerCase().indexOf("ptt.cc") >= 0) { | |
window.addEventListener("load", linkifyAllAidsInPage, false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment