Wanikani Open Framework - Apiv2 module

Apiv2 module for Wanikani Open Framework

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/38581/1402158/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.15
  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. spoof: override_key,
  22. };
  23. //########################################################################
  24.  
  25. function promise(){let a,b,c=new Promise(function(d,e){a=d;b=e;});c.resolve=a;c.reject=b;return c;}
  26.  
  27. let using_apikey_override = false;
  28. let skip_username_check = false;
  29.  
  30. //------------------------------
  31. // Set up an API key to spoof for testing
  32. //------------------------------
  33. function override_key(key) {
  34. if (is_valid_apikey_format(key)) {
  35. localStorage.setItem('apiv2_key_override', key);
  36. } else if (key === undefined) {
  37. let key = localStorage.getItem('apiv2_key_override');
  38. if (key === null) {
  39. console.log('Not currently spoofing.');
  40. } else {
  41. console.log(key);
  42. }
  43. } else if (key === '') {
  44. localStorage.removeItem('apiv2_key_override');
  45. } else {
  46. console.log('That\'s not a valid key!');
  47. }
  48. }
  49.  
  50. //------------------------------
  51. // Retrieve the username from the page.
  52. //------------------------------
  53. function get_username() {
  54. try {
  55. return document.querySelector('.user-summary__username').textContent.trim();
  56. } catch(e) {
  57. return undefined;
  58. }
  59. }
  60.  
  61. //------------------------------
  62. // Check if a string is a valid apikey format.
  63. //------------------------------
  64. function is_valid_apikey_format(str) {
  65. return ((typeof str === 'string') &&
  66. (str.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) !== null));
  67. }
  68.  
  69. //------------------------------
  70. // Clear any datapoint cache not belonging to the current user.
  71. //------------------------------
  72. function clear_cache(include_non_user) {
  73. let clear_promises = [];
  74. let dir = wkof.file_cache.dir;
  75. for (let filename in wkof.file_cache.dir) {
  76. if (!filename.match(/^Apiv2\./)) continue;
  77. if ((filename === 'Apiv2.subjects' && include_non_user !== true) || !dir[filename]) continue;
  78. clear_promises.push(filename);
  79. }
  80. clear_promises = clear_promises.map(delete_file);
  81.  
  82. if (clear_promises.length > 0) {
  83. console.log('Clearing user cache...');
  84. return Promise.all(clear_promises);
  85. } else {
  86. return Promise.resolve();
  87. }
  88.  
  89. function delete_file(filename){
  90. return wkof.file_cache.delete(filename);
  91. }
  92. }
  93.  
  94. wkof.set_state('wkof.Apiv2.key', 'not_ready');
  95.  
  96. //------------------------------
  97. // Get the API key (either from localStorage, or from the Account page).
  98. //------------------------------
  99. function get_apikey() {
  100. // If we already have the apikey, just return it.
  101. if (is_valid_apikey_format(wkof.Apiv2.key))
  102. return Promise.resolve(wkof.Apiv2.key);
  103.  
  104. // If we don't have the apikey, but override was requested, return error.
  105. if (using_apikey_override)
  106. return Promise.reject('Invalid api2_key_override in localStorage!');
  107.  
  108. // Fetch the apikey from the account page.
  109. console.log('Fetching API key...');
  110. wkof.set_state('wkof.Apiv2.key', 'fetching');
  111. return wkof.load_file('/settings/personal_access_tokens')
  112. .then(parse_page);
  113.  
  114. function parse_page(html){
  115. let page = new DOMParser().parseFromString(html, 'text/html');
  116. let apikey = page.querySelector('.api-tokens__tokens .wk-code')?.textContent.trim() || '';
  117. if (!wkof.Apiv2.is_valid_apikey_format(apikey)) {
  118. let status = localStorage.getItem('wkof_generate_token');
  119. if (status === null) {
  120. if (confirm("It looks like you haven't generated a Personal Access Token yet,\nwhich is required to run Open Framework scripts.\nDo you want to generate one now?")) {
  121. return generate_apiv2_key();
  122. } else {
  123. localStorage.setItem('wkof_generate_token', 'ignore');
  124. }
  125. } else if (status === "ignore") {
  126. wkof.Menu.insert_script_link({
  127. name: 'gen_apiv2_key',
  128. title: 'Generate APIv2 key',
  129. on_click: generate_apiv2_key
  130. });
  131. }
  132. return Promise.reject('No API key (version 2) found on account page!');
  133. } else {
  134. delete localStorage.wkof_generate_token;
  135. }
  136.  
  137. // Store the api key.
  138. wkof.Apiv2.key = apikey;
  139. localStorage.setItem('apiv2_key', apikey);
  140. wkof.set_state('wkof.Apiv2.key', 'ready');
  141. return apikey;
  142. };
  143.  
  144. function generate_apiv2_key()
  145. {
  146. localStorage.setItem('wkof_generate_token', 'generating');
  147. return wkof.load_file('/settings/personal_access_tokens/new')
  148. .then(parse_token_page).then(function(){
  149. location.reload();
  150. });
  151. }
  152.  
  153. function parse_token_page(html) {
  154. let page = new DOMParser().parseFromString(html, 'text/html');
  155. let form = page.querySelector('.wk-form');
  156. let hidden_inputs = Array.from(form.querySelectorAll('input[type="hidden"][name="authenticity_token"]'));
  157. let checkboxes = Array.from(form.querySelectorAll('input[type="checkbox"]'));
  158. let submit_url = form.attributes['action'].value;
  159. let data = [].concat(
  160. hidden_inputs.map((elem) => [elem.attributes.name.value, elem.attributes.value.value]),
  161. [['description', 'Open+Framework+%28read-only%29']],
  162. checkboxes.map((elem) => [elem.attributes.name.value, '0']),
  163. [['button','']]
  164. ).map((kv)=>kv.map(encodeURIComponent).join('=')).join('&');
  165.  
  166. return fetch(submit_url, {
  167. method:'POST',
  168. headers: {
  169. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  170. },
  171. body: data
  172. });
  173. }
  174. }
  175.  
  176. //------------------------------
  177. // Fetch a URL asynchronously, and pass the result as resolved Promise data.
  178. //------------------------------
  179. function fetch_endpoint(endpoint, options) {
  180. let retry_cnt, endpoint_data, url, headers;
  181. let progress_data = {name:'wk_api_'+endpoint, label:'Wanikani '+endpoint, value:0, max:100};
  182. let bad_key_cnt = 0;
  183.  
  184. // Parse options.
  185. if (!options) options = {};
  186. let filters = options.filters;
  187. if (!filters) filters = {};
  188. let progress_callback = options.progress_callback;
  189.  
  190. // Get timestamp of last fetch from options (if specified)
  191. let last_update = options.last_update;
  192.  
  193. // If no prior fetch... (i.e. no valid last_update)
  194. if (typeof last_update !== 'string' && !(last_update instanceof Date)) {
  195. // If updated_after is present, use it. Otherwise, default to ancient date.
  196. if (filters.updated_after === undefined)
  197. last_update = '1999-01-01T01:00:00.000000Z';
  198. else
  199. last_update = filters.updated_after;
  200. }
  201. // If last_update is a Date object, convert it to ISO string.
  202. // If it's a string, but not an ISO string, try converting to an ISO string.
  203. if (last_update instanceof Date)
  204. last_update = last_update.toISOString().replace(/Z$/,'000Z');
  205. else if (last_update.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/) === null)
  206. last_update = new Date(last_update).toISOString().replace(/Z$/,'000Z');
  207.  
  208. // Set up URL and headers
  209. url = "https://api.wanikani.com/v2/" + endpoint;
  210.  
  211. // Add user-specified data filters to the URL
  212. filters.updated_after = last_update;
  213. let arr = [];
  214. for (let name in filters) {
  215. let value = filters[name];
  216. if (Array.isArray(value)) value = value.join(',');
  217. arr.push(name+'='+value);
  218. }
  219. url += '?'+arr.join('&');
  220.  
  221. // Get API key and fetch the data.
  222. let fetch_promise = promise();
  223. get_apikey()
  224. .then(setup_and_fetch);
  225.  
  226. return fetch_promise;
  227.  
  228. //============
  229. function setup_and_fetch() {
  230. if (options.disable_progress_dialog !== true) wkof.Progress.update(progress_data);
  231. headers = {
  232. // 'Wanikani-Revision': '20170710', // Placeholder?
  233. 'Authorization': 'Bearer '+wkof.Apiv2.key,
  234. };
  235. headers['If-Modified-Since'] = new Date(last_update).toUTCString(last_update);
  236.  
  237. retry_cnt = 0;
  238. fetch();
  239. }
  240.  
  241. //============
  242. function fetch() {
  243. retry_cnt++;
  244. let request = new XMLHttpRequest();
  245. request.onreadystatechange = received;
  246. request.open('GET', url, true);
  247. for (let key in headers)
  248. request.setRequestHeader(key, headers[key]);
  249. request.send();
  250. }
  251.  
  252. //============
  253. function received(event) {
  254. // ReadyState of 4 means transaction is complete.
  255. if (this.readyState !== 4) return;
  256.  
  257. // Check for rate-limit error. Delay and retry if necessary.
  258. if (this.status === 429 && retry_cnt < 40) {
  259. // Check for "ratelimit-reset" header. Delay until the specified time.
  260. let resetTime = parseInt(this.getResponseHeader("ratelimit-reset"));
  261. if (resetTime) {
  262. let timeRemaining = (resetTime * 1000) - Date.now();
  263. setTimeout(fetch, timeRemaining + 500);
  264. } else {
  265. let delay = Math.min((retry_cnt * 250), 2000);
  266. setTimeout(fetch, delay);
  267. }
  268. return;
  269. }
  270.  
  271. // Check for bad API key.
  272. if (this.status === 401) return bad_apikey();
  273.  
  274. // Check of 'no updates'.
  275. if (this.status >= 300) {
  276. if (typeof progress_callback === 'function')
  277. progress_callback(endpoint, 0, 1, 1);
  278. progress_data.value = 1;
  279. progress_data.max = 1;
  280. if (options.disable_progress_dialog !== true) wkof.Progress.update(progress_data);
  281. return fetch_promise.reject({status:this.status, url:url});
  282. }
  283.  
  284. // Process the response data.
  285. let json = JSON.parse(event.target.response);
  286.  
  287. // Data may be a single object, or collection of objects.
  288. // Collections are paginated, so we may need more fetches.
  289. if (json.object === 'collection') {
  290. // It's a multi-page endpoint.
  291. let first_new, so_far, total;
  292. if (endpoint_data === undefined) {
  293. // First page of results.
  294. first_new = 0;
  295. so_far = json.data.length;
  296. } else {
  297. // Nth page of results.
  298. first_new = endpoint_data.data.length;
  299. so_far = first_new + json.data.length;
  300. json.data = endpoint_data.data.concat(json.data);
  301. }
  302. endpoint_data = json;
  303. total = json.total_count;
  304.  
  305. // Call the 'progress' callback.
  306. if (typeof progress_callback === 'function')
  307. progress_callback(endpoint, first_new, so_far, total);
  308. progress_data.value = so_far;
  309. progress_data.max = total;
  310. if (options.disable_progress_dialog !== true) wkof.Progress.update(progress_data);
  311.  
  312. // If there are more pages, fetch the next one.
  313. if (json.pages.next_url !== null) {
  314. retry_cnt = 0;
  315. url = json.pages.next_url;
  316. fetch();
  317. return;
  318. }
  319.  
  320. // This was the last page. Return the data.
  321. fetch_promise.resolve(endpoint_data);
  322.  
  323. } else {
  324. // Single-page result. Report single-page progress, and return data.
  325. if (typeof progress_callback === 'function')
  326. progress_callback(endpoint, 0, 1, 1);
  327. progress_data.value = 1;
  328. progress_data.max = 1;
  329. if (options.disable_progress_dialog !== true) wkof.Progress.update(progress_data);
  330. fetch_promise.resolve(json);
  331. }
  332. }
  333.  
  334. //============
  335. function bad_apikey(){
  336. // If we are using an override key, abort and return error.
  337. if (using_apikey_override) {
  338. fetch_promise.reject('Wanikani doesn\'t recognize the apiv2_key_override key ("'+wkof.Apiv2.key+'")');
  339. return;
  340. }
  341.  
  342. // If bad key received too many times, abort and return error.
  343. bad_key_cnt++;
  344. if (bad_key_cnt > 1) {
  345. fetch_promise.reject('Aborting fetch: Bad key reported multiple times!');
  346. return;
  347. }
  348.  
  349. // We received a bad key. Report on the console, then try fetching the key (and data) again.
  350. console.log('Seems we have a bad API key. Erasing stored info.');
  351. localStorage.removeItem('apiv2_key');
  352. wkof.Apiv2.key = undefined;
  353. get_apikey()
  354. .then(populate_user_cache)
  355. .then(setup_and_fetch);
  356. }
  357. }
  358.  
  359.  
  360. let min_update_interval = 60;
  361. let ep_cache = {};
  362.  
  363. //------------------------------
  364. // Get endpoint data from cache with updates from API.
  365. //------------------------------
  366. function get_endpoint(ep_name, options) {
  367. if (!options) options = {};
  368.  
  369. // We cache data for 'min_update_interval' seconds.
  370. // If within that interval, we return the cached data.
  371. // User can override cache via "options.force_update = true"
  372. let ep_info = ep_cache[ep_name];
  373. if (ep_info) {
  374. // If still awaiting prior fetch return pending promise.
  375. // Also, not force_update, return non-expired cache (i.e. resolved promise)
  376. if (options.force_update !== true || ep_info.timer === undefined)
  377. return ep_info.promise;
  378. // User is requesting force_update, and we have unexpired cache.
  379. // Clear the expiration timer since we will re-fetch anyway.
  380. clearTimeout(ep_info.timer);
  381. }
  382.  
  383. // Create a promise to fetch data. The resolved promise will also serve as cache.
  384. let get_promise = promise();
  385. ep_cache[ep_name] = {promise: get_promise};
  386.  
  387. // Make sure the requested endpoint is valid.
  388. let merged_data;
  389.  
  390. // Perform the fetch, and process the data.
  391. wkof.file_cache.load('Apiv2.'+ep_name)
  392. .then(fetch, fetch);
  393. return get_promise;
  394.  
  395. //============
  396. function fetch(cache_data) {
  397. if (typeof cache_data === 'string') cache_data = {last_update:null};
  398. merged_data = cache_data;
  399. let fetch_options = Object.assign({}, options);
  400. fetch_options.last_update = cache_data.last_update;
  401. fetch_endpoint(ep_name, fetch_options)
  402. .then(process_api_data, handle_error);
  403. }
  404.  
  405. //============
  406. function process_api_data(fetched_data) {
  407. // Mark the data with the last_update timestamp reported by the server.
  408. if (fetched_data.data_updated_at !== null) merged_data.last_update = fetched_data.data_updated_at;
  409.  
  410. // Process data according to whether it is paginated or not.
  411. if (fetched_data.object === 'collection') {
  412. if (merged_data.data === undefined) merged_data.data = {};
  413. for (let idx = 0; idx < fetched_data.data.length; idx++) {
  414. let item = fetched_data.data[idx];
  415. merged_data.data[item.id] = item;
  416. }
  417. } else {
  418. merged_data.data = fetched_data.data;
  419. }
  420.  
  421. // If it's the 'user' endpoint, we insert the apikey before caching.
  422. if (ep_name === 'user') merged_data.data.apikey = wkof.Apiv2.key;
  423.  
  424. // Save data to cache and finish up.
  425. wkof.file_cache.save('Apiv2.'+ep_name, merged_data)
  426. .then(finish);
  427. }
  428.  
  429. //============
  430. function finish() {
  431. // Return the data, then set up a cache expiration timer.
  432. get_promise.resolve(merged_data.data);
  433. ep_cache[ep_name].timer = setTimeout(expire_cache, min_update_interval*1000);
  434. }
  435.  
  436. //============
  437. function expire_cache() {
  438. // Delete the data from cache.
  439. delete ep_cache[ep_name];
  440. }
  441.  
  442. //============
  443. function handle_error(error) {
  444. if (typeof error === 'string')
  445. get_promise.reject(error);
  446. if (error.status >= 300 && error.status <= 399)
  447. finish();
  448. else
  449. get_promise.reject('Error '+error.status+' fetching "'+error.url+'"');
  450. }
  451. }
  452.  
  453. //########################################################################
  454. //------------------------------
  455. // Make sure user cache matches the current (or override) user.
  456. //------------------------------
  457. function validate_user_cache() {
  458. let user = get_username();
  459. if (!user) {
  460. // Username unavailable if not logged in, or if on Lessons or Reviews pages.
  461. // If not logged in, stop running the framework.
  462. if (location.pathname.match(/^(\/|\/login)$/) !== null)
  463. return Promise.reject('Couldn\'t extract username from user menu! Not logged in?');
  464. skip_username_check = true;
  465. }
  466.  
  467. let apikey = localStorage.getItem('apiv2_key_override');
  468. if (apikey !== null) {
  469. // It looks like we're trying to override the apikey (e.g. for debug)
  470. using_apikey_override = true;
  471. if (!is_valid_apikey_format(apikey)) {
  472. return Promise.reject('Invalid api2_key_override in localStorage!');
  473. }
  474. console.log('Using apiv2_key_override key ('+apikey+')');
  475. } else {
  476. // Use regular apikey (versus override apikey)
  477. apikey = localStorage.getItem('apiv2_key');
  478. if (!is_valid_apikey_format(apikey)) apikey = undefined;
  479. }
  480.  
  481. wkof.Apiv2.key = apikey;
  482.  
  483. // Make sure cache is still valid
  484. return wkof.file_cache.load('Apiv2.user')
  485. .then(process_user_info)
  486. .catch(retry);
  487.  
  488. //============
  489. function process_user_info(user_info) {
  490. // If cache matches, we're done.
  491. if (user_info.data.apikey === wkof.Apiv2.key) {
  492. // We don't check username when using override key.
  493. if (using_apikey_override || skip_username_check || (user_info.data.username === user)) {
  494. wkof.Apiv2.user = user_info.data.username;
  495. return populate_user_cache();
  496. }
  497. }
  498. // Cache doesn't match.
  499. if (!using_apikey_override) {
  500. // Fetch the key from the accounts page.
  501. wkof.Apiv2.key = undefined;
  502. throw 'fetch key';
  503. } else {
  504. // We're using override. No need to fetch key, just populate cache.
  505. return clear_cache().then(populate_user_cache);
  506. }
  507. }
  508.  
  509. //============
  510. function retry() {
  511. // Either empty cache, or user mismatch. Fetch key, then populate cache.
  512. return get_apikey().then(clear_cache).then(populate_user_cache);
  513. }
  514. }
  515.  
  516. //------------------------------
  517. // Populate the user info into cache.
  518. //------------------------------
  519. function populate_user_cache() {
  520. return fetch_endpoint('user')
  521. .then(function(user_info){
  522. // Store the apikey in the cache.
  523. user_info.data.apikey = wkof.Apiv2.key;
  524. wkof.Apiv2.user = user_info.data.username;
  525. wkof.user = user_info.data
  526. return wkof.file_cache.save('Apiv2.user', user_info);
  527. });
  528. }
  529.  
  530. //------------------------------
  531. // Do initialization once document is loaded.
  532. //------------------------------
  533. function notify_ready() {
  534. // Notify listeners that we are ready.
  535. // Delay guarantees include() callbacks are called before ready() callbacks.
  536. setTimeout(function(){wkof.set_state('wkof.Apiv2', 'ready');},0);
  537. }
  538.  
  539. //------------------------------
  540. // Do initialization once document is loaded.
  541. //------------------------------
  542. wkof.include('Progress');
  543. wkof.ready('document,Progress').then(startup);
  544. function startup() {
  545. validate_user_cache()
  546. .then(notify_ready);
  547. }
  548.  
  549. })(window);