YouTube RatingBars (Like/Dislike Rating)

在与动画的链接中显示表示被“高评价”的比率的栏。

  1. // ==UserScript==
  2. // @name YouTube RatingBars (Like/Dislike Rating)
  3. // @name:ja YouTube RatingBars (Like/Dislike Rating)
  4. // @name:zh-CN YouTube RatingBars (Like/Dislike Rating)
  5. // @namespace knoa.jp
  6. // @description It shows rating bars which represents Like/Dislike rating ratio.
  7. // @description:ja 動画へのリンクに「高く評価」された比率を示すバーを表示します。
  8. // @description:zh-CN 在与动画的链接中显示表示被“高评价”的比率的栏。
  9. // @include https://www.youtube.com/*
  10. // @exclude https://www.youtube.com/live_chat*
  11. // @exclude https://www.youtube.com/live_chat_replay*
  12. // @include https://console.cloud.google.com/*
  13. // @version 4.0.12
  14. // @grant none
  15. // @noframes
  16. // ==/UserScript==
  17.  
  18. (function(){
  19. const SCRIPTID = 'YouTubeRatingBars';
  20. const SCRIPTNAME = 'YouTube RatingBars';
  21. const DEBUG = false;/*
  22. [update]
  23. Minor fix for YouTube's update.
  24.  
  25. [bug]
  26.  
  27. [to do]
  28. 定期: 自動取得機能してるか
  29. 自分のアイコン内のメニューにあることを示唆するために ratingbars パネルを閉じる際は右上に向けて隠す
  30. スクリプトの説明で設定ボタンの場所をわかりやすく説明とかスクショとか
  31.  
  32. [possible]
  33. title属性に実数を入れる手もある?
  34.  
  35. [to research]
  36. スクロールとリサイズだけトリガにして毎秒の処理を軽減する手もあるか
  37. 全部にバーを付与した上で中身の幅だけを更新する手も
  38. URL変わるたびに中身を一度0幅にすれば更新時のアニメーションも不自然ではないか
  39.  
  40. [memo]
  41. 要素はとことん再利用されるので注意。
  42.  
  43. API Document:
  44. https://developers.google.com/youtube/v3/docs/videos/list
  45. API Quotas:
  46. https://console.developers.google.com/apis/api/youtube.googleapis.com/quotas?project=youtube-ratingbars
  47.  
  48. 先例があった
  49. https://github.com/elliotwaite/thumbnail-rating-bar-for-youtube/issues/17
  50. https://github.com/elliotwaite/thumbnail-rating-bar-for-youtube
  51. 各自にAPIキーを取得してもらっているようだ。他の拡張は全滅の様相。
  52.  
  53. icon:
  54. https://www.onlinewebfonts.com/icon/11481
  55. */
  56. if(window === top && console.time) console.time(SCRIPTID);
  57. const SECOND = 1000, MINUTE = 60*SECOND, HOUR = 60*MINUTE, DAY = 24*HOUR, WEEK = 7*DAY, MONTH = 30*DAY, YEAR = 365*DAY;
  58. const INTERVAL = 1*SECOND;/*for core.observeItems*/
  59. const HEIGHT = 2;/*bar height(px)*/
  60. const THINHEIGHT = 1;/*bar height(px) for videos with few ratings*/
  61. const RELIABLECOUNT = 10;/*ratings less than this number has less reliability*/
  62. const STABLECOUNT = 100;/*ratings more than this number has stable reliability*/
  63. const CACHELIMIT = 30*DAY;/*cache limit for stable videos*/
  64. const LIKECOLOR = 'rgb(6, 95, 212)';
  65. const DISLIKECOLOR = 'rgb(204, 204, 204)';
  66. const FLAG = SCRIPTID.toLowerCase();/*dataset name to add for videos to append a RatingBar*/
  67. const MAXRESULTS = 48;/* API limits 50 videos per request */
  68. const API = `https://www.googleapis.com/youtube/v3/videos?id={ids}&part=statistics&fields=items(id,statistics)&maxResults=${MAXRESULTS}&key={apiKey}`;
  69. const VIDEOID = /\?v=([^&]+)/;/*video id in URL parameters*/
  70. const RETRY = 10;
  71. const sites = {
  72. youtube: {
  73. url: 'https://www.youtube.com/',
  74. targets: {
  75. avatarBtn: () => $('#avatar-btn') || $('ytd-topbar-menu-button-renderer:last-of-type button#button'),
  76. },
  77. views: {
  78. home: {
  79. url: /^https:\/\/www\.youtube\.com\/([?#].+)?$/,
  80. videos: () => [...$$('ytd-rich-item-renderer'), ...$$('ytd-rich-grid-video-renderer'), ...$$('ytd-grid-video-renderer'), ...$$('ytd-video-renderer')],
  81. anchor: (item) => item.querySelector('a'),
  82. insertAfter: (item) => item.querySelector('#metadata-line'),
  83. },
  84. feed: {
  85. url: /^https:\/\/www\.youtube\.com\/feed\//,
  86. videos: () => [...$$('ytd-grid-video-renderer'), ...$$('ytd-video-renderer')],
  87. anchor: (item) => item.querySelector('a'),
  88. insertAfter: (item) => item.querySelector('#metadata-line'),
  89. },
  90. results: {
  91. url: /^https:\/\/www\.youtube\.com\/results\?/,
  92. videos: () => $$('ytd-video-renderer'),
  93. anchor: (item) => item.querySelector('a'),
  94. insertAfter: (item) => item.querySelector('#metadata-line'),
  95. },
  96. watch: {
  97. url: /^https:\/\/www\.youtube\.com\/watch\?/,
  98. videos: () => $$('ytd-compact-video-renderer'),
  99. anchor: (item) => item.querySelector('a'),
  100. insertAfter: (item) => item.querySelector('#metadata-line'),
  101. },
  102. channel: {
  103. url: /^https:\/\/www\.youtube\.com\/(channel|c|user)\//,
  104. videos: () => [...$$('ytd-grid-video-renderer'), ...$$('ytd-video-renderer')],
  105. anchor: (item) => item.querySelector('a'),
  106. insertAfter: (item) => item.querySelector('#metadata-line'),
  107. },
  108. default: {
  109. url: /^https:\/\/www\.youtube\.com\//,
  110. videos: () => [...$$('ytd-grid-video-renderer'), ...$$('ytd-video-renderer')],
  111. anchor: (item) => item.querySelector('a'),
  112. insertAfter: (item) => item.querySelector('#metadata-line'),
  113. },
  114. },
  115. get: {
  116. api: (ids) => new Request(API.replace('{apiKey}', configs.apiKey).replace('{ids}', ids.join())),
  117. bar: (item) => item.querySelector('#container.ytd-sentiment-bar-renderer'),
  118. accountMenuItem: () => $('ytd-popup-container a[href="/account"]', (a) => a.parentNode),
  119. },
  120. is: {
  121. popupped: () => ($('ytd-popup-container > iron-dropdown:not([aria-hidden="true"])') === null),
  122. },
  123. },
  124. google: {
  125. views: {
  126. projectcreate: {/* 1-1. Create a new project */
  127. url: 'https://console.cloud.google.com/projectcreate',
  128. targets: {
  129. anchor: () => $('body'),
  130. projectName: () => $('proj-name-id-input input'),
  131. createButton: () => $('.projtest-create-form-submit'),
  132. },
  133. styles: {
  134. 'width': '400px',
  135. 'top': '50%',
  136. 'left': '60%',
  137. 'transform': 'translate(-50%, -50%)',
  138. },
  139. },
  140. dashboard: {/* 1-2. Complete the creation */
  141. url: 'https://console.cloud.google.com/home/dashboard',
  142. targets: {
  143. anchor: () => $('body'),
  144. },
  145. styles: {
  146. 'width': '400px',
  147. 'top': '50%',
  148. 'left': '50%',
  149. 'transform': 'translate(-50%, -50%)',
  150. },
  151. get: {
  152. createdProjects: () => $$('[icon="status-success"]', (icon) => icon.parentNode),
  153. },
  154. },
  155. library: {/* 2-1. Enable the API */
  156. url: 'https://console.cloud.google.com/apis/library/youtube.googleapis.com',
  157. targets: {
  158. anchor: () => $('body'),
  159. },
  160. styles: {
  161. 'width': '400px',
  162. 'top': '50%',
  163. 'left': '60%',
  164. 'transform': 'translate(-50%, -50%)',
  165. },
  166. },
  167. api: {/* 2-2. After the enabling */
  168. url: 'https://console.cloud.google.com/apis/api/',
  169. redirect: 'https://console.cloud.google.com/apis/credentials',
  170. },
  171. credentials: {/* 3. Create an API Key */
  172. url: 'https://console.cloud.google.com/apis/credentials',
  173. targets: {
  174. anchor: () => $('body'),
  175. createButton: () => $('button#action-bar-create-button'),
  176. },
  177. styles: {
  178. 'width': '400px',
  179. 'top': '50%',
  180. 'left': '50%',
  181. 'transform': 'translate(-50%, -50%)',
  182. },
  183. get: {/* MANY WEAK SELECTORS CAUTION */
  184. apiKeyMenuLabel: () => $('cfc-menu-item[label*="API"]'),
  185. apiKeyInput: () => $('span[label*="API"] input'),
  186. restrictKeyButton: () => $('.mat-dialog-actions button[tabindex="0"]'),/* SO WEAK */
  187. apiRestrictionRadioButtonLabel: () => $('services-key-api-restrictions mat-radio-button:nth-child(2) label'),
  188. apiRestrictionSelect: () => $('services-key-api-restrictions [role="combobox"]'),
  189. youtubeDataApiOption: () => Array.from($$('mat-option')).find(o => o.textContent.includes('YouTube Data API v3')),
  190. saveButton: () => $('form button[type="submit"]'),
  191. createdKey: () => $('ace-icon[icon="status-success"] + a[href^="/apis/credentials/key/"]'),
  192. },
  193. },
  194. quotas: {/* Check your quota */
  195. url: 'https://console.cloud.google.com/apis/api/youtube.googleapis.com/quotas',
  196. },
  197. error: {
  198. url: undefined,
  199. targets: {
  200. anchor: () => $('body'),
  201. },
  202. styles: {
  203. 'width': '400px',
  204. 'top': '50%',
  205. 'left': '50%',
  206. 'transform': 'translate(-50%, -50%)',
  207. },
  208. },
  209. },
  210. },
  211. };
  212. class Configs{
  213. constructor(configs){
  214. Configs.PROPERTIES = {
  215. apiKey: {type: 'string', default: ''},
  216. };
  217. this.data = this.read(configs || {});
  218. return new Proxy(this, {
  219. get: function(configs, field){
  220. if(field in configs) return configs[field];
  221. }
  222. });
  223. }
  224. read(configs){
  225. let newConfigs = {};
  226. Object.keys(Configs.PROPERTIES).forEach(key => {
  227. if(configs[key] === undefined) return newConfigs[key] = Configs.PROPERTIES[key].default;
  228. switch(Configs.PROPERTIES[key].type){
  229. case('bool'): return newConfigs[key] = (configs[key]) ? 1 : 0;
  230. case('int'): return newConfigs[key] = parseInt(configs[key]);
  231. case('float'): return newConfigs[key] = parseFloat(configs[key]);
  232. default: return newConfigs[key] = configs[key];
  233. }
  234. });
  235. return newConfigs;
  236. }
  237. toJSON(){
  238. let json = {};
  239. Object.keys(this.data).forEach(key => {
  240. json[key] = this.data[key];
  241. });
  242. return json;
  243. }
  244. set apiKey(apiKey){this.data.apiKey = apiKey;}
  245. get apiKey(){return this.data.apiKey;}
  246. }
  247. let elements = {}, timers = {}, site, view, panels, configs;
  248. let cache = {};/* each of identical video elements has a reference to its video ID. */
  249. /* {'ID': {commentCount: "123", dislikeCount: "12", favoriteCount: "0", likeCount: "1234", viewCount: "12345", timestamp: 1234567890}} */
  250. let cached = 0;/*cache usage*/
  251. let videoIdTable = {};/* each of identical video elements has a reference to its video ID. */
  252. /* {'ID': [element, element, element]} */
  253. let queue = [];/* each item of the queue has ids to get data from API at once */
  254. const core = {
  255. initialize: function(){
  256. elements.html = document.documentElement;
  257. elements.html.classList.add(SCRIPTID);
  258. text.setup(texts, elements.html.lang);
  259. switch(true){
  260. case(/^https:\/\/www\.youtube\.com\//.test(location.href)):
  261. site = sites.youtube;
  262. core.readyForYouTube();
  263. core.addStyle('style');
  264. core.addStyle('panelStyle');
  265. break;
  266. case(/^https:\/\/console\.cloud\.google\.com\//.test(location.href)):
  267. site = sites.google;
  268. core.readyForGoogle();
  269. core.addStyle('guideStyle');
  270. break;
  271. default:
  272. log('Doesn\'t match any sites:', location.href)
  273. break;
  274. }
  275. },
  276. readyForYouTube: function(){
  277. if(core.commingBack()) return;
  278. if(document.hidden) return setTimeout(core.readyForYouTube, 1000);
  279. core.getTargets(site.targets, RETRY).then(() => {
  280. log("I'm ready for YouTube.");
  281. core.configs.prepare();
  282. if(configs.apiKey !== ''){
  283. core.cacheReady();
  284. core.observeItems();
  285. core.export();
  286. }else{
  287. log('No API key.');
  288. }
  289. }).catch(e => {
  290. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  291. });
  292. },
  293. commingBack: function(){
  294. let commingBack = Storage.read('commingBack');
  295. if(commingBack){
  296. Storage.remove('commingBack');
  297. location.assign(commingBack + location.hash);
  298. return true;
  299. }
  300. },
  301. cacheReady: function(){
  302. let now = Date.now();
  303. cache = Storage.read('cache') || {};
  304. Object.keys(cache).forEach(id => {
  305. switch(true){
  306. case(cache[id].timestamp < now - CACHELIMIT):
  307. case(parseInt(cache[id].dislikeCount) + parseInt(cache[id].likeCount) < STABLECOUNT):
  308. return delete cache[id];
  309. }
  310. });
  311. window.addEventListener('unload', function(e){
  312. Storage.save('cache', cache);
  313. });
  314. },
  315. observeItems: function(){
  316. let previousUrl = '';
  317. clearInterval(timers.observeItems);
  318. timers.observeItems = setInterval(function(){
  319. if(document.hidden) return;
  320. /* select the view of the current page */
  321. if(location.href !== previousUrl){
  322. let key = Object.keys(site.views).find(key => site.views[key].url.test(location.href));
  323. view = site.views[key];
  324. previousUrl = location.href;
  325. }
  326. /* get the target videos of the current page */
  327. if(view){
  328. core.getVideos(view);
  329. }
  330. /* get ratings from the API */
  331. if(queue[0] && queue[0].length){
  332. core.getRatings(queue.shift());
  333. }
  334. }, INTERVAL);
  335. },
  336. getVideos: function(view){
  337. let items = view.videos();
  338. if(items.length === 0) return;
  339. /* pushes id to the queue */
  340. const push = function(id){
  341. for(let i = 0; true; i++){
  342. if(queue[i] === undefined) queue[i] = [];
  343. if(queue[i].length < MAXRESULTS){
  344. queue[i].push(id);
  345. break;
  346. }
  347. }
  348. };
  349. /* push ids to the queue */
  350. for(let i = 0, item; item = items[i]; i++){
  351. let a = view.anchor(item);
  352. if(!a || !a.href){
  353. log('Not found: anchor.');
  354. continue;
  355. }
  356. let m = a.href.match(VIDEOID), id = m ? m[1] : null;
  357. if(id === null) continue;
  358. if(item.dataset[FLAG] === id) continue;/*sometimes DOM was re-used for a different video*/
  359. item.dataset[FLAG] = id;/*flag for video found by the script*/
  360. if(!videoIdTable[id]) videoIdTable[id] = [item];
  361. else videoIdTable[id].push(item);
  362. if(cache[id]) core.appendBar(item, cache[id]), cached++;
  363. else push(id);
  364. }
  365. },
  366. getRatings: function(ids){
  367. fetch(site.get.api(ids))
  368. .then(response => response.json())
  369. .then(json => {
  370. log('JSON from API:', json);
  371. let items = json.items;
  372. if(!items || !items.length) return;
  373. for(let i = 0, now = Date.now(), item; item = items[i]; i++){
  374. videoIdTable[item.id] = videoIdTable[item.id].filter(v => v.isConnected);
  375. videoIdTable[item.id].forEach(v => {
  376. core.appendBar(v, item.statistics);
  377. });
  378. cache[item.id] = item.statistics;
  379. cache[item.id].timestamp = now;
  380. }
  381. });
  382. },
  383. appendBar: function(item, statistics){
  384. let s = statistics, likes = parseInt(s.likeCount), dislikes = parseInt(s.dislikeCount);
  385. if(s.likeCount === undefined) return log('Not found: like count.', item);
  386. if(likes === 0 && dislikes === 0) return
  387. let height = (RELIABLECOUNT < likes + dislikes) ? HEIGHT : THINHEIGHT;
  388. let percentage = (likes / (likes + dislikes)) * 100;
  389. let bar = createElement(html.bar(height, percentage));
  390. let insertAfter = view.insertAfter(item);
  391. if(insertAfter === null) return log('Not found: insertAfter.');
  392. if(site.get.bar(item)){/*bar already exists*/
  393. insertAfter.parentNode.replaceChild(bar, insertAfter.nextElementSibling);
  394. }else{
  395. insertAfter.parentNode.insertBefore(bar, insertAfter.nextElementSibling);
  396. }
  397. },
  398. export: function(){
  399. if(DEBUG !== true) return;
  400. window.save = function(){
  401. log(
  402. 'Cache length:', Object.keys(cache).length,
  403. 'videoElements:', Object.keys(videoIdTable).map(key => videoIdTable[key].length).reduce((x, y) => x + y),
  404. 'videoIds:', Object.keys(videoIdTable).length,
  405. 'usage:', cached,
  406. 'saved:', ((cached / Object.keys(videoIdTable).length)*100).toFixed(1) + '%',
  407. );
  408. };
  409. },
  410. configs: {
  411. prepare: function(){
  412. panels = new Panels(document.body.appendChild(createElement(html.panels())));
  413. configs = new Configs(Storage.read('configs') || {});
  414. if(location.hash.includes('#apiKey=')){
  415. configs.apiKey = location.hash.match(/#apiKey=(.+)/)[1];
  416. Storage.save('configs', configs.toJSON());
  417. }
  418. core.configs.createPanel();
  419. core.configs.observePopup();
  420. if(configs.apiKey === '' || location.hash.includes('#apiKey=')) panels.show('configs');
  421. },
  422. observePopup: function(){
  423. let button = elements.avatarBtn;
  424. button.addEventListener('click', function(e){
  425. if(site.is.popupped() === false) return;
  426. let timer = setInterval(function(){
  427. let account = site.get.accountMenuItem();
  428. if(account){
  429. clearInterval(timer);
  430. core.configs.appendConfigButton(account);
  431. }
  432. }, 125);
  433. });
  434. },
  435. appendConfigButton: function(account){
  436. let config = elements.configButton = createElement(html.configButton());
  437. config.addEventListener('click', function(e){
  438. panels.show('configs');
  439. });
  440. account.parentNode.insertBefore(config, account.nextElementSibling);
  441. },
  442. createPanel: function(){
  443. let panel = createElement(html.configPanel()), items = {};
  444. Array.from(panel.querySelectorAll('[name]')).forEach(e => items[e.name] = e);
  445. /* getKeyButton */
  446. let getKeyButton = panel.querySelector(`#${SCRIPTID}-getKeyButton`);
  447. getKeyButton.addEventListener('click', function(e){
  448. if(location.href === site.url) return;
  449. Storage.save('commingBack', location.href.replace(location.hash, ''), Date.now() + 1*HOUR);
  450. });
  451. if(items.apiKey.value === '') getKeyButton.classList.add('active');
  452. items.apiKey.addEventListener('input', function(e){
  453. if(items.apiKey.value === '') getKeyButton.classList.add('active');
  454. else getKeyButton.classList.remove('active');
  455. });
  456. /* cancel */
  457. panel.querySelector('button.cancel').addEventListener('click', function(e){
  458. panels.hide('configs');
  459. core.configs.createPanel();/*clear*/
  460. });
  461. /* save */
  462. const save = panel.querySelector('button.save');
  463. save.addEventListener('click', function(e){
  464. configs = new Configs({
  465. apiKey: items.apiKey.value,
  466. });
  467. Storage.save('configs', configs.toJSON());
  468. panels.hide('configs');
  469. core.observeItems();
  470. });
  471. panels.add('configs', panel);
  472. },
  473. },
  474. readyForGoogle: function(){
  475. /* check the guidance session */
  476. if(location.search.includes(SCRIPTID)) Storage.save('guiding', true, Date.now() + 1*HOUR);
  477. if(Storage.read('guiding') === undefined) return log('Guidance session time out.');
  478. /* choose guidance */
  479. let key = Object.keys(site.views).find(key => location.href.startsWith(site.views[key].url)) || 'error';
  480. view = site.views[key];
  481. /* should be redirected */
  482. if(view.redirect) location.assign(view.redirect);
  483. /* can show guidance */
  484. core.getTargets(view.targets, RETRY).then(() => {
  485. log("I'm ready for Google.");
  486. core.createGuidance(key);
  487. }).catch(e => {
  488. view = site.views.error;
  489. core.createGuidance('error');
  490. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  491. });
  492. },
  493. createGuidance: function(key){
  494. let anchor = elements.anchor, guidance = createElement(html[key](view));
  495. Object.keys(view.styles).forEach(key => guidance.style[key] = view.styles[key]);
  496. core.prepareGuidances[key](guidance);
  497. draggable(guidance);
  498. guidance.querySelectorAll('a').forEach(a => a.addEventListener('click', e => {
  499. location.assign(a.href);/* for avoiding google's silent refresh and properly activating this script */
  500. }));
  501. guidance.classList.add('hidden');
  502. anchor.appendChild(guidance);
  503. setTimeout(() => guidance.classList.remove('hidden'), 1000);
  504. },
  505. prepareGuidances: {
  506. projectcreate: function(guidance){
  507. log('projectcreate');
  508. /* default name */
  509. let projectName = elements.projectName;
  510. let defaultName = guidance.querySelector('.name.default');
  511. defaultName.textContent = projectName.value;
  512. /* auto selection for convenience */
  513. Array.from(guidance.querySelectorAll('.name')).forEach(name => {
  514. name.addEventListener('click', function(e){
  515. window.getSelection().selectAllChildren(name);
  516. });
  517. });
  518. /* create button */
  519. let createButton = elements.createButton;
  520. createButton.addEventListener('click', function(e){
  521. /* it doesn't refresh the page */
  522. Storage.save('projectName', projectName.value);
  523. /* hide the guidance */
  524. guidance.classList.add('hidden');
  525. setTimeout(() => guidance.parentNode.removeChild(guidance), 1000);
  526. /* append body layer */
  527. let layer = createElement(html.bodyLayer());
  528. document.body.appendChild(layer);
  529. /* show new guidance for dashboard */
  530. view = site.views.dashboard;
  531. core.createGuidance('dashboard');
  532. });
  533. /* leave the guidance */
  534. let leave = guidance.querySelector(`a[href="${sites.google.views.projectcreate.url}"]`);
  535. leave.addEventListener('click', function(e){
  536. guidance.parentNode.removeChild(guidance);
  537. Storage.remove('guiding');
  538. });
  539. },
  540. dashboard: function(guidance){
  541. log('dashboard');
  542. let projectName = (Storage.read('projectName') || '').trim();
  543. let seconds = guidance.querySelector('.secondsLeft');
  544. let timer = setInterval(function(){
  545. /* automatically redirect to next step in 60s */
  546. /* even if project was not created in this page, it will be created on next step */
  547. seconds.textContent = parseInt(seconds.textContent) - 1;
  548. if(seconds.textContent === '0') return location.assign(site.views.library.url);
  549. /* also automatically redirect when the project surely created */
  550. let projects = view.get.createdProjects();
  551. if(projects.length === 0) return;
  552. if(Array.from(projects).some(p => p.textContent.includes(projectName))){
  553. return setTimeout(() => location.assign(site.views.library.url), 2500);
  554. }
  555. }, 1000);
  556. },
  557. library: function(guidance){
  558. log('library');
  559. /* there're completely different versions of html by unknown conditions, so... */
  560. let timer = setInterval(function(){
  561. if(location.href.startsWith(site.views.api.url) === false) return;
  562. location.assign(sites.google.views.credentials.url);
  563. }, 1000);
  564. },
  565. credentials: function(guidance){
  566. log('credentials');
  567. let createButton = elements.createButton, apiKey;
  568. /* redirect timer */
  569. let seconds = guidance.querySelector('.secondsLeft');
  570. let timer = setInterval(function(){
  571. /* automatically redirect to YouTube in 60s */
  572. seconds.textContent = parseInt(seconds.textContent) - 1;
  573. if(seconds.textContent === '0') return location.assign(sites.youtube.url + `#apiKey=${apiKey}`);
  574. }, 1000);
  575. /* append body layer */
  576. let layer = createElement(html.bodyLayer());
  577. document.body.appendChild(layer);
  578. /* procedure */
  579. wait(2500).then(() => {
  580. createButton.click();
  581. return core.getTarget(view.get.apiKeyMenuLabel, RETRY);
  582. }).then((apiKeyMenuLabel) => {
  583. apiKeyMenuLabel.click();
  584. return core.getTarget(view.get.apiKeyInput, RETRY);
  585. }).then(apiKeyInput => {
  586. apiKey = apiKeyInput.value;
  587. return core.getTarget(view.get.restrictKeyButton, RETRY);
  588. }).then(restrictKeyButton => {
  589. restrictKeyButton.click();
  590. return core.getTarget(view.get.apiRestrictionRadioButtonLabel, RETRY);
  591. }).then(apiRestrictionRadioButtonLabel => {
  592. apiRestrictionRadioButtonLabel.click();
  593. return core.getTarget(view.get.apiRestrictionSelect, RETRY);
  594. }).then(apiRestrictionSelect => {
  595. apiRestrictionSelect.click();
  596. return core.getTarget(view.get.youtubeDataApiOption, RETRY);
  597. }).then(youtubeDataApiOption => {
  598. if(youtubeDataApiOption.classList.contains('mat-selected') === false) youtubeDataApiOption.click();
  599. return core.getTarget(view.get.saveButton, RETRY);
  600. }).then(saveButton => {
  601. saveButton.click();
  602. return core.getTarget(view.get.createdKey, RETRY);
  603. }).then(createdKey => {
  604. Storage.remove('guiding');
  605. log('Automation completed:');
  606. }).catch((selector) => {
  607. log('Automation error:', selector);
  608. document.body.removeChild(layer);
  609. clearInterval(timer);
  610. });
  611. },
  612. error: function(guidance){
  613. log('error');
  614. let restart = guidance.querySelector(`a[href="${sites.google.views.projectcreate.url}?${SCRIPTID}=true"]`);
  615. restart.addEventListener('click', function(e){
  616. guidance.parentNode.removeChild(guidance);
  617. });
  618. let search = guidance.querySelector(`#${SCRIPTID}-google-how-to`);
  619. search.addEventListener('click', function(e){
  620. Storage.remove('guiding');
  621. });
  622. },
  623. },
  624. getTarget: function(selector, retry = 10, interval = 1*SECOND){
  625. const key = selector.name;
  626. const get = function(resolve, reject){
  627. let selected = selector();
  628. if(selected && selected.length > 0) selected.forEach((s) => s.dataset.selector = key);/* elements */
  629. else if(selected instanceof HTMLElement) selected.dataset.selector = key;/* element */
  630. else if(--retry) return log(`Not found: ${key}, retrying... (${retry})`), setTimeout(get, interval, resolve, reject);
  631. else return reject(new Error(`Not found: ${selector.name}, I give up.`));
  632. elements[key] = selected;
  633. resolve(selected);
  634. };
  635. return new Promise(function(resolve, reject){
  636. get(resolve, reject);
  637. });
  638. },
  639. getTargets: function(selectors, retry = 10, interval = 1*SECOND){
  640. return Promise.all(Object.values(selectors).map(selector => core.getTarget(selector, retry, interval)));
  641. },
  642. addStyle: function(name = 'style'){
  643. let style = createElement(html[name]());
  644. document.head.appendChild(style);
  645. if(elements[name] && elements[name].isConnected) document.head.removeChild(elements[name]);
  646. elements[name] = style;
  647. },
  648. };
  649. const texts = {
  650. /* common */
  651. '${SCRIPTNAME}': {
  652. en: () => `${SCRIPTNAME}`,
  653. ja: () => `${SCRIPTNAME}`,
  654. zh: () => `${SCRIPTNAME}`,
  655. },
  656. /* setup */
  657. '${SCRIPTNAME} setup': {
  658. en: () => `${SCRIPTNAME} setup`,
  659. ja: () => `${SCRIPTNAME} 設定`,
  660. zh: () => `${SCRIPTNAME} 设定`,
  661. },
  662. 'YouTube Data API key': {
  663. en: () => `YouTube Data API key`,
  664. ja: () => `YouTube Data API キー`,
  665. zh: () => `YouTube Data API 密钥`,
  666. },
  667. 'To make it work properly, you should have a YouTube Data API key. Or you can get it now from Google Cloud Platform for FREE. (I shall guide you!!)': {
  668. en: () => `To make it work properly, you should have a YouTube Data API key. Or you can get it now from Google Cloud Platform for FREE. (I shall guide you!!)`,
  669. ja: () => `このスクリプトの動作には YouTube Data API キー が必要です。お持ちでなければ無料でいま取得することもできます。(ご案内します!)`,
  670. zh: () => `要使其正常工作,您应该有一个 YouTube Data API 密钥。或者你现在可以从 Google Cloud Platform 免费得到它。(我来给你带路!)`,
  671. },
  672. 'Create your API key on Google': {
  673. en: () => `Create your API key on Google`,
  674. ja: () => `Google API キー を作成する`,
  675. zh: () => `在 Google 上创建您的 API 密钥`,
  676. },
  677. 'Check your API key already you have': {
  678. en: () => `Check your API key already you have`,
  679. ja: () => `すでにお持ちの API キー を確認する`,
  680. zh: () => `查看您已经拥有的 API 密钥`,
  681. },
  682. 'Check your API quota and usage': {
  683. en: () => `Check your API quota and usage`,
  684. ja: () => `API 割り当て量と使用量を確認する`,
  685. zh: () => `检查您的 API 配额和使用情况`,
  686. },
  687. 'Cancel': {
  688. en: () => `Cancel`,
  689. ja: () => `キャンセル`,
  690. zh: () => `取消`,
  691. },
  692. 'Save': {
  693. en: () => `Save`,
  694. ja: () => `保存`,
  695. zh: () => `保存`,
  696. },
  697. /* guidance */
  698. '${SCRIPTNAME} guidance': {
  699. en: () => `${SCRIPTNAME} guidance`,
  700. ja: () => `${SCRIPTNAME} ガイド`,
  701. zh: () => `${SCRIPTNAME} 向导`,
  702. },
  703. /* projectcreate */
  704. 'Create a new project': {
  705. en: () => `Create a new project`,
  706. ja: () => `新しいプロジェクトの作成`,
  707. zh: () => `创建新项目`,
  708. },
  709. '<em>Project name</em>: You can input any name such as "<span class="name">${SCRIPTNAME}</span>" or "<span class="name">Private</span>" or just leave it as "<span class="name default">default</span>".': {
  710. en: () => `<em>Project name</em>: You can input any name such as "<span class="name">${SCRIPTNAME}</span>" or "<span class="name">Private</span>" or just leave it as "<span class="name default">default</span>".`,
  711. ja: () => `<em>プロジェクト名</em>: 自由な名前をご入力ください。"<span class="name">${SCRIPTNAME}</span>" や "<span class="name">Private</span>" などでも、"<span class="name default">デフォルト</span>" のままでもかまいません。`,
  712. zh: () => `<em>项目名称</em>: 可以输入 "<span class="name">${SCRIPTNAME}</span>"、"<span class="name">Private</span>" 等任意名称、也可以保留为 "<span class="name default">默认</span>"。`,
  713. },
  714. '<em>Location</em>: Leave it as "No organization".': {
  715. en: () => `<em>Location</em>: Leave it as "No organization".`,
  716. ja: () => `<em>場所</em>: "組織なし" のままで大丈夫です。`,
  717. zh: () => `<em>位置</em>: 保留为 "无组织"。`,
  718. },
  719. 'Click the <em>CREATE</em> button.': {
  720. en: () => `Click the <em>CREATE</em> button.`,
  721. ja: () => `<em>作成</em> ボタンをクリックします。`,
  722. zh: () => `单击 <em>创建</em> 按钮。`,
  723. },
  724. 'If you already have a project to use, <a href="${sites.google.views.library.url}">skip this step</a>.': {
  725. en: () => `If you already have a project to use, <a href="${sites.google.views.library.url}">skip this step</a>.`,
  726. ja: () => `すでに利用するプロジェクトを作成済みの場合は、<a href="${sites.google.views.library.url}">このステップを飛ばしてください</a>。`,
  727. zh: () => `如果您已经有项目要使用,<a href="${sites.google.views.library.url}">跳过此步骤</a>。`,
  728. },
  729. 'Or you can <a href="${sites.google.views.projectcreate.url}">leave this guidance</a>.': {
  730. en: () => `Or you can <a href="${sites.google.views.projectcreate.url}">leave this guidance</a>.`,
  731. ja: () => `または<a href="${sites.google.views.projectcreate.url}">このガイダンスを終了することもできます</a>。`,
  732. zh: () => `或者你可以<a href="${sites.google.views.projectcreate.url}">离开这份向导</a>。`,
  733. },
  734. /* dashboard */
  735. 'Wait until the project has been created.': {
  736. en: () => `Wait until the project has been created.`,
  737. ja: () => `プロジェクトの作成が完了するまでお待ちください。`,
  738. zh: () => `等待项目创建完成。`,
  739. },
  740. 'After creation, you can go to the next step. (You will automatically be redirected within <span class="secondsLeft">60</span> seconds at the most)': {
  741. en: () => `After creation, you can go to the next step. (You will automatically be redirected within <span class="secondsLeft">60</span> seconds at the most)`,
  742. ja: () => `完了後に次のステップにお進みいただけます。 (<span class="secondsLeft">60</span>秒以内に自動的に移動します)`,
  743. zh: () => `完成后可以进入下一步。 (您最多会在<span class="secondsLeft">60</span>秒内自动重定向)`,
  744. },
  745. 'Enable the YouTube Data API': {
  746. en: () => `Enable the YouTube Data API`,
  747. ja: () => `YouTube Data API を有効にする`,
  748. zh: () => `启用 YouTube Data API`,
  749. },
  750. /* library */
  751. 'Enable the API': {
  752. en: () => `Enable the API`,
  753. ja: () => `API を有効にします`,
  754. zh: () => `启用 API`,
  755. },
  756. 'Just click the <em>ENABLE</em> button.': {
  757. en: () => `Just click the <em>ENABLE</em> button.`,
  758. ja: () => `<em>有効にする</em> ボタンをクリックしてください。`,
  759. zh: () => `只需单击 <em>启用</em> 按钮。`,
  760. },
  761. 'If a dialog to select a project is shown, select the project you just created.': {
  762. en: () => `If a dialog to select a project is shown, select the project you just created.`,
  763. ja: () => `もしプロジェクトを選択するダイアログが表示されたら、先ほど作成したプロジェクトを選択します。`,
  764. zh: () => `如果显示选择项目的对话框,请选择您刚刚创建的项目。`,
  765. },
  766. 'Then wait a moment.': {
  767. en: () => `Then wait a moment.`,
  768. ja: () => `しばらくお待ちください。`,
  769. zh: () => `那么请稍等片刻。`,
  770. },
  771. 'If the API is already enabled, you can go to the next step.': {
  772. en: () => `If the API is already enabled, you can go to the next step.`,
  773. ja: () => `すでに API が有効になっている場合は、次のステップにお進みください。`,
  774. zh: () => `如果 API 已经启用,您可以进入下一步。`,
  775. },
  776. 'Create an API key': {
  777. en: () => `Create an API key`,
  778. ja: () => `API キー を作成する`,
  779. zh: () => `创建 API 密钥`,
  780. },
  781. /* credentials */
  782. 'Now automatically creating API key... (You will be redirected back to <a href="${sites.youtube.url}">YouTube</a> in <span class="secondsLeft">60</span> seconds)': {
  783. en: () => `Now automatically creating API key... (You will be redirected back to <a href="${sites.youtube.url}">YouTube</a> in <span class="secondsLeft">60</span> seconds)`,
  784. ja: () => `API キー を作成しています... (<span class="secondsLeft">60</span>秒後に自動的に <a href="${sites.youtube.url}">YouTube</a> に戻ります)`,
  785. zh: () => `正在自动创建 API 密钥... (您将在<span class="secondsLeft">60</span>秒内被重定向回 <a href="${sites.youtube.url}">YouTube</a>)`,
  786. },
  787. 'If it fails and stuck, you can check and do the following steps by yourself.': {
  788. en: () => `If it fails and stuck, you can check and do the following steps by yourself.`,
  789. ja: () => `失敗して処理が止まった場合は、次の手続きをご自身で確認してください。`,
  790. zh: () => `如果失败并停止,您可以自行检查并执行以下步骤。`,
  791. },
  792. 'Click the <em>+ CREATE CREDENTIALS</em> button.': {
  793. en: () => `Click the <em>+ CREATE CREDENTIALS</em> button.`,
  794. ja: () => `<em>+ 認証情報を作成</em> ボタンをクリックします。`,
  795. zh: () => `单击 <em>+ 创建凭据</em> 按钮。`,
  796. },
  797. 'Click <em>API key</em> on the dropdown menu.': {
  798. en: () => `Click <em>API key</em> on the dropdown menu.`,
  799. ja: () => `表示されたメニュー内の <em>API キー</em> をクリックします。`,
  800. zh: () => `单击下拉菜单上的 <em>API 密钥</em>`,
  801. },
  802. 'API key will be created.': {
  803. en: () => `API key will be created.`,
  804. ja: () => `API キーが作成されます。`,
  805. zh: () => `将创建 API 密钥。`,
  806. },
  807. 'Click the <em>RESTRICT KEY</em> button.': {
  808. en: () => `Click the <em>RESTRICT KEY</em> button.`,
  809. ja: () => `<em>キーを制限</em> ボタンをクリックします。`,
  810. zh: () => `单击 <em>限制键</em> 按钮。`,
  811. },
  812. 'Click the <em>Restrict key</em> radio button on the <em>API restrictions</em> section.': {
  813. en: () => `Click the <em>Restrict key</em> radio button on the <em>API restrictions</em> section.`,
  814. ja: () => `<em>API の制限</em> セクション内の <em>キーを制限</em> ラジオボタンをクリックします。`,
  815. zh: () => `单击 <em>API 限制</em> 部分上的 <em>限制密钥</em> 单选按钮。`,
  816. },
  817. 'Click the <em>Select APIs</em> dropdown menu and check <em>YouTube Data API v3</em> at (probably) the bottom of the menu.': {
  818. en: () => `Click the <em>Select APIs</em> dropdown menu and check <em>YouTube Data API v3</em> at (probably) the bottom of the menu.`,
  819. ja: () => `<em>Select APIs</em> ドロップダウンメニューをクリックし、(おそらく)一番下に表示される <em>YouTube Data API v3</em> にチェックを入れます。`,
  820. zh: () => `单击 <em>Select APIs</em> 下拉菜单,然后选中菜单底部(可能)的 <em>YouTube Data API v3</em>。`,
  821. },
  822. 'Click the <em>SAVE</em> button.': {
  823. en: () => `Click the <em>SAVE</em> button.`,
  824. ja: () => `<em>保存</em> ボタンをクリックします。`,
  825. zh: () => `单击 <em>保存</em> 按钮。`,
  826. },
  827. 'Copy the created API key with the copy icon button on the right.': {
  828. en: () => `Copy the created API key with the copy icon button on the right.`,
  829. ja: () => `作成された API キー を、すぐ右隣のコピーアイコンボタンをクリックしてコピーします。`,
  830. zh: () => `使用右侧的复制图标按钮复制创建的 API 密钥。`,
  831. },
  832. 'Go to <a href="${sites.youtube.url}">YouTube</a>, then paste and save the key on ${SCRIPTNAME} setup panel.': {
  833. en: () => `Go to <a href="${sites.youtube.url}">YouTube</a>, then paste and save the key on ${SCRIPTNAME} setup panel.`,
  834. ja: () => `<a href="${sites.youtube.url}">YouTube</a> へ移動して、${SCRIPTNAME} 設定 パネル内にキーを貼り付け保存します。`,
  835. zh: () => `转到 <a href="${sites.youtube.url}">YouTube</a>,然后在 ${SCRIPTNAME} 设置 面板上粘贴并保存密钥。`,
  836. },
  837. /* error */
  838. 'Sorry, no guidance was found for this page.': {
  839. en: () => `Sorry, no guidance was found for this page.`,
  840. ja: () => `申し訳ありません。このページ向けのガイダンスが見つかりませんでした。`,
  841. zh: () => `抱歉,找不到此页的指导。`,
  842. },
  843. 'Start over from the first step': {
  844. en: () => `Start over from the first step`,
  845. ja: () => `最初からやり直す`,
  846. zh: () => `从第一步开始`,
  847. },
  848. 'You can also get an API key by yourself and enter it on YouTube.': {
  849. en: () => `You can also get an API key by yourself and enter it on YouTube.`,
  850. ja: () => `独自に API キー を取得してYouTubeで入力することもできます。`,
  851. zh: () => `您也可以自己获取 API 密钥,然后在 YouTube 上输入。`,
  852. },
  853. 'https://www.google.com/search?q=How+to+get+YouTube+Data+API+key': {
  854. en: () => `https://www.google.com/search?q=How+to+get+YouTube+Data+API+key`,
  855. ja: () => `https://www.google.com/search?q=YouTube+Data+API+キー+取得`,
  856. zh: () => `https://www.google.com/search?q=YouTube+Data+API+密钥+获取`,
  857. },
  858. 'Serach how to get an API key': {
  859. en: () => `Serach how to get an API key`,
  860. ja: () => `API キー の取得の仕方を検索する`,
  861. zh: () => `研究如何获取 API 密钥。`,
  862. },
  863. '<a href="https://gf.qytechs.cn/en/scripts/30254">Your reporting of this error is very welcomed.</a>': {
  864. en: () => `<a href="https://gf.qytechs.cn/en/scripts/30254">Your reporting of this error is very welcomed.</a>`,
  865. ja: () => `<a href="https://gf.qytechs.cn/ja/scripts/30254">エラーの報告を歓迎します。</a>`,
  866. zh: () => `<a href="https://gf.qytechs.cn/zh-CN/scripts/30254">欢迎报告错误。</a>`,
  867. },
  868. };
  869. const html = {
  870. bar: (height, percentage) => `
  871. <div id="container" class="style-scope ytd-sentiment-bar-renderer" style="height:${height}px; background-color:${DISLIKECOLOR}">
  872. <div id="like-bar" class="style-scope ytd-sentiment-bar-renderer" style="height:${height}px; width:${percentage}%; background-color:${LIKECOLOR}"></div>
  873. </div>
  874. `,
  875. configButton: () => `
  876. <div id="${SCRIPTID}-configButton">
  877. <span class="icon"><!-- Svg Vector Icons : http://www.onlinewebfonts.com/icon --><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1000 1000" enable-background="new 0 0 1000 1000" xml:space="preserve"><metadata> Svg Vector Icons : http://www.onlinewebfonts.com/icon </metadata><g><path d="M10,141.7v211.4h980V141.7H10z M960.2,323.3H636V171.6h324.2V323.3z"/><path d="M10,604.6h980V393.1H10V604.6z M960.2,574.7H365.7V423h594.5V574.7z"/><path d="M10,858.3h980V646.8H10V858.3z M960.2,828.4H815.1V676.7h145.1V828.4z"/></g></svg></span>
  878. <span class="label">${text('${SCRIPTNAME}')}</span>
  879. </div>
  880. `,
  881. panels: () => `<div class="panels" id="${SCRIPTID}-panels" data-panels="0"></div>`,
  882. configPanel: () => `
  883. <div class="panel" id="${SCRIPTID}-configPanel" data-order="1">
  884. <h1>${text('${SCRIPTNAME} setup')}</h1>
  885. <fieldset>
  886. <legend>${text('YouTube Data API key')}:</legend>
  887. <p><input type="text" name="apiKey" value="${configs.apiKey}" placeholder="API key"></p>
  888. <p class="description">${text('To make it work properly, you should have a YouTube Data API key. Or you can get it now from Google Cloud Platform for FREE. (I shall guide you!!)')}</p>
  889. <p class="description"><a href="${sites.google.views.projectcreate.url}?${SCRIPTID}=true" id="${SCRIPTID}-getKeyButton" class="button">${text('Create your API key on Google')}</a></p>
  890. <p class="note"><a href="${sites.google.views.credentials.url}">${text('Check your API key already you have')}</a></p>
  891. <p class="note"><a href="${sites.google.views.quotas.url}">${text('Check your API quota and usage')}</a></p>
  892. </fieldset>
  893. <p class="buttons"><button class="cancel">${text('Cancel')}</button><button class="save primary">${text('Save')}</button></p>
  894. </div>
  895. `,
  896. projectcreate: () => `
  897. <div class="${SCRIPTID}-guidance">
  898. <h1>${text('${SCRIPTNAME} guidance')}</h1>
  899. <p class="message">${text('Create a new project')}</p>
  900. <ol>
  901. <li>${text('<em>Project name</em>: You can input any name such as "<span class="name">${SCRIPTNAME}</span>" or "<span class="name">Private</span>" or just leave it as "<span class="name default">default</span>".')}</li>
  902. <li>${text('<em>Location</em>: Leave it as "No organization".')}</li>
  903. <li>${text('Click the <em>CREATE</em> button.')}</li>
  904. </ol>
  905. <p class="note">${text('If you already have a project to use, <a href="${sites.google.views.library.url}">skip this step</a>.')}</p>
  906. <p class="note">${text('Or you can <a href="${sites.google.views.projectcreate.url}">leave this guidance</a>.')}</p>
  907. </div>
  908. `,
  909. bodyLayer: () => `<div class="${SCRIPTID}-bodyLayer"></div>`,
  910. dashboard: () => `
  911. <div class="${SCRIPTID}-guidance">
  912. <h1>${text('${SCRIPTNAME} guidance')}</h1>
  913. <ol>
  914. <li>${text('Wait until the project has been created.')}</li>
  915. <li>${text('After creation, you can go to the next step. (You will automatically be redirected within <span class="secondsLeft">60</span> seconds at the most)')} <a href="${sites.google.views.library.url}">${text('Enable the YouTube Data API')}</a></li>
  916. </ol>
  917. </div>
  918. `,
  919. library: () => `
  920. <div class="${SCRIPTID}-guidance">
  921. <h1>${text('${SCRIPTNAME} guidance')}</h1>
  922. <p class="message">${text('Enable the API')}</p>
  923. <ol>
  924. <li>
  925. ${text('Just click the <em>ENABLE</em> button.')}
  926. <p class="note">${text('If the API is already enabled, you can go to the next step.')} <a href="${sites.google.views.credentials.url}">${text('Create an API key')}</a></p>
  927. </li>
  928. <li>${text('If a dialog to select a project is shown, select the project you just created.')}</li>
  929. <li>${text('Then wait a moment.')}</li>
  930. </ol>
  931. </div>
  932. `,
  933. credentials: () => `
  934. <div class="${SCRIPTID}-guidance">
  935. <h1>${text('${SCRIPTNAME} guidance')}</h1>
  936. <p class="message">${text('Now automatically creating API key... (You will be redirected back to <a href="${sites.youtube.url}">YouTube</a> in <span class="secondsLeft">60</span> seconds)')}</p>
  937. <p>${text('If it fails and stuck, you can check and do the following steps by yourself.')}</p>
  938. <ol>
  939. <li>${text('Click the <em>+ CREATE CREDENTIALS</em> button.')}</li>
  940. <li>${text('Click <em>API key</em> on the dropdown menu.')}</li>
  941. <li>${text('API key will be created.')}</li>
  942. <li>${text('Click the <em>RESTRICT KEY</em> button.')}</li>
  943. <li>${text('Click the <em>Restrict key</em> radio button on the <em>API restrictions</em> section.')}</li>
  944. <li>${text('Click the <em>Select APIs</em> dropdown menu and check <em>YouTube Data API v3</em> at (probably) the bottom of the menu.')}</li>
  945. <li>${text('Click the <em>SAVE</em> button.')}</li>
  946. <li>${text('Copy the created API key with the copy icon button on the right.')}</li>
  947. <li>${text('Go to <a href="${sites.youtube.url}">YouTube</a>, then paste and save the key on ${SCRIPTNAME} setup panel.')}</li>
  948. </ol>
  949. </div>
  950. `,
  951. error: () => `
  952. <div class="${SCRIPTID}-guidance">
  953. <h1>${text('${SCRIPTNAME} guidance')}</h1>
  954. <p class="message">${text('Sorry, no guidance was found for this page.')}</p>
  955. <p><a href="${sites.google.views.projectcreate.url}?${SCRIPTID}=true" class="button active">${text('Start over from the first step')}</a></p>
  956. <p>${text('You can also get an API key by yourself and enter it on YouTube.')}</p>
  957. <p><a href="${text('https://www.google.com/search?q=How+to+get+YouTube+Data+API+key')}" class="button active" id="${SCRIPTID}-google-how-to">${text('Serach how to get an API key')}</a></p>
  958. <p class="note">${text('<a href="https://gf.qytechs.cn/en/scripts/30254">Your reporting of this error is very welcomed.</a>')}</p>
  959. </div>
  960. `,
  961. style: () => `
  962. <style type="text/css" id="${SCRIPTID}-style">
  963. /* maximize bar width */
  964. #meta.ytd-rich-grid-video-renderer/*home*/,
  965. #meta.ytd-rich-grid-media/*home*/,
  966. ytd-video-meta-block,
  967. #metadata.ytd-video-meta-block,
  968. #container.ytd-sentiment-bar-renderer,
  969. .metadata.ytd-compact-video-renderer{
  970. width: 100%;
  971. }
  972. /* rating bars */
  973. #container.ytd-sentiment-bar-renderer{
  974. margin-bottom: 1px;/*gap for LIVE, NEW banner*/
  975. animation: ${SCRIPTID}-show 250ms 1;/*softly show bars*/
  976. }
  977. @keyframes ${SCRIPTID}-show{
  978. from{
  979. opacity: 0;
  980. }
  981. to{
  982. opacity: 1;
  983. }
  984. }
  985. /* config button */
  986. #${SCRIPTID}-configButton{
  987. height: 40px;
  988. padding: var(--yt-compact-link-paper-item-padding, 0px 36px 0 16px);
  989. font-size: var(--ytd-user-comment_-_font-size);
  990. font-weight: var(--ytd-user-comment_-_font-weight);
  991. line-height: 40px;
  992. color: var(--yt-compact-link-color, var(--yt-spec-text-primary));
  993. font-family: var(--paper-font-subhead_-_font-family);
  994. cursor: pointer;
  995. display: flex;
  996. }
  997. #${SCRIPTID}-configButton:hover{
  998. background: var(--yt-spec-badge-chip-background);
  999. }
  1000. #${SCRIPTID}-configButton .icon{
  1001. margin-right: 16px;
  1002. width: 24px;
  1003. height: 40px;
  1004. fill: gray;
  1005. display: flex;
  1006. }
  1007. #${SCRIPTID}-configButton .icon svg{
  1008. width: 100%;
  1009. height: 100%;
  1010. }
  1011. </style>
  1012. `,
  1013. panelStyle: () => `
  1014. <style type="text/css" id="${SCRIPTID}-panelStyle">
  1015. /* panels default */
  1016. #${SCRIPTID}-panels *{
  1017. font-size: 14px;
  1018. line-height: 20px;
  1019. padding: 0;
  1020. margin: 0;
  1021. }
  1022. #${SCRIPTID}-panels{
  1023. font-family: Arial, sans-serif;
  1024. position: fixed;
  1025. width: 100%;
  1026. height: 100%;
  1027. top: 0;
  1028. left: 0;
  1029. overflow: hidden;
  1030. pointer-events: none;
  1031. cursor: default;
  1032. z-index: 99999;
  1033. }
  1034. #${SCRIPTID}-panels div.panel{
  1035. position: absolute;
  1036. max-height: 100%;
  1037. overflow: auto;
  1038. left: 50%;
  1039. bottom: 50%;
  1040. transform: translate(-50%, 50%);
  1041. background: rgba(0,0,0,.75);
  1042. transition: 250ms;
  1043. padding: 5px 0;
  1044. pointer-events: auto;
  1045. }
  1046. #${SCRIPTID}-panels div.panel.hidden{
  1047. bottom: 0;
  1048. transform: translate(-50%, 100%) !important;
  1049. display: block !important;
  1050. }
  1051. #${SCRIPTID}-panels div.panel.hidden *{
  1052. animation: none !important;
  1053. }
  1054. #${SCRIPTID}-panels h1,
  1055. #${SCRIPTID}-panels h2,
  1056. #${SCRIPTID}-panels h3,
  1057. #${SCRIPTID}-panels h4,
  1058. #${SCRIPTID}-panels legend,
  1059. #${SCRIPTID}-panels ul,
  1060. #${SCRIPTID}-panels ol,
  1061. #${SCRIPTID}-panels dl,
  1062. #${SCRIPTID}-panels p{
  1063. color: white;
  1064. padding: 2px 10px;
  1065. vertical-align: baseline;
  1066. }
  1067. #${SCRIPTID}-panels legend ~ p,
  1068. #${SCRIPTID}-panels legend ~ ul,
  1069. #${SCRIPTID}-panels legend ~ ol,
  1070. #${SCRIPTID}-panels legend ~ dl{
  1071. padding-left: calc(10px + 14px);
  1072. }
  1073. #${SCRIPTID}-panels header{
  1074. display: flex;
  1075. }
  1076. #${SCRIPTID}-panels header h1{
  1077. flex: 1;
  1078. }
  1079. #${SCRIPTID}-panels fieldset{
  1080. border: none;
  1081. }
  1082. #${SCRIPTID}-panels fieldset > p{
  1083. display: flex;
  1084. align-items: center;
  1085. }
  1086. #${SCRIPTID}-panels fieldset > p:not([class]):hover{
  1087. background: rgba(255,255,255,.125);
  1088. }
  1089. #${SCRIPTID}-panels fieldset > p > label{
  1090. flex: 1;
  1091. }
  1092. #${SCRIPTID}-panels fieldset > p > input,
  1093. #${SCRIPTID}-panels fieldset > p > textarea,
  1094. #${SCRIPTID}-panels fieldset > p > select{
  1095. color: black;
  1096. background: white;
  1097. padding: 1px 2px;
  1098. }
  1099. #${SCRIPTID}-panels fieldset > p > input,
  1100. #${SCRIPTID}-panels fieldset > p > button{
  1101. box-sizing: border-box;
  1102. height: 20px;
  1103. }
  1104. #${SCRIPTID}-panels fieldset small{
  1105. font-size: 12px;
  1106. margin: 0 0 0 .25em;
  1107. }
  1108. #${SCRIPTID}-panels fieldset sup,
  1109. #${SCRIPTID}-panels fieldset p.note{
  1110. font-size: 10px;
  1111. line-height: 14px;
  1112. color: rgb(192,192,192);
  1113. }
  1114. #${SCRIPTID}-panels a{
  1115. color: inherit;
  1116. font-size: inherit;
  1117. line-height: inherit;
  1118. }
  1119. #${SCRIPTID}-panels a:hover{
  1120. color: rgb(224,224,224);
  1121. }
  1122. #${SCRIPTID}-panels div.panel > p.buttons{
  1123. text-align: right;
  1124. padding: 5px 10px;
  1125. }
  1126. #${SCRIPTID}-panels div.panel > p.buttons button{
  1127. line-height: 1.4;
  1128. width: 120px;
  1129. padding: 5px 10px;
  1130. margin-left: 10px;
  1131. border-radius: 5px;
  1132. color: rgba(255,255,255,1);
  1133. background: rgba(64,64,64,1);
  1134. border: 1px solid rgba(255,255,255,1);
  1135. cursor: pointer;
  1136. }
  1137. #${SCRIPTID}-panels div.panel > p.buttons button.primary{
  1138. font-weight: bold;
  1139. background: rgba(0,0,0,1);
  1140. }
  1141. #${SCRIPTID}-panels div.panel > p.buttons button.primary.active{
  1142. background: rgba(0,0,255,1);
  1143. }
  1144. #${SCRIPTID}-panels div.panel > p.buttons button:hover,
  1145. #${SCRIPTID}-panels div.panel > p.buttons button:focus{
  1146. background: rgba(128,128,128,1);
  1147. }
  1148. #${SCRIPTID}-panels .template{
  1149. display: none !important;
  1150. }
  1151. /* config panel */
  1152. #${SCRIPTID}-configPanel{
  1153. width: 380px;
  1154. }
  1155. [name="apiKey"]{
  1156. width: 100%;
  1157. }
  1158. #${SCRIPTID}-configPanel a.button{
  1159. background: rgb(128,128,128);
  1160. color: white;
  1161. padding: 5px 10px;
  1162. margin: 5px 0;
  1163. border: 1px solid white;
  1164. border-radius: 5px;
  1165. display: inline-block;
  1166. text-decoration: none;
  1167. }
  1168. #${SCRIPTID}-configPanel a.button.active{
  1169. background: rgb(6, 95, 212);
  1170. }
  1171. #${SCRIPTID}-configPanel a.button:hover,
  1172. #${SCRIPTID}-configPanel a.button:focus{
  1173. background: rgb(112, 172, 251);
  1174. }
  1175. </style>
  1176. `,
  1177. guideStyle: () => `
  1178. <style type="text/css" id="${SCRIPTID}-guideStyle">
  1179. /* overlay */
  1180. .${SCRIPTID}-bodyLayer{
  1181. width: 100%;
  1182. height: 100%;
  1183. background: rgba(255,255,255,.75);
  1184. z-index: 99990;
  1185. position: fixed;
  1186. top: 0;
  1187. left: 0;
  1188. }
  1189. /* guide panel */
  1190. .${SCRIPTID}-guidance{
  1191. font-size: 14px !important;
  1192. line-height: 20px !important;
  1193. background: rgba(0,0,0,.75);
  1194. padding: 5px 0;
  1195. position: absolute;
  1196. z-index: 99999;
  1197. transition: opacity 1s;
  1198. }
  1199. .${SCRIPTID}-guidance.hidden{
  1200. opacity: 0;
  1201. }
  1202. .${SCRIPTID}-guidance *{
  1203. font-size: inherit !important;
  1204. line-height: inherit !important;
  1205. color: white !important;
  1206. }
  1207. .${SCRIPTID}-guidance a{
  1208. font-size: inherit !important;
  1209. line-height: inherit !important;
  1210. color: inherit !important;
  1211. border-color: inherit !important;
  1212. text-decoration: underline !important;
  1213. }
  1214. .${SCRIPTID}-guidance a:hover{
  1215. color: rgb(224,224,224) !important;
  1216. }
  1217. .${SCRIPTID}-guidance h1,
  1218. .${SCRIPTID}-guidance p{
  1219. padding: 2px 10px !important;
  1220. margin: 0 !important;
  1221. display: block;
  1222. bottom: 0;/* overwrite google */
  1223. }
  1224. .${SCRIPTID}-guidance p.message{
  1225. font-size: 20px !important;
  1226. line-height: 28px !important;
  1227. background: rgba(255,255,255,.125) !important;
  1228. padding: 5px 10px !important;
  1229. }
  1230. .${SCRIPTID}-guidance p.note{
  1231. font-size: 10px !important;
  1232. line-height: 14px !important;
  1233. color: rgb(192,192,192) !important;
  1234. }
  1235. .${SCRIPTID}-guidance h1{
  1236. color: rgb(192,192,192) !important;
  1237. }
  1238. .${SCRIPTID}-guidance ol{
  1239. padding-left: 2em;
  1240. margin: 5px 0 !important;
  1241. list-style-type: decimal;
  1242. }
  1243. .${SCRIPTID}-guidance li{
  1244. padding: 2px 10px 2px 0 !important;
  1245. margin: 5px 0 !important;
  1246. }
  1247. .${SCRIPTID}-guidance em{
  1248. font-weight: bold !important;
  1249. font-style: normal !important;
  1250. }
  1251. .${SCRIPTID}-guidance span.name{
  1252. background: rgba(255,255,255,.25);
  1253. cursor: pointer;
  1254. }
  1255. .${SCRIPTID}-guidance a.button{
  1256. background: rgb(128,128,128);
  1257. color: white;
  1258. padding: 5px 10px;
  1259. margin: 5px 0;
  1260. border: 1px solid white;
  1261. border-radius: 5px;
  1262. display: inline-block;
  1263. text-decoration: none;
  1264. }
  1265. .${SCRIPTID}-guidance a.button.active{
  1266. background: rgb(6, 95, 212);
  1267. }
  1268. .${SCRIPTID}-guidance a.button:hover,
  1269. .${SCRIPTID}-guidance a.button:focus{
  1270. background: rgb(112, 172, 251);
  1271. }
  1272. .draggable{
  1273. cursor: move;
  1274. }
  1275. .draggable.dragging{
  1276. user-select: none;
  1277. }
  1278. </style>
  1279. `,
  1280. };
  1281. const setTimeout = window.setTimeout.bind(window), clearTimeout = window.clearTimeout.bind(window), setInterval = window.setInterval.bind(window), clearInterval = window.clearInterval.bind(window), requestAnimationFrame = window.requestAnimationFrame.bind(window);
  1282. const alert = window.alert.bind(window), confirm = window.confirm.bind(window), prompt = window.prompt.bind(window), getComputedStyle = window.getComputedStyle.bind(window), fetch = window.fetch.bind(window);
  1283. if(!('isConnected' in Node.prototype)) Object.defineProperty(Node.prototype, 'isConnected', {get: function(){return document.contains(this)}});
  1284. class Storage{
  1285. static key(key){
  1286. return (SCRIPTID) ? (SCRIPTID + '-' + key) : key;
  1287. }
  1288. static save(key, value, expire = null){
  1289. key = Storage.key(key);
  1290. localStorage[key] = JSON.stringify({
  1291. value: value,
  1292. saved: Date.now(),
  1293. expire: expire,
  1294. });
  1295. }
  1296. static read(key){
  1297. key = Storage.key(key);
  1298. if(localStorage[key] === undefined) return undefined;
  1299. let data = JSON.parse(localStorage[key]);
  1300. if(data.value === undefined) return data;
  1301. if(data.expire === undefined) return data;
  1302. if(data.expire === null) return data.value;
  1303. if(data.expire < Date.now()) return localStorage.removeItem(key);/*undefined*/
  1304. return data.value;
  1305. }
  1306. static remove(key){
  1307. key = Storage.key(key);
  1308. delete localStorage.removeItem(key);
  1309. }
  1310. static delete(key){
  1311. Storage.remove(key);
  1312. }
  1313. static saved(key){
  1314. key = Storage.key(key);
  1315. if(localStorage[key] === undefined) return undefined;
  1316. let data = JSON.parse(localStorage[key]);
  1317. if(data.saved) return data.saved;
  1318. else return undefined;
  1319. }
  1320. }
  1321. class Panels{
  1322. constructor(parent){
  1323. this.parent = parent;
  1324. this.panels = {};
  1325. this.listen();
  1326. }
  1327. listen(){
  1328. window.addEventListener('keydown', (e) => {
  1329. if(e.key !== 'Escape') return;
  1330. if(['input', 'textarea'].includes(document.activeElement.localName)) return;
  1331. Object.keys(this.panels).forEach(key => this.hide(key));
  1332. }, true);
  1333. }
  1334. add(name, panel){
  1335. this.panels[name] = panel;
  1336. }
  1337. toggle(name){
  1338. let panel = this.panels[name];
  1339. if(panel.isConnected === false || panel.classList.contains('hidden')) this.show(name);
  1340. else this.hide(name);
  1341. }
  1342. show(name){
  1343. let panel = this.panels[name];
  1344. if(panel.isConnected) return;
  1345. panel.classList.add('hidden');
  1346. this.parent.appendChild(panel);
  1347. this.parent.dataset.panels = parseInt(this.parent.dataset.panels) + 1;
  1348. animate(() => panel.classList.remove('hidden'));
  1349. }
  1350. hide(name){
  1351. let panel = this.panels[name];
  1352. if(panel.classList.contains('hidden')) return;
  1353. panel.classList.add('hidden');
  1354. panel.addEventListener('transitionend', (e) => {
  1355. this.parent.removeChild(panel);
  1356. this.parent.dataset.panels = parseInt(this.parent.dataset.panels) - 1;
  1357. }, {once: true});
  1358. }
  1359. }
  1360. const text = function(key, ...args){
  1361. if(text.texts[key] === undefined){
  1362. log('Not found text key:', key);
  1363. return key;
  1364. }else return text.texts[key](args);
  1365. };
  1366. text.setup = function(texts, language){
  1367. let languages = [...window.navigator.languages];
  1368. if(language) languages.unshift(...String(language).split('-').map((p,i,a) => a.slice(0,1+i).join('-')).reverse());
  1369. if(!languages.includes('en')) languages.push('en');
  1370. languages = languages.map(l => l.toLowerCase());
  1371. Object.keys(texts).forEach(key => {
  1372. Object.keys(texts[key]).forEach(l => texts[key][l.toLowerCase()] = texts[key][l]);
  1373. texts[key] = texts[key][languages.find(l => texts[key][l] !== undefined)] || (() => key);
  1374. });
  1375. text.texts = texts;
  1376. };
  1377. const $ = function(s, f){
  1378. let target = document.querySelector(s);
  1379. if(target === null) return null;
  1380. return f ? f(target) : target;
  1381. };
  1382. const $$ = function(s, f){
  1383. let targets = document.querySelectorAll(s);
  1384. return f ? Array.from(targets).map(t => f(t)) : targets;
  1385. };
  1386. const animate = function(callback, ...params){requestAnimationFrame(() => requestAnimationFrame(() => callback(...params)))};
  1387. const wait = function(ms){return new Promise((resolve) => setTimeout(resolve, ms))};
  1388. const createElement = function(html = '<span></span>'){
  1389. let outer = document.createElement('div');
  1390. outer.innerHTML = html;
  1391. return outer.firstElementChild;
  1392. };
  1393. const observe = function(element, callback, options = {childList: true, attributes: false, characterData: false}){
  1394. let observer = new MutationObserver(callback.bind(element));
  1395. observer.observe(element, options);
  1396. return observer;
  1397. };
  1398. const draggable = function(element){
  1399. const DELAY = 125;/* catching up mouse position while fast dragging (ms) */
  1400. const mousedown = function(e){
  1401. if(e.button !== 0) return;
  1402. element.classList.add('dragging');
  1403. [screenX, screenY] = [e.screenX, e.screenY];
  1404. [a,b,c,d,tx,ty] = (getComputedStyle(element).transform.match(/[-0-9.]+/g) || [1,0,0,1,0,0]).map((n) => parseFloat(n));
  1405. window.addEventListener('mousemove', mousemove);
  1406. window.addEventListener('mouseup', mouseup, {once: true});
  1407. document.body.addEventListener('mouseleave', mouseup, {once: true});
  1408. element.addEventListener('mouseleave', mouseleave, {once: true});
  1409. };
  1410. const mousemove = function(e){
  1411. element.style.transform = `matrix(${a},${b},${c},${d},${tx + (e.screenX - screenX)},${ty + (e.screenY - screenY)})`;
  1412. };
  1413. const mouseup = function(e){
  1414. element.classList.remove('dragging');
  1415. window.removeEventListener('mousemove', mousemove);
  1416. };
  1417. const mouseleave = function(e){
  1418. let timer = setTimeout(mouseup, DELAY);
  1419. element.addEventListener('mouseenter', clearTimeout.bind(window, timer), {once: true});
  1420. };
  1421. let screenX, screenY, a, b, c, d, tx, ty;
  1422. element.classList.add('draggable');
  1423. element.addEventListener('mousedown', mousedown);
  1424. };
  1425. const log = function(){
  1426. if(!DEBUG) return;
  1427. let l = log.last = log.now || new Date(), n = log.now = new Date();
  1428. let error = new Error(), line = log.format.getLine(error), callers = log.format.getCallers(error);
  1429. //console.log(error.stack);
  1430. console.log(
  1431. SCRIPTID + ':',
  1432. /* 00:00:00.000 */ n.toLocaleTimeString() + '.' + n.getTime().toString().slice(-3),
  1433. /* +0.000s */ '+' + ((n-l)/1000).toFixed(3) + 's',
  1434. /* :00 */ ':' + line,
  1435. /* caller.caller */ (callers[2] ? callers[2] + '() => ' : '') +
  1436. /* caller */ (callers[1] || '') + '()',
  1437. ...arguments
  1438. );
  1439. };
  1440. log.formats = [{
  1441. name: 'Firefox Scratchpad',
  1442. detector: /MARKER@Scratchpad/,
  1443. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1444. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1445. }, {
  1446. name: 'Firefox Console',
  1447. detector: /MARKER@debugger/,
  1448. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1449. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1450. }, {
  1451. name: 'Firefox Greasemonkey 3',
  1452. detector: /\/gm_scripts\//,
  1453. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1454. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1455. }, {
  1456. name: 'Firefox Greasemonkey 4+',
  1457. detector: /MARKER@user-script:/,
  1458. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 500,
  1459. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1460. }, {
  1461. name: 'Firefox Tampermonkey',
  1462. detector: /MARKER@moz-extension:/,
  1463. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 6,
  1464. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1465. }, {
  1466. name: 'Chrome Console',
  1467. detector: /at MARKER \(<anonymous>/,
  1468. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1],
  1469. getCallers: (e) => e.stack.match(/[^ ]+(?= \(<anonymous>)/gm),
  1470. }, {
  1471. name: 'Chrome Tampermonkey',
  1472. detector: /at MARKER \(chrome-extension:.*?\/userscript.html\?id=/,
  1473. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)?$/)[1] - 3,
  1474. getCallers: (e) => e.stack.match(/[^ ]+(?= \(chrome-extension:)/gm),
  1475. }, {
  1476. name: 'Edge Console',
  1477. detector: /at MARKER \(eval/,
  1478. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1],
  1479. getCallers: (e) => e.stack.match(/[^ ]+(?= \(eval)/gm),
  1480. }, {
  1481. name: 'Edge Tampermonkey',
  1482. detector: /at MARKER \(Function/,
  1483. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1] - 4,
  1484. getCallers: (e) => e.stack.match(/[^ ]+(?= \(Function)/gm),
  1485. }, {
  1486. name: 'Safari',
  1487. detector: /^MARKER$/m,
  1488. getLine: (e) => 0,/*e.lineが用意されているが最終呼び出し位置のみ*/
  1489. getCallers: (e) => e.stack.split('\n'),
  1490. }, {
  1491. name: 'Default',
  1492. detector: /./,
  1493. getLine: (e) => 0,
  1494. getCallers: (e) => [],
  1495. }];
  1496. log.format = log.formats.find(function MARKER(f){
  1497. if(!f.detector.test(new Error().stack)) return false;
  1498. //console.log('//// ' + f.name + '\n' + new Error().stack);
  1499. return true;
  1500. });
  1501. core.initialize();
  1502. if(window === top && console.timeEnd) console.timeEnd(SCRIPTID);
  1503. })();

QingJ © 2025

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