Greasy Fork 还支持 简体中文。

Wanikani Open Framework - Apiv2 module

Apiv2 module for Wanikani Open Framework

目前為 2018-03-02 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/38581/255508/Wanikani%20Open%20Framework%20-%20Apiv2%20module.js

  1. // ==UserScript==
  2. // @name Wanikani Open Framework - Apiv2 module
  3. // @namespace rfindley
  4. // @description Apiv2 module for Wanikani Open Framework
  5. // @version 1.0.1
  6. // @copyright 2018+, Robin Findley
  7. // @license MIT; http://opensource.org/licenses/MIT
  8. // ==/UserScript==
  9.  
  10. (function(global) {
  11.  
  12. //########################################################################
  13. //------------------------------
  14. // Published interface.
  15. //------------------------------
  16. global.wkof.Apiv2 = {
  17. clear_cache: clear_cache,
  18. fetch_endpoint: fetch_endpoint,
  19. get_endpoint: get_endpoint,
  20. is_valid_apikey_format: is_valid_apikey_format,
  21. };
  22. //########################################################################
  23.  
  24. function promise(){var a,b,c=new Promise(function(d,e){a=d;b=e;});c.resolve=a;c.reject=b;return c;}
  25.  
  26. var available_endpoints = [
  27. 'assignments','level_progressions','resets','review_statistics',
  28. 'reviews','study_materials','subjects','summary','user'
  29. ];
  30. var using_apikey_override = false;
  31. var skip_username_check = false;
  32.  
  33. //------------------------------
  34. // Retrieve the username from the page.
  35. //------------------------------
  36. function get_username() {
  37. try {
  38. return ($('.account a[href^="/users/"]').attr('href') || '').match(/[^\/]+$/)[0];
  39. } catch(e) {
  40. return undefined;
  41. }
  42. }
  43.  
  44. //------------------------------
  45. // Check if a string is a valid apikey format.
  46. //------------------------------
  47. function is_valid_apikey_format(str) {
  48. return ((typeof str === 'string') &&
  49. (str.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) !== null));
  50. }
  51.  
  52. //------------------------------
  53. // Clear any datapoint cache not belonging to the current user.
  54. //------------------------------
  55. function clear_cache() {
  56. var clear_promises = [];
  57. var dir = wkof.file_cache.dir;
  58. for (var idx in available_endpoints) {
  59. var filename = 'Apiv2.'+available_endpoints[idx];
  60. if (filename === 'Apiv2.subjects' || !dir[filename]) continue;
  61. clear_promises.push(filename);
  62. }
  63. clear_promises = clear_promises.map(delete_file);
  64.  
  65. if (clear_promises.length > 0) {
  66. console.log('Clearing user cache...');
  67. return Promise.all(clear_promises);
  68. } else {
  69. return Promise.resolve();
  70. }
  71.  
  72. function delete_file(filename){
  73. return wkof.file_cache.delete(filename);
  74. }
  75. }
  76.  
  77. wkof.set_state('wkof.Apiv2.key', 'not_ready');
  78.  
  79. //------------------------------
  80. // Get the API key (either from localStorage, or from the Account page).
  81. //------------------------------
  82. function get_apikey() {
  83. // If we already have the apikey, just return it.
  84. if (is_valid_apikey_format(wkof.Apiv2.key))
  85. return Promise.resolve(wkof.Apiv2.key);
  86.  
  87. // If we don't have the apikey, but override was requested, return error.
  88. if (using_apikey_override)
  89. return Promise.reject('Invalid api2_key_override in localStorage!');
  90.  
  91. // Fetch the apikey from the account page.
  92. console.log('Fetching API key...');
  93. wkof.set_state('wkof.Apiv2.key', 'fetching');
  94. return wkof.load_file('https://www.wanikani.com/settings/account')
  95. .then(parse_page);
  96.  
  97. function parse_page(page){
  98. var page = $(page);
  99. var apikey = page.find('#user_api_key_v2').val();
  100. if (!wkof.Apiv2.is_valid_apikey_format(apikey))
  101. return Promise.reject('No API key (version 2) found on account page!');
  102.  
  103. // Store the api key.
  104. wkof.Apiv2.key = apikey;
  105. localStorage.setItem('apiv2_key', apikey);
  106. wkof.set_state('wkof.Apiv2.key', 'ready');
  107. return apikey;
  108. };
  109. }
  110.  
  111. //------------------------------
  112. // Fetch a URL asynchronously, and pass the result as resolved Promise data.
  113. //------------------------------
  114. function fetch_endpoint(endpoint, options) {
  115. var retry_cnt, endpoint_data, url, headers;
  116. var progress_data = {name:'wk_api_'+endpoint, label:'Wanikani '+endpoint, value:0, max:100};
  117. var bad_key_cnt = 0;
  118.  
  119. // Parse options.
  120. if (!options) options = {};
  121. var filters = options.filters;
  122. if (!filters) filters = {};
  123. var progress_callback = options.progress_callback;
  124.  
  125. // Get timestamp of last fetch from options (if specified)
  126. var last_update = options.last_update;
  127.  
  128. // If no prior fetch, set last_update to ancient date.
  129. if (typeof last_update !== 'string') {
  130. if (filters.updated_after === undefined)
  131. last_update = '1999-01-01T01:00:00.000000Z';
  132. else
  133. last_update = filters.updated_after;
  134. }
  135.  
  136. // Set up URL and headers
  137. url = "https://www.wanikani.com/api/v2/" + endpoint;
  138.  
  139. // Add user-specified data filters to the URL
  140. filters.updated_after = last_update;
  141. var arr = [];
  142. for (var name in filters) {
  143. var value = filters[name];
  144. if (Array.isArray(value)) value = value.join(',');
  145. arr.push(name+'='+value);
  146. }
  147. url += '?'+arr.join('&');
  148.  
  149. // Get API key and fetch the data.
  150. var fetch_promise = promise();
  151. get_apikey()
  152. .then(setup_and_fetch);
  153.  
  154. return fetch_promise;
  155.  
  156. //============
  157. function setup_and_fetch() {
  158. wkof.Progress.update(progress_data);
  159. headers = {
  160. // 'Wanikani-Revision': '20170710', // Placeholder?
  161. 'Authorization': 'Bearer '+wkof.Apiv2.key,
  162. };
  163. headers['If-Modified-Since'] = new Date(last_update).toUTCString(last_update);
  164.  
  165. retry_cnt = 0;
  166. fetch();
  167. }
  168.  
  169. //============
  170. function fetch() {
  171. retry_cnt++;
  172. var request = new XMLHttpRequest();
  173. request.onreadystatechange = received;
  174. request.open('GET', url, true);
  175. for (var key in headers)
  176. request.setRequestHeader(key, headers[key]);
  177. request.send();
  178. }
  179.  
  180. //============
  181. function received(event) {
  182. // ReadyState of 4 means transaction is complete.
  183. if (this.readyState !== 4) return;
  184.  
  185. // Check for rate-limit error. Delay and retry if necessary.
  186. if (this.status === 429 && retry_cnt < 40) {
  187. var delay = Math.min((retry_cnt * 250), 2000);
  188. setTimeout(fetch, delay);
  189. return;
  190. }
  191.  
  192. // Check for bad API key.
  193. if (this.status === 401) return bad_apikey();
  194.  
  195. // Check of 'no updates'.
  196. if (this.status >= 300) {
  197. if (typeof progress_callback === 'function')
  198. progress_callback(endpoint, 0, 1, 1);
  199. progress_data.value = 1;
  200. progress_data.max = 1;
  201. wkof.Progress.update(progress_data);
  202. return fetch_promise.reject({status:this.status, url:url});
  203. }
  204.  
  205. // Process the response data.
  206. var json = JSON.parse(event.target.response);
  207.  
  208. // Data may be a single object, or collection of objects.
  209. // Collections are paginated, so we may need more fetches.
  210. if (json.object === 'collection') {
  211. // It's a multi-page endpoint.
  212. var first_new, so_far, total;
  213. if (endpoint_data === undefined) {
  214. // First page of results.
  215. first_new = 0;
  216. so_far = json.data.length;
  217. } else {
  218. // Nth page of results.
  219. first_new = endpoint_data.data.length;
  220. so_far = first_new + json.data.length;
  221. json.data = endpoint_data.data.concat(json.data);
  222. }
  223. endpoint_data = json;
  224. total = json.total_count;
  225.  
  226. // Call the 'progress' callback.
  227. if (typeof progress_callback === 'function')
  228. progress_callback(endpoint, first_new, so_far, total);
  229. progress_data.value = so_far;
  230. progress_data.max = total;
  231. wkof.Progress.update(progress_data);
  232.  
  233. // If there are more pages, fetch the next one.
  234. if (json.pages.next_url !== null) {
  235. retry_cnt = 0;
  236. url = json.pages.next_url;
  237. fetch();
  238. return;
  239. }
  240.  
  241. // This was the last page. Return the data.
  242. fetch_promise.resolve(endpoint_data);
  243.  
  244. } else {
  245. // Single-page result. Report single-page progress, and return data.
  246. if (typeof progress_callback === 'function')
  247. progress_callback(endpoint, 0, 1, 1);
  248. progress_data.value = 1;
  249. progress_data.max = 1;
  250. wkof.Progress.update(progress_data);
  251. fetch_promise.resolve(json);
  252. }
  253. }
  254.  
  255. //============
  256. function bad_apikey(){
  257. // If we are using an override key, abort and return error.
  258. if (using_apikey_override) {
  259. fetch_promise.reject('Wanikani doesn\'t recognize the apiv2_key_override key ("'+wkof.Apiv2.key+'")');
  260. return;
  261. }
  262.  
  263. // If bad key received too many times, abort and return error.
  264. bad_key_cnt++;
  265. if (bad_key_cnt > 1) {
  266. fetch_promise.reject('Aborting fetch: Bad key reported multiple times!');
  267. return;
  268. }
  269.  
  270. // We received a bad key. Report on the console, then try fetching the key (and data) again.
  271. console.log('Seems we have a bad API key. Erasing stored info.');
  272. localStorage.removeItem('apiv2_key');
  273. wkof.Apiv2.key = undefined;
  274. get_apikey()
  275. .then(populate_user_cache)
  276. .then(setup_and_fetch);
  277. }
  278. }
  279.  
  280.  
  281. var min_update_interval = 60;
  282. var ep_cache = {};
  283.  
  284. //------------------------------
  285. // Get endpoint data from cache with updates from API.
  286. //------------------------------
  287. function get_endpoint(ep_name, options) {
  288. if (!options) options = {};
  289.  
  290. // We cache data for 'min_update_interval' seconds.
  291. // If within that interval, we return the cached data.
  292. // User can override cache via "options.force_update = true"
  293. var ep_info = ep_cache[ep_name];
  294. if (ep_info) {
  295. // If still awaiting prior fetch return pending promise.
  296. // Also, not force_update, return non-expired cache (i.e. resolved promise)
  297. if (options.force_update !== true || ep_info.timer === undefined)
  298. return ep_info.promise;
  299. // User is requesting force_update, and we have unexpired cache.
  300. // Clear the expiration timer since we will re-fetch anyway.
  301. clearTimeout(ep_info.timer);
  302. }
  303.  
  304. // Create a promise to fetch data. The resolved promise will also serve as cache.
  305. var get_promise = promise();
  306. ep_cache[ep_name] = {promise: get_promise};
  307.  
  308. // Make sure the requested endpoint is valid.
  309. var merged_data;
  310. if (available_endpoints.indexOf(ep_name) < 0) {
  311. get_promise.reject(new Error('Invalid endpoint name "'+ep_name+'"'));
  312. return get_promise;
  313. }
  314.  
  315. // Perform the fetch, and process the data.
  316. wkof.file_cache.load('Apiv2.'+ep_name)
  317. .then(fetch, fetch);
  318. return get_promise;
  319.  
  320. //============
  321. function fetch(cache_data) {
  322. if (typeof cache_data === 'string') cache_data = {last_update:null};
  323. merged_data = cache_data;
  324. var fetch_options = Object.assign({}, options);
  325. fetch_options.last_update = cache_data.last_update;
  326. fetch_endpoint(ep_name, fetch_options)
  327. .then(process_api_data, handle_error);
  328. }
  329.  
  330. //============
  331. function process_api_data(fetched_data) {
  332. // Mark the data with the last_update timestamp reported by the server.
  333. if (fetched_data.data_updated_at !== null) merged_data.last_update = fetched_data.data_updated_at;
  334.  
  335. // Process data according to whether it is paginated or not.
  336. if (fetched_data.object === 'collection') {
  337. if (merged_data.data === undefined) merged_data.data = {};
  338. for (var idx = 0; idx < fetched_data.data.length; idx++) {
  339. var item = fetched_data.data[idx];
  340. merged_data.data[item.id] = item;
  341. }
  342. } else {
  343. merged_data.data = fetched_data.data;
  344. }
  345.  
  346. // If it's the 'user' endpoint, we insert the apikey before caching.
  347. if (ep_name === 'user') merged_data.data.apikey = wkof.Apiv2.key;
  348.  
  349. // Save data to cache and finish up.
  350. wkof.file_cache.save('Apiv2.'+ep_name, merged_data)
  351. .then(finish);
  352. }
  353.  
  354. //============
  355. function finish() {
  356. // Return the data, then set up a cache expiration timer.
  357. get_promise.resolve(merged_data.data);
  358. ep_cache[ep_name].timer = setTimeout(expire_cache, min_update_interval*1000);
  359. }
  360.  
  361. //============
  362. function expire_cache() {
  363. // Delete the data from cache.
  364. delete ep_cache[ep_name];
  365. }
  366.  
  367. //============
  368. function handle_error(error) {
  369. if (typeof error === 'string')
  370. get_promise.reject(error);
  371. if (error.status >= 300 && error.status <= 399)
  372. finish();
  373. else
  374. get_promise.reject('Error '+error.status+' fetching "'+error.url+'"');
  375. }
  376. }
  377.  
  378. //########################################################################
  379. //------------------------------
  380. // Make sure user cache matches the current (or override) user.
  381. //------------------------------
  382. function validate_user_cache() {
  383. var user = get_username();
  384. if (!user) {
  385. // Username unavailable if not logged in, or if on Lessons or Reviews pages.
  386. // If not logged in, stop running the framework.
  387. if (location.pathname.match(/^(\/|\/login)$/) !== null)
  388. return Promise.reject('Couldn\'t extract username from user menu! Not logged in?');
  389. skip_username_check = true;
  390. }
  391.  
  392. var apikey = localStorage.getItem('apiv2_key_override');
  393. if (apikey !== null) {
  394. // It looks like we're trying to override the apikey (e.g. for debug)
  395. using_apikey_override = true;
  396. if (!is_valid_apikey_format(apikey)) {
  397. return Promise.reject('Invalid api2_key_override in localStorage!');
  398. }
  399. console.log('Using apiv2_key_override key ('+apikey+')');
  400. } else {
  401. // Use regular apikey (versus override apikey)
  402. apikey = localStorage.getItem('apiv2_key');
  403. if (!is_valid_apikey_format(apikey)) apikey = undefined;
  404. }
  405.  
  406. wkof.Apiv2.key = apikey;
  407.  
  408. // Make sure cache is still valid
  409. return wkof.file_cache.load('Apiv2.user')
  410. .then(process_user_info)
  411. .catch(retry);
  412.  
  413. //============
  414. function process_user_info(user_info) {
  415. // If cache matches, we're done.
  416. if (user_info.data.apikey === wkof.Apiv2.key) {
  417. // We don't check username when using override key.
  418. if (using_apikey_override || skip_username_check || (user_info.data.username === user)) {
  419. wkof.Apiv2.user = user_info.data.username;
  420. wkof.user = user_info.data;
  421. return;
  422. }
  423. }
  424. // Cache doesn't match.
  425. if (!using_apikey_override) {
  426. // Fetch the key from the accounts page.
  427. wkof.Apiv2.key = undefined;
  428. throw 'fetch key';
  429. } else {
  430. // We're using override. No need to fetch key, just populate cache.
  431. return clear_cache().then(populate_user_cache);
  432. }
  433. }
  434.  
  435. //============
  436. function retry() {
  437. // Either empty cache, or user mismatch. Fetch key, then populate cache.
  438. return get_apikey().then(clear_cache).then(populate_user_cache);
  439. }
  440. }
  441.  
  442. //------------------------------
  443. // Populate the user info into cache.
  444. //------------------------------
  445. function populate_user_cache() {
  446. console.log('Fetching user info...');
  447. return fetch_endpoint('user')
  448. .then(function(user_info){
  449. // Store the apikey in the cache.
  450. user_info.data.apikey = wkof.Apiv2.key;
  451. wkof.Apiv2.user = user_info.data.username;
  452. wkof.user = user_info.data
  453. console.log('Caching user info...');
  454. return wkof.file_cache.save('Apiv2.user', user_info);
  455. })
  456. }
  457.  
  458. //------------------------------
  459. // Do initialization once document is loaded.
  460. //------------------------------
  461. function notify_ready() {
  462. // Notify listeners that we are ready.
  463. // Delay guarantees include() callbacks are called before ready() callbacks.
  464. setTimeout(function(){wkof.set_state('wkof.Apiv2', 'ready');},0);
  465. }
  466.  
  467. //------------------------------
  468. // Do initialization once document is loaded.
  469. //------------------------------
  470. wkof.include('Progress');
  471. wkof.ready('document,Progress').then(startup);
  472. function startup() {
  473. validate_user_cache()
  474. .then(notify_ready);
  475. }
  476.  
  477. })(window);