Greasy Fork镜像 支持简体中文。

Wanikani Open Framework - Apiv2 module

Apiv2 module for Wanikani Open Framework

目前為 2019-05-23 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/38581/700865/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.10
  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(){var a,b,c=new Promise(function(d,e){a=d;b=e;});c.resolve=a;c.reject=b;return c;}
  26.  
  27. var using_apikey_override = false;
  28. var 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. var 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 $('.user-summary__username').text();
  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. var clear_promises = [];
  74. var dir = wkof.file_cache.dir;
  75. for (var 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('https://www.wanikani.com/settings/personal_access_tokens')
  112. .then(parse_page);
  113.  
  114. function parse_page(html){
  115. var page = $(html);
  116. var apikey = page.find('.personal-access-token-token > code').eq(0).text();
  117. if (!wkof.Apiv2.is_valid_apikey_format(apikey)) {
  118. var 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('https://www.wanikani.com/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. var page = $(html);
  155. var form = page.find('form.new_personal_access_token');
  156. var hidden_inputs = form.find('input[type="hidden"]');
  157. var checkboxes = form.find('input[type="checkbox"]');
  158. var submit_url = form.attr('action');
  159. var data = {};
  160.  
  161. hidden_inputs.each(parse_hidden_inputs);
  162. checkboxes.each(parse_checkboxes);
  163. data['personal_access_token[description]'] = 'Open Framework (read-only)';
  164.  
  165. return $.post(submit_url, data);
  166.  
  167. function parse_hidden_inputs(idx, elem) {
  168. data[elem.attributes.name.value] = elem.attributes.value.value;
  169. }
  170.  
  171. function parse_checkboxes(idx, elem) {
  172. data[elem.attributes.name.value] = '0';
  173. }
  174. }
  175. }
  176.  
  177. //------------------------------
  178. // Fetch a URL asynchronously, and pass the result as resolved Promise data.
  179. //------------------------------
  180. function fetch_endpoint(endpoint, options) {
  181. var retry_cnt, endpoint_data, url, headers;
  182. var progress_data = {name:'wk_api_'+endpoint, label:'Wanikani '+endpoint, value:0, max:100};
  183. var bad_key_cnt = 0;
  184.  
  185. // Parse options.
  186. if (!options) options = {};
  187. var filters = options.filters;
  188. if (!filters) filters = {};
  189. var progress_callback = options.progress_callback;
  190.  
  191. // Get timestamp of last fetch from options (if specified)
  192. var last_update = options.last_update;
  193.  
  194. // If no prior fetch... (i.e. no valid last_update)
  195. if (typeof last_update !== 'string' && !(last_update instanceof Date)) {
  196. // If updated_after is present, use it. Otherwise, default to ancient date.
  197. if (filters.updated_after === undefined)
  198. last_update = '1999-01-01T01:00:00.000000Z';
  199. else
  200. last_update = filters.updated_after;
  201. }
  202. // If last_update is a Date object, convert it to ISO string.
  203. // If it's a string, but not an ISO string, try converting to an ISO string.
  204. if (last_update instanceof Date)
  205. last_update = last_update.toISOString().replace(/Z$/,'000Z');
  206. else if (last_update.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/) === null)
  207. last_update = new Date(last_update).toISOString().replace(/Z$/,'000Z');
  208.  
  209. // Set up URL and headers
  210. url = "https://api.wanikani.com/v2/" + endpoint;
  211.  
  212. // Add user-specified data filters to the URL
  213. filters.updated_after = last_update;
  214. var arr = [];
  215. for (var name in filters) {
  216. var value = filters[name];
  217. if (Array.isArray(value)) value = value.join(',');
  218. arr.push(name+'='+value);
  219. }
  220. url += '?'+arr.join('&');
  221.  
  222. // Get API key and fetch the data.
  223. var fetch_promise = promise();
  224. get_apikey()
  225. .then(setup_and_fetch);
  226.  
  227. return fetch_promise;
  228.  
  229. //============
  230. function setup_and_fetch() {
  231. wkof.Progress.update(progress_data);
  232. headers = {
  233. // 'Wanikani-Revision': '20170710', // Placeholder?
  234. 'Authorization': 'Bearer '+wkof.Apiv2.key,
  235. };
  236. headers['If-Modified-Since'] = new Date(last_update).toUTCString(last_update);
  237.  
  238. retry_cnt = 0;
  239. fetch();
  240. }
  241.  
  242. //============
  243. function fetch() {
  244. retry_cnt++;
  245. var request = new XMLHttpRequest();
  246. request.onreadystatechange = received;
  247. request.open('GET', url, true);
  248. for (var key in headers)
  249. request.setRequestHeader(key, headers[key]);
  250. request.send();
  251. }
  252.  
  253. //============
  254. function received(event) {
  255. // ReadyState of 4 means transaction is complete.
  256. if (this.readyState !== 4) return;
  257.  
  258. // Check for rate-limit error. Delay and retry if necessary.
  259. if (this.status === 429 && retry_cnt < 40) {
  260. var delay = Math.min((retry_cnt * 250), 2000);
  261. setTimeout(fetch, delay);
  262. return;
  263. }
  264.  
  265. // Check for bad API key.
  266. if (this.status === 401) return bad_apikey();
  267.  
  268. // Check of 'no updates'.
  269. if (this.status >= 300) {
  270. if (typeof progress_callback === 'function')
  271. progress_callback(endpoint, 0, 1, 1);
  272. progress_data.value = 1;
  273. progress_data.max = 1;
  274. wkof.Progress.update(progress_data);
  275. return fetch_promise.reject({status:this.status, url:url});
  276. }
  277.  
  278. // Process the response data.
  279. var json = JSON.parse(event.target.response);
  280.  
  281. // Data may be a single object, or collection of objects.
  282. // Collections are paginated, so we may need more fetches.
  283. if (json.object === 'collection') {
  284. // It's a multi-page endpoint.
  285. var first_new, so_far, total;
  286. if (endpoint_data === undefined) {
  287. // First page of results.
  288. first_new = 0;
  289. so_far = json.data.length;
  290. } else {
  291. // Nth page of results.
  292. first_new = endpoint_data.data.length;
  293. so_far = first_new + json.data.length;
  294. json.data = endpoint_data.data.concat(json.data);
  295. }
  296. endpoint_data = json;
  297. total = json.total_count;
  298.  
  299. // Call the 'progress' callback.
  300. if (typeof progress_callback === 'function')
  301. progress_callback(endpoint, first_new, so_far, total);
  302. progress_data.value = so_far;
  303. progress_data.max = total;
  304. wkof.Progress.update(progress_data);
  305.  
  306. // If there are more pages, fetch the next one.
  307. if (json.pages.next_url !== null) {
  308. retry_cnt = 0;
  309. url = json.pages.next_url;
  310. fetch();
  311. return;
  312. }
  313.  
  314. // This was the last page. Return the data.
  315. fetch_promise.resolve(endpoint_data);
  316.  
  317. } else {
  318. // Single-page result. Report single-page progress, and return data.
  319. if (typeof progress_callback === 'function')
  320. progress_callback(endpoint, 0, 1, 1);
  321. progress_data.value = 1;
  322. progress_data.max = 1;
  323. wkof.Progress.update(progress_data);
  324. fetch_promise.resolve(json);
  325. }
  326. }
  327.  
  328. //============
  329. function bad_apikey(){
  330. // If we are using an override key, abort and return error.
  331. if (using_apikey_override) {
  332. fetch_promise.reject('Wanikani doesn\'t recognize the apiv2_key_override key ("'+wkof.Apiv2.key+'")');
  333. return;
  334. }
  335.  
  336. // If bad key received too many times, abort and return error.
  337. bad_key_cnt++;
  338. if (bad_key_cnt > 1) {
  339. fetch_promise.reject('Aborting fetch: Bad key reported multiple times!');
  340. return;
  341. }
  342.  
  343. // We received a bad key. Report on the console, then try fetching the key (and data) again.
  344. console.log('Seems we have a bad API key. Erasing stored info.');
  345. localStorage.removeItem('apiv2_key');
  346. wkof.Apiv2.key = undefined;
  347. get_apikey()
  348. .then(populate_user_cache)
  349. .then(setup_and_fetch);
  350. }
  351. }
  352.  
  353.  
  354. var min_update_interval = 60;
  355. var ep_cache = {};
  356.  
  357. //------------------------------
  358. // Get endpoint data from cache with updates from API.
  359. //------------------------------
  360. function get_endpoint(ep_name, options) {
  361. if (!options) options = {};
  362.  
  363. // We cache data for 'min_update_interval' seconds.
  364. // If within that interval, we return the cached data.
  365. // User can override cache via "options.force_update = true"
  366. var ep_info = ep_cache[ep_name];
  367. if (ep_info) {
  368. // If still awaiting prior fetch return pending promise.
  369. // Also, not force_update, return non-expired cache (i.e. resolved promise)
  370. if (options.force_update !== true || ep_info.timer === undefined)
  371. return ep_info.promise;
  372. // User is requesting force_update, and we have unexpired cache.
  373. // Clear the expiration timer since we will re-fetch anyway.
  374. clearTimeout(ep_info.timer);
  375. }
  376.  
  377. // Create a promise to fetch data. The resolved promise will also serve as cache.
  378. var get_promise = promise();
  379. ep_cache[ep_name] = {promise: get_promise};
  380.  
  381. // Make sure the requested endpoint is valid.
  382. var merged_data;
  383.  
  384. // Perform the fetch, and process the data.
  385. wkof.file_cache.load('Apiv2.'+ep_name)
  386. .then(fetch, fetch);
  387. return get_promise;
  388.  
  389. //============
  390. function fetch(cache_data) {
  391. if (typeof cache_data === 'string') cache_data = {last_update:null};
  392. merged_data = cache_data;
  393. var fetch_options = Object.assign({}, options);
  394. fetch_options.last_update = cache_data.last_update;
  395. fetch_endpoint(ep_name, fetch_options)
  396. .then(process_api_data, handle_error);
  397. }
  398.  
  399. //============
  400. function process_api_data(fetched_data) {
  401. // Mark the data with the last_update timestamp reported by the server.
  402. if (fetched_data.data_updated_at !== null) merged_data.last_update = fetched_data.data_updated_at;
  403.  
  404. // Process data according to whether it is paginated or not.
  405. if (fetched_data.object === 'collection') {
  406. if (merged_data.data === undefined) merged_data.data = {};
  407. for (var idx = 0; idx < fetched_data.data.length; idx++) {
  408. var item = fetched_data.data[idx];
  409. merged_data.data[item.id] = item;
  410. }
  411. } else {
  412. merged_data.data = fetched_data.data;
  413. }
  414.  
  415. // If it's the 'user' endpoint, we insert the apikey before caching.
  416. if (ep_name === 'user') merged_data.data.apikey = wkof.Apiv2.key;
  417.  
  418. // Save data to cache and finish up.
  419. wkof.file_cache.save('Apiv2.'+ep_name, merged_data)
  420. .then(finish);
  421. }
  422.  
  423. //============
  424. function finish() {
  425. // Return the data, then set up a cache expiration timer.
  426. get_promise.resolve(merged_data.data);
  427. ep_cache[ep_name].timer = setTimeout(expire_cache, min_update_interval*1000);
  428. }
  429.  
  430. //============
  431. function expire_cache() {
  432. // Delete the data from cache.
  433. delete ep_cache[ep_name];
  434. }
  435.  
  436. //============
  437. function handle_error(error) {
  438. if (typeof error === 'string')
  439. get_promise.reject(error);
  440. if (error.status >= 300 && error.status <= 399)
  441. finish();
  442. else
  443. get_promise.reject('Error '+error.status+' fetching "'+error.url+'"');
  444. }
  445. }
  446.  
  447. //########################################################################
  448. //------------------------------
  449. // Make sure user cache matches the current (or override) user.
  450. //------------------------------
  451. function validate_user_cache() {
  452. var user = get_username();
  453. if (!user) {
  454. // Username unavailable if not logged in, or if on Lessons or Reviews pages.
  455. // If not logged in, stop running the framework.
  456. if (location.pathname.match(/^(\/|\/login)$/) !== null)
  457. return Promise.reject('Couldn\'t extract username from user menu! Not logged in?');
  458. skip_username_check = true;
  459. }
  460.  
  461. var apikey = localStorage.getItem('apiv2_key_override');
  462. if (apikey !== null) {
  463. // It looks like we're trying to override the apikey (e.g. for debug)
  464. using_apikey_override = true;
  465. if (!is_valid_apikey_format(apikey)) {
  466. return Promise.reject('Invalid api2_key_override in localStorage!');
  467. }
  468. console.log('Using apiv2_key_override key ('+apikey+')');
  469. } else {
  470. // Use regular apikey (versus override apikey)
  471. apikey = localStorage.getItem('apiv2_key');
  472. if (!is_valid_apikey_format(apikey)) apikey = undefined;
  473. }
  474.  
  475. wkof.Apiv2.key = apikey;
  476.  
  477. // Make sure cache is still valid
  478. return wkof.file_cache.load('Apiv2.user')
  479. .then(process_user_info)
  480. .catch(retry);
  481.  
  482. //============
  483. function process_user_info(user_info) {
  484. // If cache matches, we're done.
  485. if (user_info.data.apikey === wkof.Apiv2.key) {
  486. // We don't check username when using override key.
  487. if (using_apikey_override || skip_username_check || (user_info.data.username === user)) {
  488. wkof.Apiv2.user = user_info.data.username;
  489. return populate_user_cache();
  490. }
  491. }
  492. // Cache doesn't match.
  493. if (!using_apikey_override) {
  494. // Fetch the key from the accounts page.
  495. wkof.Apiv2.key = undefined;
  496. throw 'fetch key';
  497. } else {
  498. // We're using override. No need to fetch key, just populate cache.
  499. return clear_cache().then(populate_user_cache);
  500. }
  501. }
  502.  
  503. //============
  504. function retry() {
  505. // Either empty cache, or user mismatch. Fetch key, then populate cache.
  506. return get_apikey().then(clear_cache).then(populate_user_cache);
  507. }
  508. }
  509.  
  510. //------------------------------
  511. // Populate the user info into cache.
  512. //------------------------------
  513. function populate_user_cache() {
  514. return fetch_endpoint('user')
  515. .then(function(user_info){
  516. // Store the apikey in the cache.
  517. user_info.data.apikey = wkof.Apiv2.key;
  518. wkof.Apiv2.user = user_info.data.username;
  519. wkof.user = user_info.data
  520. return wkof.file_cache.save('Apiv2.user', user_info);
  521. });
  522. }
  523.  
  524. //------------------------------
  525. // Do initialization once document is loaded.
  526. //------------------------------
  527. function notify_ready() {
  528. // Notify listeners that we are ready.
  529. // Delay guarantees include() callbacks are called before ready() callbacks.
  530. setTimeout(function(){wkof.set_state('wkof.Apiv2', 'ready');},0);
  531. }
  532.  
  533. //------------------------------
  534. // Do initialization once document is loaded.
  535. //------------------------------
  536. wkof.include('Progress');
  537. wkof.ready('document,Progress').then(startup);
  538. function startup() {
  539. validate_user_cache()
  540. .then(notify_ready);
  541. }
  542.  
  543. })(window);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址