Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ニコニコ動画でgetFlvを呼び出す関数
(function() {
if (!('nicovideo_getFlv' in window)) {
const Getter = function(videoID) {
this._videoID = videoID;
this._callbacks = [];
};
Getter.prototype = {
_videoID: null,
_lock: false,
_callbacks: null,
_cacheStr: null,
_cacheObj: null,
get: function(callback) {
if (typeof callback === 'function')
this._callbacks.push(callback);
if (this._cacheStr !== null) {
this._callCallback();
return;
}
if (this._lock) return;
this._lock = true;
let self = this;
this._updateCache(function() {
self._callCallback();
self._lock = false;
});
},
_callCallback: function() {
let original = this._cacheObj, str = this._cacheStr;
this._callbacks.forEach(function(c) {
try {
let obj = {};
for (let key in original) {
if (original.hasOwnProperty(key))
obj[key] = original[key];
}
c(obj, str);
} catch(e) {
GM_log(e);
}
});
this._callbacks = [];
},
_updateCache: function(callback) {
let self = this;
GM_xmlhttpRequest( {
method: 'GET',
url: 'http://flapi.nicovideo.jp/api/getflv/' + this._videoID,
headers: {
'User-Agent': 'Mozilla/5.0 Greasemonkey; NicoGetFlv'
},
onload: function(response) {
self._cacheStr = response.responseText;
self._cacheObj = self._parse(response.responseText);
callback();
},
onerror: function(response) {
self._cacheStr = null;
self._cacheObj = null;
callback();
}
});
},
_parse: function(str) {
let result = {};
let pairs = str.split('&').map(
function(pair) pair.split('=').map(decodeURIComponent)
).forEach(function([key, value]) {
switch (key) {
case 'rpu':
result[key] = JSON.parse(value);
break;
case 'ng_up':
result[key] = value.split('&').map(
function(data) {
let [before, after] = data.split('=').map(decodeURIComponent);
let replaceAll = false;
if (before[0] === '*') {
before = before.slice(1);
replaceAll = true;
}
return [ before, after, replaceAll ];
}
);
break;
default:
result[key] = value;
break;
}
});
return result;
}
};
let getters = {};
getters.__proto__ = null;
window.nicovideo_getFlv = function(videoID, callback) {
let getter = null;
if (videoID in getters) {
getter = getters[videoID];
} else {
getter = new Getter(videoID);
getters[videoID] = getter;
}
getter.get(callback);
};
};
})();
nicovideo_getFlv('sm9', function(obj, responseText) {
// http://flapi.nicovideo.jp/api/getflv/sm9 の内容を取得する
alert(responseText); // 上記URLにアクセスして得られる文字列
alert(uneval(obj)); // 得られた文字列をパースしたもの
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment