VRChat Web Pages Extender

Add features into VRChat Web Pages and improve user experience.

目前为 2022-06-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name VRChat Web Pages Extender
  3. // @name:ja VRChat Webページ拡張
  4. // @description Add features into VRChat Web Pages and improve user experience.
  5. // @description:ja VRChatのWebページに機能を追加し、また使い勝手を改善します。
  6. // @namespace https://greasyfork.org/users/137
  7. // @version 2.9.0
  8. // @match https://www.vrchat.com/*
  9. // @match https://vrchat.com/*
  10. // @match https://api.vrchat.cloud/*
  11. // @require https://greasyfork.org/scripts/19616/code/utilities.js?version=895049
  12. // @license MPL-2.0
  13. // @contributionURL https://pokemori.booth.pm/items/969835
  14. // @compatible Edge
  15. // @compatible Firefox Firefoxを推奨 / Firefox is recommended
  16. // @compatible Opera
  17. // @compatible Chrome
  18. // @grant dummy
  19. // @run-at document-start
  20. // @icon https://images.squarespace-cdn.com/content/v1/5f0770791aaf57311515b23d/1599678606410-4QMTB25DHF87E8EFFKXY/ke17ZwdGBToddI8pDm48kGfiFqkITS6axXxhYYUCnlRZw-zPPgdn4jUwVcJE1ZvWQUxwkmyExglNqGp0IvTJZUJFbgE-7XRK3dMEBRBhUpxQ1ibo-zdhORxWnJtmNCajDe36aQmu-4Z4SFOss0oowgxUaachD66r8Ra2gwuBSqM/favicon.ico
  21. // @author 100の人
  22. // @homepageURL https://greasyfork.org/ja/scripts/371331-vrchat-web-pages-extender
  23. // ==/UserScript==
  24.  
  25. 'use strict';
  26.  
  27. // L10N
  28. Gettext.setLocalizedTexts({
  29. /*eslint-disable quote-props, max-len */
  30. 'en': {
  31. 'エラーが発生しました': 'Error occurred',
  32. '$LENGTH$ 文字まで表示可能です。': 'This text is displayed up to $LENGTH$ characters.',
  33. },
  34. /*eslint-enable quote-props, max-len */
  35. });
  36.  
  37. Gettext.setLocale(navigator.language);
  38.  
  39.  
  40.  
  41. if (typeof content !== 'undefined') {
  42. // For Greasemonkey 4
  43. fetch = content.fetch.bind(content); //eslint-disable-line no-global-assign, no-native-reassign, no-undef
  44. }
  45.  
  46.  
  47.  
  48. /**
  49. * ページ上部にエラー内容を表示します。
  50. * @param {Error} exception
  51. * @returns {void}
  52. */
  53. function showError(exception)
  54. {
  55. console.error(exception);
  56. try {
  57. const errorMessage = _('エラーが発生しました') + ': ' + exception
  58. + ('stack' in exception ? '\n\n' + exception.stack : '');
  59. const homeContent = document.getElementsByClassName('home-content')[0];
  60. if (homeContent) {
  61. homeContent.firstElementChild.firstElementChild.insertAdjacentHTML('afterbegin', h`<div class="row">
  62. <div class="alert alert-danger fade show" role="alert"
  63. style="white-space: pre-wrap; font-size: 1rem; font-weight: normal;">${errorMessage}</div>
  64. </div>`);
  65. } else {
  66. alert(errorMessage);
  67. }
  68. } catch (e) {
  69. alert(_('エラーが発生しました') + ': ' + e);
  70. }
  71. }
  72.  
  73. const ID = 'vrchat-web-pages-extender-137';
  74.  
  75. /**
  76. * 一度に取得できる最大の要素数。
  77. * @constant {number}
  78. */
  79. const MAX_ITEMS_COUNT = 100;
  80.  
  81. /**
  82. * Statusの種類。
  83. * @constant {number}
  84. */
  85. const STATUSES = {
  86. 'join me': {
  87. label: 'Join Me: Auto-accept join requests.',
  88. color: '--status-joinme',
  89. },
  90. active: {
  91. label: 'Online: See join requests.',
  92. color: '--status-online',
  93. },
  94. 'ask me': {
  95. label: 'Ask Me: Hide location, see join requests.',
  96. color: '--status-askme',
  97. },
  98. busy: {
  99. label: 'Do Not Disturb: Hide location, hide join requests.',
  100. color: '--status-busy',
  101. },
  102. };
  103.  
  104. /**
  105. * Status Descriptionの最大文字数。
  106. * @constant {number}
  107. */
  108. const MAX_STATUS_DESCRIPTION_LENGTH = 32;
  109.  
  110. /**
  111. * 一つのブックマークグループの最大登録数。
  112. * @constant {number}
  113. */
  114. const MAX_FAVORITES_COUNT_PER_GROUP = 64;
  115.  
  116. /**
  117. * @type {Function}
  118. * @access private
  119. */
  120. let resolveUserDetails;
  121.  
  122. /**
  123. * @type {Promise.<Object>}
  124. * @access private
  125. */
  126. const userDetails = new Promise(function (resolve) {
  127. resolveUserDetails = resolve;
  128. });
  129.  
  130. addEventListener('message', function receiveUserDetails(event) {
  131. if (event.origin !== location.origin || typeof event.data !== 'object' || event.data === null
  132. || event.data.id !== ID || !event.data.userDetails) {
  133. return;
  134. }
  135. event.currentTarget.removeEventListener(event.type, receiveUserDetails);
  136.  
  137. resolveUserDetails(event.data.userDetails);
  138. });
  139.  
  140. /**
  141. * ログインしているユーザーの情報を取得します。
  142. * @see [User Info — VRChat API Documentation]{@link https://vrchatapi.github.io/#/UserAPI/CurrentUserDetails}
  143. * @returns {Promise.<?Object.<(string|string[]|boolean|number|Object)>>}
  144. */
  145. async function getUserDetails()
  146. {
  147. return await userDetails;
  148. }
  149.  
  150. /**
  151. * JSONファイルをオブジェクトとして取得します。
  152. * @param {string} url
  153. * @returns {Promise.<(Object|Array)>} OKステータスでなければ失敗します。
  154. */
  155. async function fetchJSON(url)
  156. {
  157. const response = await fetch(url, {credentials: 'same-origin'});
  158. return response.ok
  159. ? response.json()
  160. : Promise.reject(new Error(`${response.status} ${response.statusText}\n${await response.text()}`));
  161. }
  162.  
  163. /**
  164. * スクリプトで扱うブックマークの種類。
  165. * @constant {string[]}
  166. */
  167. const FAVORITE_TYPES = ['friend', 'world'];
  168.  
  169. let favoriteTypeGroupsPairsPromise;
  170.  
  171. /**
  172. * ログインしているユーザーのfavoriteのグループ名を取得します。
  173. * @returns {Object.<Object.<string>[]>} {@link FAVORITE_TYPES}の要素をキーに持つ連想配列。
  174. */
  175. function getFavoriteTypeGroupsPairs()
  176. {
  177. if (!favoriteTypeGroupsPairsPromise) {
  178. favoriteTypeGroupsPairsPromise = fetchJSON('/api/1/favorite/groups', {credentials: 'same-origin'})
  179. .then(function (groups) {
  180. const favoriteTypeGroupsPairs = {};
  181. for (const group of groups.filter(group => FAVORITE_TYPES.includes(group.type))) {
  182. if (!(group.type in favoriteTypeGroupsPairs)) {
  183. favoriteTypeGroupsPairs[group.type] = {};
  184. }
  185. favoriteTypeGroupsPairs[group.type][group.name] = group.displayName;
  186. }
  187. return favoriteTypeGroupsPairs;
  188. });
  189. }
  190. return favoriteTypeGroupsPairsPromise;
  191. }
  192.  
  193. /**
  194. * @type {Promise.<Object.<(string|string[])[]>[]>}
  195. * @access private
  196. */
  197. let favorites;
  198.  
  199. /**
  200. * ブックマークを全件取得します。
  201. * @see [List Favorites — VRChat API Documentation]{@link https://vrchatapi.github.io/#/FavoritesAPI/ListAllFavorites}
  202. * @returns {Promise.<Object.<(string|string[])[]>[]>} {@link FAVORITE_TYPES}の要素をキーに持つ連想配列。
  203. */
  204. function getFavorites()
  205. {
  206. return favorites || (favorites = async function () {
  207. const allFavorites = { };
  208. for (const type of FAVORITE_TYPES) {
  209. allFavorites[type] = [];
  210. }
  211. let offset = 0;
  212. while (true) {
  213. const favorites
  214. = await fetchJSON(`/api/1/favorites/?n=${MAX_ITEMS_COUNT}&offset=${offset}`).catch(showError);
  215.  
  216. for (const favorite of favorites) {
  217. if (!FAVORITE_TYPES.includes(favorite.type)) {
  218. continue;
  219. }
  220. allFavorites[favorite.type].push(favorite);
  221. }
  222.  
  223. if (favorites.length < MAX_ITEMS_COUNT) {
  224. break;
  225. }
  226.  
  227. offset += favorites.length;
  228. }
  229. return allFavorites;
  230. }());
  231. }
  232.  
  233. /**
  234. * 「Edit Profile」ページに、ステータス文変更フォームを挿入します。
  235. * @returns {Promise.<void>}
  236. */
  237. async function insertUpdateStatusForm()
  238. {
  239. if ('update-status' in document.forms) {
  240. return;
  241. }
  242.  
  243. const sidebarStatus = document.querySelector('.leftbar .user-info h6 span[title]');
  244. const sidebarStatusDescription = document.querySelector('.leftbar .statusDescription small');
  245.  
  246. const templateCard = document.getElementById('name-change-submit').closest('.card');
  247. const card = templateCard.cloneNode(true);
  248. card.getElementsByClassName('card-header')[0].textContent = 'Status';
  249. const form = card.getElementsByTagName('form')[0];
  250. form.name = 'update-status';
  251. form.action = '/api/1/users/' + document.querySelector('[href*="/home/user/usr_"]').pathname.replace(/.+\//u, '');
  252.  
  253. const description = form.displayName;
  254. description.id = 'status-description';
  255. description.type = 'text';
  256. description.name = 'statusDescription';
  257. description.value = sidebarStatusDescription.textContent;
  258. description.placeholder = '';
  259. description.pattern = `.{0,${MAX_STATUS_DESCRIPTION_LENGTH}}`;
  260. description.title = _('$LENGTH$ 文字まで表示可能です。').replace('$LENGTH$', MAX_STATUS_DESCRIPTION_LENGTH);
  261. description.parentElement.getElementsByClassName('alert')[0].remove();
  262. const descriptionContainer = description.closest('.col-10');
  263. descriptionContainer.classList.replace('col-10', 'col');
  264.  
  265. descriptionContainer.parentElement.classList.add('mb-2');
  266. const statusContainer = descriptionContainer.previousElementSibling;
  267. statusContainer.outerHTML = '<div class="col-auto"><select name="status" class="form-control">'
  268. + Object.keys(STATUSES).map(status => h`<option value="${status}">⬤ ${STATUSES[status].label}</option>`)
  269. .join('')
  270. + '</select></div>';
  271. form.status.value = sidebarStatus.title;
  272. form.status.classList.add(form.status.value.replace(' ', '-'));
  273. form.status.addEventListener('change', function (event) {
  274. const classList = event.target.classList;
  275. classList.remove(...Object.keys(STATUSES).map(status => status.replace(' ', '-')));
  276. classList.add(event.target.value.replace(' ', '-'));
  277. });
  278.  
  279. const submit = form.getElementsByClassName('btn')[0];
  280. submit.id = 'status-change-submit';
  281. submit.textContent = 'Update Status';
  282. submit.disabled = false;
  283. form.addEventListener('submit', function (event) {
  284. event.preventDefault();
  285. for (const control of event.target) {
  286. control.disabled = true;
  287. }
  288.  
  289. const body = {};
  290. for (const element of event.target) {
  291. if (element.localName === 'button') {
  292. continue;
  293. }
  294. body[element.name] = element.value;
  295. }
  296.  
  297. fetch(event.target.action, {
  298. method: 'PUT',
  299. headers: {'content-type': 'application/json'},
  300. credentials: 'same-origin',
  301. body: JSON.stringify(body),
  302. })
  303. .then(async function (response) {
  304. if (!response.ok) {
  305. return Promise.reject(
  306. new Error(`${response.status} ${response.statusText}\n${await response.text()}`)
  307. );
  308. }
  309. sidebarStatus.classList.remove(...Object.keys(STATUSES).map(status => status.replace(' ', '-')));
  310. sidebarStatus.classList.add(event.target.status.value.replace(' ', '-'));
  311. sidebarStatus.title = event.target.status;
  312. sidebarStatusDescription.textContent = event.target.statusDescription.value;
  313. })
  314. .catch(showError)
  315. .then(function () {
  316. for (const control of event.target) {
  317. control.disabled = false;
  318. }
  319. });
  320. });
  321.  
  322. templateCard.parentElement.getElementsByClassName('card')[0].before(card, document.createElement('hr'));
  323. }
  324.  
  325. /**
  326. * ブックマーク登録/解除ボタンの登録数表示を更新します。
  327. * @param {string} type - 「user」「favorite」のいずれか。
  328. * @returns {Promise.<void>}
  329. */
  330. async function updateFavoriteCounts(type)
  331. {
  332. const counts = {};
  333. for (const favorite of (await getFavorites())[type]) {
  334. for (const tag of favorite.tags) {
  335. if (!(tag in counts)) {
  336. counts[tag] = 0;
  337. }
  338. counts[tag]++;
  339. }
  340. }
  341.  
  342. for (const button of document.getElementsByName('favorite-' + type)) {
  343. button.getElementsByClassName('count')[0].textContent = counts[button.value] || 0;
  344. }
  345. }
  346.  
  347. /**
  348. * ブックマーク登録/解除ボタンを追加します。
  349. * @param {string} type - {@link FAVOLITE_TYPES}のいずれかの要素。
  350. * @returns {Promise.<void>}
  351. */
  352. async function insertFavoriteButtons(type)
  353. {
  354. const homeContent = document.getElementsByClassName('home-content')[0];
  355. if (homeContent.querySelector('[aria-label="Private World Callout"]')) {
  356. // privateワールド
  357. return;
  358. }
  359.  
  360. const sibling = type === 'friend'
  361. ? homeContent.querySelector('[role="group"]')
  362. : homeContent.getElementsByClassName('justify-content-between flex-column flex-sm-row')[1];
  363. if (!sibling) {
  364. return;
  365. }
  366. const parent = sibling.closest('[class*="col-"]');
  367.  
  368. const result = /[a-z]+_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.exec(location.pathname);
  369. if (!result) {
  370. return;
  371. }
  372. const id = result[0];
  373.  
  374. const buttons = document.getElementsByName('favorite-' + type);
  375. if (type === 'friend' && !(await getUserDetails()).friends.includes(id) || buttons[0]) {
  376. return;
  377. }
  378.  
  379. const groupNameDisplayNamePairs = (await getFavoriteTypeGroupsPairs())[type];
  380. const groupNames = Object.keys(groupNameDisplayNamePairs);
  381. const button = parent.querySelector(`[name="favorite-${CSS.escape(type)}"][value="${CSS.escape(groupNames[0])}"]`);
  382. if (button) {
  383. // 多重挿入の防止
  384. if (type === 'world') {
  385. const buttonsParent = button.closest('[role="group"]');
  386. if (sibling.nextElementSibling !== buttonsParent) {
  387. sibling.after(buttonsParent);
  388. }
  389. }
  390. return;
  391. }
  392. sibling.insertAdjacentHTML('afterend', '<div role="group" class="w-100 btn-group-lg btn-group-vertical mt-4">'
  393. + groupNames.sort().map(tag => h`<button type="button"
  394. class="btn btn-secondary" name="favorite-${type}" value="${tag}" disabled="">
  395. <span aria-hidden="true" class="fa fa-star"></span>
  396. &#xA0;<span class="name">${groupNameDisplayNamePairs[tag]}</span>
  397. &#xA0;<span class="count">‒</span>⁄${MAX_FAVORITES_COUNT_PER_GROUP}
  398. </button>`).join('')
  399. + '</div>');
  400.  
  401. await updateFavoriteCounts(type);
  402.  
  403. const tags = [].concat(...(await getFavorites())[type]
  404. .filter(favorite => favorite.favoriteId === id)
  405. .map(favorite => favorite.tags));
  406.  
  407. for (const button of buttons) {
  408. button.dataset.id = id;
  409. if (tags.includes(button.value)) {
  410. button.classList.remove('btn-secondary');
  411. button.classList.add('btn-primary');
  412. }
  413. if (button.classList.contains('btn-primary')
  414. || button.getElementsByClassName('count')[0].textContent < MAX_FAVORITES_COUNT_PER_GROUP) {
  415. button.disabled = false;
  416. }
  417. }
  418.  
  419. buttons[0].closest('[role="group"]').addEventListener('click', async function (event) {
  420. const button = event.target.closest('button');
  421. if (!button || button.name !== 'favorite-' + type) {
  422. return;
  423. }
  424.  
  425. const buttons = document.getElementsByName('favorite-' + type);
  426. for (const button of buttons) {
  427. button.disabled = true;
  428. }
  429.  
  430. const id = button.dataset.id;
  431. const newTags = button.classList.contains('btn-secondary') ? [button.value] : [];
  432.  
  433. const favorites = (await getFavorites())[type];
  434. for (let i = favorites.length - 1; i >= 0; i--) {
  435. if (favorites[i].favoriteId === id) {
  436. await fetch(
  437. '/api/1/favorites/' + favorites[i].id,
  438. {method: 'DELETE', credentials: 'same-origin'}
  439. );
  440.  
  441. for (const button of buttons) {
  442. if (favorites[i].tags.includes(button.value)) {
  443. button.classList.remove('btn-primary');
  444. button.classList.add('btn-secondary');
  445. }
  446. }
  447.  
  448. favorites.splice(i, 1);
  449. }
  450. }
  451.  
  452. if (newTags.length > 0) {
  453. await fetch('/api/1/favorites', {
  454. method: 'POST',
  455. headers: { 'content-type': 'application/json' },
  456. credentials: 'same-origin',
  457. body: JSON.stringify({type, favoriteId: id, tags: newTags}),
  458. })
  459. .then(async response => response.ok ? response.json() : Promise.reject(
  460. new Error(`${response.status} ${response.statusText}\n${await response.text()}`)
  461. ))
  462. .then(function (favorite) {
  463. favorites.push(favorite);
  464. for (const button of buttons) {
  465. if (favorite.tags.includes(button.value)) {
  466. button.classList.remove('btn-secondary');
  467. button.classList.add('btn-primary');
  468. }
  469. }
  470. })
  471. .catch(showError);
  472. }
  473.  
  474. await updateFavoriteCounts(type);
  475.  
  476. for (const button of buttons) {
  477. if (button.getElementsByClassName('count')[0].textContent < MAX_FAVORITES_COUNT_PER_GROUP) {
  478. button.disabled = false;
  479. }
  480. }
  481. });
  482. }
  483.  
  484. /**
  485. * フレンド一覧で次のページが確実に存在しない場合、次ページのボタンを無効化します。
  486. * また、オンラインのフレンド数を表示します。
  487. * @param {HTMLDivElement} group 「friend-group」クラスを持つ要素。
  488. * @returns {void}
  489. */
  490. function improveFriendList(group)
  491. {
  492. // フレンド一覧で次のページが確実に存在しない場合、次ページのボタンを無効化します
  493. const pager = group.querySelector('.friend-group > div:last-of-type');
  494. const count = group.querySelectorAll('.friend-group > div:not(:last-of-type)').length;
  495. const nextPageButton = pager.getElementsByClassName('fa-angle-down')[0].closest('button');
  496. nextPageButton.disabled = count < MAX_ITEMS_COUNT;
  497.  
  498. // オンラインのフレンド数を表示します
  499. const heading = group.firstElementChild;
  500. if (heading.textContent.includes('Online')) {
  501. heading.textContent = `Online (${
  502. MAX_ITEMS_COUNT * (/[0-9]+/.exec(pager.getElementsByClassName('page')[0].textContent)[0] - 1)
  503. + count
  504. + (nextPageButton.disabled ? '' : '+')
  505. })`;
  506. }
  507. }
  508.  
  509. /**
  510. * ページ読み込み後に一度だけ実行する処理をすでに行っていれば `true`。
  511. * @type {boolean}
  512. * @access private
  513. */
  514. let headChildrenInserted = false;
  515.  
  516. new MutationObserver(async function (mutations) {
  517. if (document.head && !headChildrenInserted) {
  518. headChildrenInserted = true;
  519. document.head.insertAdjacentHTML('beforeend', `<style>
  520. /*====================================
  521. Edit Profile
  522. */
  523. ` + Object.keys(STATUSES).map(status => `
  524. [name="status"].${CSS.escape(status.replace(' ', '-'))},
  525. [name="status"] option[value=${CSS.escape(status)}] {
  526. color: var(${STATUSES[status].color});
  527. }
  528. `).join('') + `
  529.  
  530. /*====================================
  531. フレンドのユーザーページ
  532. */
  533. .btn[name^="favorite-"] {
  534. white-space: unset;
  535. }
  536. </style>`);
  537.  
  538. // ユーザー情報を取得します
  539. GreasemonkeyUtils.executeOnUnsafeContext(function (id) {
  540.  
  541. const responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  542. responseText.get = new Proxy(responseText.get, {
  543. apply(get, thisArgument, argumentList)
  544. {
  545. const responseText = Reflect.apply(get, thisArgument, argumentList);
  546. if (thisArgument.status === 200
  547. && new URL(thisArgument.responseURL).pathname === '/api/1/auth/user') {
  548. postMessage({ id, userDetails: JSON.parse(responseText) }, location.origin);
  549. }
  550. return responseText;
  551. },
  552. });
  553. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', responseText);
  554. }, [ ID ]);
  555. }
  556.  
  557. for (const mutation of mutations) {
  558. let parent = mutation.target;
  559. if (parent.id === 'home') {
  560. break;
  561. }
  562.  
  563. if (/* URLを開いたとき */ parent.localName === 'head' && document.body
  564. || /* ページを移動したとき */ parent.id === 'app' || parent.classList.contains('home-content')
  565. || parent.parentElement && parent.parentElement.classList.contains('home-content')) {
  566. const homeContent = document.getElementsByClassName('home-content')[0];
  567. if (!homeContent || homeContent.getElementsByClassName('fa-cog')[0]) {
  568. break;
  569. }
  570.  
  571. if (location.pathname === '/home/profile') {
  572. // 「Edit Profile」ページなら
  573. //await insertUpdateStatusForm();
  574. } else if (location.pathname.startsWith('/home/user/')) {
  575. // ユーザーページ
  576. await insertFavoriteButtons('friend');
  577. const displayName = document.getElementsByTagName('h2')[0].textContent;
  578. const name = document.getElementsByTagName('h3')[0].firstElementChild.firstChild.data;
  579. document.title = `${displayName} ${name} - VRChat`;
  580. } else if (location.pathname.startsWith('/home/world/')) {
  581. // ワールドページ
  582. await insertFavoriteButtons('world');
  583. const heading = document.querySelector('.home-content h2');
  584. const name = heading.firstChild.data;
  585. const author = heading.nextElementSibling.querySelector('[href^="/home/user/usr_"]').firstChild.data;
  586. document.title = `${name} By ${author} - VRChat`;
  587. }
  588. }
  589.  
  590. if (parent.classList.contains('friend-container')) {
  591. parent = mutation.addedNodes[0];
  592. }
  593.  
  594. if (parent.classList.contains('friend-group')) {
  595. let groups = document.getElementsByClassName('friend-group');
  596. const heading = groups[0].firstElementChild.textContent;
  597. if (groups.length === 1 || heading.includes('Online') && !heading.includes('(')) {
  598. groups = [parent];
  599. }
  600.  
  601. for (const group of groups) {
  602. improveFriendList(group);
  603. }
  604. break;
  605. }
  606. }
  607. }).observe(document, {childList: true, subtree: true});