// function(string text, bool redirect) -> string
var replaceShortUrlAll = (function()
{
var printlnLog = function(message)
{
v2c.println("[post.js/replaceShortUrlAll()] " + message);
};
var expandUrl = function(sourceUrl, redirect)
{
var expanded = v2c.expandShortURL(sourceUrl, true);
if(expanded != sourceUrl)
return expanded;
return redirect
? getRedirectUrl(sourceUrl)
: sourceUrl;
};
var getRedirectUrl = function(sourceUrl)
{
var req = v2c.createHttpRequest(sourceUrl, "");
req.getContentsAsBytes(); // ignore contents
printlnLog(req.responseCode + "\n" + req.getResponseHeader("Location"))
if(301 <= req.responseCode && hr.responseCode <= 303)
{
return getRedirectUrl(req.getResponseHeader("Location"));
}
return sourceUrl;
};
return function(text, redirect)
{
var message = text + "";
return message.replace(/(h?ttps?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/g,
function(s, scheme)
{
printlnLog("match: " + s + ", scheme: " + scheme);
// スキームなしの場合は https を補完
// h抜きの場合は h を補完
scheme = scheme || "";
var ttp = scheme.indexOf("ttp://");
var ttps = scheme.indexOf("ttps://");
var prefix = ttp == -1 && ttps == -1
? "https://"
: ttp == 0 || ttps == 0
? "h"
: "";
return expandUrl(prefix + s, redirect);
});
};
})();
var text = v2c.getSelectedText();
v2c.println("[ReplaceShortUrl.js]" + replaceShortUrlAll(text, false));
Ly8gZnVuY3Rpb24oc3RyaW5nIHRleHQsIGJvb2wgcmVkaXJlY3QpIC0+IHN0cmluZwp2YXIgcmVwbGFjZVNob3J0VXJsQWxsID0gKGZ1bmN0aW9uKCkKewogICAgdmFyIHByaW50bG5Mb2cgPSBmdW5jdGlvbihtZXNzYWdlKQoJewoJCXYyYy5wcmludGxuKCJbcG9zdC5qcy9yZXBsYWNlU2hvcnRVcmxBbGwoKV0gIiArIG1lc3NhZ2UpOwoJfTsKCgl2YXIgZXhwYW5kVXJsID0gZnVuY3Rpb24oc291cmNlVXJsLCByZWRpcmVjdCkKCXsKCQl2YXIgZXhwYW5kZWQgPSB2MmMuZXhwYW5kU2h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