osu!web enhancement

Some small improvements to osu!web, featuring beatmapset filter and profile page improvement.

当前为 2024-06-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name osu!web enhancement
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.6.12
  5. // @description Some small improvements to osu!web, featuring beatmapset filter and profile page improvement.
  6. // @author VoltaXTY
  7. // @match https://osu.ppy.sh/*
  8. // @match https://lazer.ppy.sh/*
  9. // @icon http://ppy.sh/favicon.ico
  10. // @grant none
  11. // @run-at document-end
  12. // ==/UserScript==
  13. // below are source code from http://i18njs.com/js/i18n.js
  14. (function() {
  15. var Translator, i18n, translator,
  16. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  17. Translator = (function() {
  18. function Translator() {
  19. this.translate = __bind(this.translate, this); this.data = {
  20. values: {},
  21. contexts: []
  22. };
  23. this.globalContext = {};
  24. }
  25. Translator.prototype.translate = function(text, defaultNumOrFormatting, numOrFormattingOrContext, formattingOrContext, context) {
  26. var defaultText, formatting, isObject, num;
  27. if (context == null) {
  28. context = this.globalContext;
  29. }
  30. isObject = function(obj) {
  31. var type;
  32. type = typeof obj;
  33. return type === "function" || type === "object" && !!obj;
  34. };
  35. if (isObject(defaultNumOrFormatting)) {
  36. defaultText = null;
  37. num = null;
  38. formatting = defaultNumOrFormatting;
  39. context = numOrFormattingOrContext || this.globalContext;
  40. } else {
  41. if (typeof defaultNumOrFormatting === "number") {
  42. defaultText = null;
  43. num = defaultNumOrFormatting;
  44. formatting = numOrFormattingOrContext;
  45. context = formattingOrContext || this.globalContext;
  46. } else {
  47. defaultText = defaultNumOrFormatting;
  48. if (typeof numOrFormattingOrContext === "number") {
  49. num = numOrFormattingOrContext;
  50. formatting = formattingOrContext;
  51. context = context;
  52. } else {
  53. num = null;
  54. formatting = numOrFormattingOrContext;
  55. context = formattingOrContext || this.globalContext;
  56. }
  57. }
  58. }
  59. if (isObject(text)) {
  60. if (isObject(text['i18n'])) {
  61. text = text['i18n'];
  62. }
  63. return this.translateHash(text, context);
  64. } else {
  65. return this.translateText(text, num, formatting, context, defaultText);
  66. }
  67. };
  68. Translator.prototype.add = function(d) {
  69. var c, k, v, _i, _len, _ref, _ref1, _results;
  70. if ((d.values != null)) {
  71. _ref = d.values;
  72. for (k in _ref) {
  73. v = _ref[k];
  74. this.data.values[k] = v;
  75. }
  76. }
  77. if ((d.contexts != null)) {
  78. _ref1 = d.contexts;
  79. _results = [];
  80. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  81. c = _ref1[_i];
  82. _results.push(this.data.contexts.push(c));
  83. }
  84. return _results;
  85. }
  86. };
  87. Translator.prototype.setContext = function(key, value) {
  88. return this.globalContext[key] = value;
  89. };
  90. Translator.prototype.clearContext = function(key) {
  91. return this.lobalContext[key] = null;
  92. };
  93. Translator.prototype.reset = function() {
  94. this.data = {
  95. values: {},
  96. contexts: []
  97. };
  98. return this.globalContext = {};
  99. };
  100. Translator.prototype.resetData = function() {
  101. return this.data = {
  102. values: {},
  103. contexts: []
  104. };
  105. };
  106. Translator.prototype.resetContext = function() {
  107. return this.globalContext = {};
  108. };
  109. Translator.prototype.translateHash = function(hash, context) {
  110. var k, v;
  111.  
  112. for (k in hash) {
  113. v = hash[k];
  114. if (typeof v === "string") {
  115. hash[k] = this.translateText(v, null, null, context);
  116. }
  117. }
  118. return hash;
  119. };
  120. Translator.prototype.translateText = function(text, num, formatting, context, defaultText) {
  121. var contextData, result;
  122. if (context == null) { context = this.globalContext; }
  123. if (this.data == null) { return this.useOriginalText(defaultText || text, num, formatting); }
  124. contextData = this.getContextData(this.data, context);
  125. if (contextData != null) { result = this.findTranslation(text, num, formatting, contextData.values, defaultText); }
  126. if (result == null) { result = this.findTranslation(text, num, formatting, this.data.values, defaultText); }
  127. if (result == null) { return this.useOriginalText(defaultText || text, num, formatting); }
  128. return result;
  129. };
  130. Translator.prototype.findTranslation = function(text, num, formatting, data) {
  131. var result, triple, value, _i, _len;
  132. value = data[text];
  133. if (value == null) { return null; }
  134. if (num == null) {
  135. if (typeof value === "string") { return this.applyFormatting(value, num, formatting); }
  136. } else {
  137. if (value instanceof Array || value.length) {
  138. for (_i = 0, _len = value.length; _i < _len; _i++) {
  139. triple = value[_i];
  140. if ((num >= triple[0] || triple[0] === null) && (num <= triple[1] || triple[1] === null)) {
  141. result = this.applyFormatting(triple[2].replace("-%n", String(-num)), num, formatting);
  142. return this.applyFormatting(result.replace("%n", String(num)), num, formatting);
  143. }
  144. }
  145. }
  146. }
  147. return null;
  148. };
  149. Translator.prototype.getContextData = function(data, context) {
  150. var c, equal, key, value, _i, _len, _ref, _ref1;
  151. if (data.contexts == null) { return null; }
  152. _ref = data.contexts;
  153. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  154. c = _ref[_i];
  155. equal = true;
  156. _ref1 = c.matches;
  157. for (key in _ref1) {
  158. value = _ref1[key];
  159. equal = equal && value === context[key];
  160. }
  161. if (equal) { return c; }
  162. }
  163. return null;
  164. };
  165. Translator.prototype.useOriginalText = function(text, num, formatting) {
  166. if (num == null) {
  167. return this.applyFormatting(text, num, formatting);
  168. }
  169. return this.applyFormatting(text.replace("%n", String(num)), num, formatting);
  170. };
  171. Translator.prototype.applyFormatting = function(text, num, formatting) {
  172. var ind, regex;
  173. for (ind in formatting) {
  174. regex = new RegExp("%{" + ind + "}", "g");
  175. text = text.replace(regex, formatting[ind]);
  176. }
  177. return text;
  178. };
  179. return Translator;
  180. })();
  181. translator = new Translator();
  182. i18n = translator.translate;
  183. i18n.translator = translator;
  184. i18n.create = function(data) {
  185. var trans;
  186. trans = new Translator();
  187. if (data != null) {
  188. trans.add(data);
  189. }
  190. trans.translate.create = i18n.create;
  191. return trans.translate;
  192. };
  193. (typeof module !== "undefined" && module !== null ? module.exports = i18n : void 0) || (this.i18n = i18n);
  194. }).call(this);
  195. // end of code from http://i18njs.com/js/i18n.js
  196. const ShowPopup = (m, t = "info") => {
  197. window.popup(m, t);
  198. [["info", console.log], ["warning", console.warn], ["danger", console.error]].find(g => g[0] === t)[1](m);
  199. }
  200. const svg_osu_miss = URL.createObjectURL(new Blob(
  201. [`<svg viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  202. <filter id="blur">
  203. <feFlood flood-color="red" flood-opacity="0.5" in="SourceGraphic" />
  204. <feComposite operator="in" in2="SourceGraphic" />
  205. <feGaussianBlur stdDeviation="6" />
  206. <feComponentTransfer result="glow1"> <feFuncA type="linear" slope="10" intercept="0" /> </feComponentTransfer>
  207. <feGaussianBlur in="glow1" stdDeviation="1" result="glow2" />
  208. <feMerge> <feMergeNode in="SourceGraphic" /> <feMergeNode in="glow2" /> </feMerge>
  209. </filter>
  210. <filter id="blur2"> <feGaussianBlur stdDeviation="0.2"/> </filter>
  211. <path id="cross" d="M 26 16 l -10 10 l 38 38 l -38 38 l 10 10 l 38 -38 l 38 38 l 10 -10 l -38 -38 l 38 -38 l -10 -10 l -38 38 Z" />
  212. <use href="#cross" stroke="red" stroke-width="2" fill="transparent" filter="url(#blur)"/>
  213. <use href="#cross" fill="white" stroke="transparent" filter="url(#blur2)"/>
  214. </svg>`], {type: "image/svg+xml"}));
  215. const svg_green_tick = URL.createObjectURL(new Blob([
  216. `<svg viewBox="0 0 18 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  217. <polyline points="2,8 7,14 16,2" stroke="#62ee56" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
  218. </svg>`], {type: "image/svg+xml"}));
  219. const inj_style =
  220. `#osu-db-input{
  221. display: none;
  222. }
  223. .osu-db-button{
  224. align-items: center;
  225. padding: 10px;
  226. }
  227. .osu-db-button:hover{
  228. cursor: pointer;
  229. }
  230. .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu-container{
  231. background-color: #87dda8;
  232. }
  233. .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu .fa-file-download, .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu .fa-heart{
  234. color: #5c9170;
  235. }
  236. .owned-beatmap-link{
  237. color: #87dda8;
  238. }
  239. .play-detail__accuracy{
  240. margin: 0px 12px;
  241. }
  242. .play-detail__accuracy.ppAcc{
  243. color: #8ef9f1;
  244. padding: 0;
  245. }
  246. .play-detail__weighted-pp{
  247. margin: 0px;
  248. }
  249. .play-detail__pp{
  250. flex-direction: column;
  251. }
  252. .lost-pp{
  253. font-size: 10px;
  254. position: relative;
  255. right: 7px;
  256. font-weight: 600;
  257. }
  258. .score-detail{
  259. display: inline-block;
  260. }
  261. .score-detail-data-text{
  262. margin-left: 5px;
  263. margin-right: 10px;
  264. width: auto;
  265. display: inline-block;
  266. }
  267. @keyframes rainbow{
  268. 0%{
  269. color: #be19ff;
  270. }
  271. 25%{
  272. color: #0075ff;
  273. }
  274. 50%{
  275. color: #4ddf86;
  276. }
  277. 75%{
  278. color: #e9ea00;
  279. }
  280. 100%{
  281. color: #ff7800;
  282. }
  283. }
  284. .play-detail__accuracy-and-weighted-pp{
  285. display: flex;
  286. flex-direction: row;
  287. }
  288. .play-detail__before{
  289. flex-grow: 1;
  290. }
  291. .mania-max{
  292. animation: 0.16s infinite alternate rainbow;
  293. }
  294. .mania-300{
  295. color: #fbff00;
  296. }
  297. .osu-100, .fruits-100, .taiko-150{
  298. color: #67ff5b;
  299. }
  300. .mania-200{
  301. color: #6cd800;
  302. }
  303. .osu-300, .fruits-300, .taiko-300{
  304. color: #7dfbff;
  305. }
  306. .mania-100{
  307. color: #257aea;
  308. }
  309. .mania-50{
  310. color: #d2d2d2;
  311. }
  312. .osu-50, .fruits-50-miss{
  313. color: #ffbf00;
  314. }
  315. .mania-miss, .taiko-miss, .fruits-miss{
  316. color: #cc2626;
  317. }
  318. .mania-max, .mania-300, .mania-200, .mania-100, .mania-50, .mania-miss, .osu-300, .osu-100, .osu-50, .osu-miss{
  319. font-weight: 600;
  320. }
  321. .score-detail-data-text{
  322. font-weight: 500;
  323. }
  324. .osu-miss{
  325. display: inline-block;
  326. }
  327. .osu-miss > img{
  328. width: 14px;
  329. height: 14px;
  330. bottom: 1px;
  331. position: relative;
  332. }
  333. .play-detail__Accuracy, .play-detail__Accuracy2, .combo, .max-combo, .play-detail__combo{
  334. display: inline-block;
  335. width: auto;
  336. }
  337. .play-detail__Accuracy{
  338. text-align: left;
  339. color: #fc2;
  340. }
  341. .play-detail__Accuracy2{
  342. text-align: left;
  343. color: rgb(142, 249, 241);
  344. }
  345. .play-detail__combo, .play-detail__Accuracy2, .play-detail__Accuracy{
  346. margin-right: 13px;
  347. }
  348. .play-detail__combo{
  349. text-align: right;
  350. }
  351. .combo, .max-combo{
  352. margin: 0px 1px;
  353. }
  354. .max-combo, .legacy-perfect-combo{
  355. color: hsl(var(--hsl-lime-1));
  356. }
  357. div.bar__exp-info{
  358. position: relative;
  359. bottom: 100%;
  360. }
  361. .play-detail__group--background, .beatmap-playcount__background{
  362. position: absolute;
  363. width: 90%;
  364. height: 100%;
  365. left: 0px;
  366. margin: 0px;
  367. pointer-events: none;
  368. z-index: 1;
  369. border-radius: 10px 0px 0px 10px;
  370. background-size: cover;
  371. background-position-y: -100%;
  372. mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
  373. -webkit-mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
  374. }
  375. @media(max-width: 900px){
  376. .play-detail__group--background, .beatmap-playcount__background{
  377. background-position-y: 0%;
  378. mask-image: linear-gradient(to bottom, #0007, #0004);
  379. -webkit-mask-image: linear-gradient(to bottom, #0007, #0004);
  380. width: 100%;
  381. }
  382. .lost-pp{
  383. left: 3px;
  384. }
  385. .play-detail__group.play-detail__group--bottom{
  386. z-index: 1;
  387. }
  388. .play-detail__before{
  389. flex-grow: 0;
  390. }
  391. }
  392. .play-detail.play-detail--highlightable.play-detail--pin-sortable.js-score-pin-sortable .play-detail__group--background{
  393. left: 20px;
  394. }
  395. .beatmap-playcount__background{
  396. width: 100%;
  397. border-radius: 6px;
  398. mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.3));
  399. -webkit-mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.3));
  400. }
  401. .beatmap-playcount__info, .beatmap-playcount__detail-count, .play-detail__group.play-detail__group--top *{
  402. z-index: 1;
  403. }
  404. div.play-detail-list time.js-timeago, span.beatmap-playcount__mapper, span.beatmap-playcount__mapper > a{
  405. color: #ccc;
  406. }
  407. button.show-more-link{
  408. z-index: 4;
  409. }
  410. a.beatmap-download-link{
  411. margin: 0px 5px;
  412. color: hsl(var(--hsl-l1));
  413. }
  414. a.beatmap-download-link:hover, a.beatmap-pack-item-download-link span:hover{
  415. color: #fff;
  416. }
  417. a.beatmap-pack-item-download-link span{
  418. color: hsl(var(--hsl-l1));
  419. }
  420. .play-detail.play-detail--highlightable.audio-player{
  421. max-width: none;
  422. height: unset;
  423. padding: unset;
  424. align-items: unset;
  425. }
  426. .play-detail.play-detail--highlightable.audio-player__button{
  427. align-items: unset;
  428. padding: unset;
  429. }
  430. .play-detail.play-detail--highlightable.audio-player__button:hover{
  431. color: unset;
  432. }
  433. .sort-detail__items{
  434. display: flex;
  435. align-items: center;
  436. flex-wrap: wrap;
  437. }
  438. .sort-detail__item{
  439. border-radius: 4px;
  440. margin: 5px;
  441. }
  442. `;
  443. const scriptContent =
  444. String.raw`console.log("page script injected from osu!web enhancement");
  445. if(window.oldXHROpen === undefined){
  446. window.oldXHROpen = window.XMLHttpRequest.prototype.open;
  447. window.XMLHttpRequest.prototype.open = function() {
  448. this.addEventListener("load", function() {
  449. const url = this.responseURL;
  450. const trreg = /https:\/\/(?<subdomain>osu|lazer)\.ppy\.sh\/users\/(?<id>[0-9]+)\/extra-pages\/(?<type>top_ranks|historical)\?mode=(?<mode>osu|taiko|fruits|mania)/.exec(url);
  451. const adreg = /https:\/\/(?<subdomain>osu|lazer)\.ppy\.sh\/users\/(?<id>[0-9]+)\/scores\/(?<type>firsts|best|recent|pinned)\?mode=(?<mode>osu|taiko|fruits|mania)&limit=[0-9]*&offset=[0-9]*/.exec(url);
  452. let reg = trreg ?? (adreg ?? null);
  453. if(!reg){
  454. const bmsreg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/search\?/;
  455. return;
  456. }
  457. let info = {
  458. type: reg.groups.type,
  459. userId: Number(reg.groups.id),
  460. mode: reg.groups.mode,
  461. subdomain: reg.groups.subdomain,
  462. };
  463. const responseBody = this.responseText;
  464. info.data = JSON.parse(responseBody);
  465. info.id = "osu!web enhancement";
  466. window.postMessage(info, "*");
  467. });
  468. return oldXHROpen.apply(this, arguments);
  469. };
  470. }`;
  471. const locales = {
  472. "en": {
  473. "values": {
  474. "Owned": "Owned",
  475. "Download": "Download",
  476. "pp Accuracy": "pp Accuracy",
  477. "V1 Accuracy": "V1 Accuracy",
  478. "V2 Accuracy": "V2 Accuracy",
  479. "Lazer Accuracy": "Lazer Accuracy",
  480. "Combo": "Combo",
  481. "Combo/Max Combo": "Combo/Max Combo",
  482. "Import osu!.db": "Import osu!.db",
  483. "Check for update": "Check for update",
  484. "Calculate pp Gini index": "Calculate pp Gini index",
  485. "Go to GreasyFork page": "Go to GreasyFork page",
  486. "Copy Text Details": "Copy Text Details",
  487. "Could not find best play data": "Could not find best play data",
  488. "The latest version is already installed!": "The latest version is already installed!",
  489. "Script is already busy reading a osu!.db file.": "Script is already busy reading a osu!.db file.",
  490. "There are still remaining unread bytes, something may be wrong.": "There are still remaining unread bytes, something may be wrong.",
  491. "Score details copied to clipboard!": "Score details copied to clipboard!",
  492. "%{pc} of total pp": "%{pc} of total pp",
  493. "Your pp Gini index of bp%{bp} is %{val}.": "Your pp Gini index of bp%{bp} is %{val}.",
  494. "Finished reading osu!.db in %{time} ms.": "Finished reading osu!.db in %{time} ms.",
  495. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  496. "Unable to copy score detail to clipboard, check console for more info.": "Unable to copy score detail to clipboard, check console for more info.",
  497. "Show bp analytic": "Show bp analytic",
  498. "Close bp analytic": "Close bp analytic",
  499. }
  500. },
  501. "zh": {
  502. "values": {
  503. "Owned": "已获得",
  504. "Download": "下载",
  505. "pp Accuracy": "pp-准确度",
  506. "V1 Accuracy": "V1-准确度",
  507. "V2 Accuracy": "V2-准确度",
  508. "Lazer Accuracy": "Lazer-准确度",
  509. "Combo": "连击数",
  510. "Combo/Max Combo": "连击数/最大连击数",
  511. "Import osu!.db": "读取 osu!.db",
  512. "Check for update": "检查更新",
  513. "Calculate pp Gini index": "计算 pp 基尼指数",
  514. "Go to GreasyFork page": "前往 GreasyFork 页面",
  515. "Copy Text Details": "复制文本信息",
  516. "Could not find best play data": "无法获取 BP 数据",
  517. "The latest version is already installed!": "已安装最新版本!",
  518. "Script is already busy reading a osu!.db file.": "脚本已经开始读取 osu!.db 文件。",
  519. "There are still remaining unread bytes, something may be wrong.": "部分数据未能读取,可能发生错误。",
  520. "Score details copied to clipboard!": "分数信息已复制到剪贴板!",
  521. "%{pc} of total pp": "占总 pp 的 %{pc}",
  522. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指数为 %{val}。",
  523. "Finished reading osu!.db in %{time} ms.": "osu!.db 读取完毕,用时 %{time}ms。",
  524. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  525. }
  526. },
  527. "zh-tw": {
  528. "values": {
  529. "Owned": "已獲得",
  530. "Download": "下載",
  531. "pp Accuracy": "pp-準確度",
  532. "V1 Accuracy": "V1-準確度",
  533. "V2 Accuracy": "V2-準確度",
  534. "Lazer Accuracy": "Lazer-準確度",
  535. "Combo": "連擊數",
  536. "Combo/Max Combo": "連擊數/最大連擊數",
  537. "Import osu!.db": "讀取 osu!.db",
  538. "Check for update": "檢查更新",
  539. "Calculate pp Gini index": "計算 pp 基尼指數",
  540. "Go to GreasyFork page": "前往 GreasyFork 頁面",
  541. "Copy Text Details": "複製文字訊息",
  542. "Could not find best play data": "无法獲取 BP 數據",
  543. "The latest version is already installed!": "已安裝最新版本!",
  544. "Script is already busy reading a osu!.db file.": "腳本已經開始讀取 osu!.db 文件。",
  545. "There are still remaining unread bytes, something may be wrong.": "部分數據未能讀取,可能發生錯誤。",
  546. "Score details copied to clipboard!": "分數訊息已複製到剪貼簿!",
  547. "%{pc} of total pp": "佔總 pp 的 %{pc}",
  548. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指數為 %{val}。",
  549. "Finished reading osu!.db in %{time} ms.": "osu!.db 讀取完畢,用時 %{time}ms。",
  550. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  551. }
  552. },
  553. "ja": {
  554. "values": {
  555. "Owned": "取得済み",
  556. "Download": "ダウンロード",
  557. "pp Accuracy": "pp-精度",
  558. "V1 Accuracy": "V1-精度",
  559. "V2 Accuracy": "V2-精度",
  560. "Lazer Accuracy": "Lazer-精度",
  561. "Combo": "コンボ数",
  562. "Combo/Max Combo": "コンボ数/最大コンボ数",
  563. "Import osu!.db": "osu!.db を読み取る",
  564. "Check for update": "更新を確認する",
  565. "Calculate pp Gini index": "pp のジニ指数の計算",
  566. "Go to GreasyFork page": "GreasyFork のページへ",
  567. "Copy Text Details": "詳細をテキストにコピー",
  568. "Could not find best play data": "BP データが見つからない",
  569. "The latest version is already installed!": "最新版は既にインストールされている!",
  570. "Script is already busy reading a osu!.db file.": "スクリプトは osu!.db ファイルの読み取りを既に始める。",
  571. "There are still remaining unread bytes, something may be wrong.": "一部のデータを読み取れません、多分何かの間違いだ。",
  572. "Score details copied to clipboard!": "スコア詳細をクリップボードにコピー!",
  573. "%{pc} of total pp": "全 pp の %{pc}",
  574. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} の pp ジニ指数は %{val} です。",
  575. "Finished reading osu!.db in %{time} ms.": "osu!.db の読み取りを %{time}ms で完了しました。",
  576. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  577. }
  578. }
  579. };
  580. const scriptId = "osu-web-enhancement-XHR-script";
  581. if(!document.querySelector(`script#${scriptId}`)){
  582. const script = document.createElement("script");
  583. script.textContent = scriptContent;
  584. document.body.appendChild(script);
  585. }
  586. const persistentEventListeners = new Map();
  587. const HTML = (tagname, attrs, ...children) => {
  588. if(attrs === undefined) return document.createTextNode(tagname);
  589. const ele = document.createElement(tagname);
  590. if(attrs) for(const [key, value] of Object.entries(attrs)){
  591. if(value === null || value === undefined) continue;
  592. if(key.charAt(0) === "_"){
  593. const type = key.slice(1);
  594. ele.addEventListener(type, value);
  595. }
  596. else if(key.charAt(0) === "#" && ele.getAttribute("id") !== null){
  597. const type = key.slice(1);
  598. persistentEventListeners.set(ele.getAttribute("id"), {type: type, value: value});
  599. ele.addEventListener(type, value);
  600. }
  601. else if(key === "eventListener"){
  602. for(const listener of value){
  603. ele.addEventListener(listener.type, listener.listener, listener.options);
  604. }
  605. }
  606. else ele.setAttribute(key, value);
  607. }
  608. for(const child of children) if(child) ele.append(child);
  609. return ele;
  610. };
  611. const html = (html) => {
  612. const t = document.createElement("template");
  613. t.innerHTML = html;
  614. return t.content.firstElementChild;
  615. };
  616. const OsuMod = {
  617. NoFail: 1 << 0,
  618. Easy: 1 << 1,
  619. TouchDevice: 1 << 2,
  620. NoVideo: 1 << 2,
  621. Hidden: 1 << 3,
  622. HardRock: 1 << 4,
  623. SuddenDeath: 1 << 5,
  624. DoubleTime: 1 << 6,
  625. Relax: 1 << 7,
  626. HalfTime: 1 << 8,
  627. Nightcore: 1 << 9, // always with DT
  628. Flashlight: 1 << 10,
  629. Autoplay: 1 << 11,
  630. SpunOut: 1 << 12,
  631. Autopilot: 1 << 13,
  632. Perfect: 1 << 14,
  633. Key4: 1 << 15,
  634. Key5: 1 << 16,
  635. Key6: 1 << 17,
  636. Key7: 1 << 18,
  637. Key8: 1 << 19,
  638. KeyMod: 1 << 19 | 1 << 18 | 1 << 17 | 1 << 16 | 1 << 15,
  639. FadeIn: 1 << 20,
  640. Random: 1 << 21,
  641. Cinema: 1 << 22,
  642. TargetPractice: 1 << 23,
  643. Key9: 1 << 24,
  644. Coop: 1 << 25,
  645. Key1: 1 << 26,
  646. Key3: 1 << 27,
  647. Key2: 1 << 28,
  648. ScoreV2: 1 << 29,
  649. Mirror: 1 << 30,
  650. };
  651. const Byte = (arr, iter) => {
  652. return arr[iter.nxtpos++];
  653. }
  654. const RankedStatus = (arr, iter) => {
  655. const r = {value: Byte(arr, iter), description: ""};
  656. switch(r.value){
  657. case 1: r.description = "unsubmitted"; break;
  658. case 2: r.description = "pending/wip/graveyard"; break;
  659. case 3: r.description = "unused"; break;
  660. case 4: r.description = "ranked"; break;
  661. case 5: r.description = "approved"; break;
  662. case 6: r.description = "qualified"; break;
  663. case 7: r.description = "loved"; break;
  664. default: r.description = "unknown"; r.value = 0;
  665. }
  666. return r;
  667. };
  668. const OsuMode = (arr, iter) => {
  669. const r = {value: Byte(arr, iter), description: ""};
  670. switch(r.value){
  671. case 1: r.description = "taiko"; break;
  672. case 2: r.description = "catch"; break;
  673. case 3: r.description = "mania"; break;
  674. default: r.value = 0; r.description = "osu";
  675. }
  676. return r;
  677. };
  678. const Grade = (arr, iter) => {
  679. const r = {value: Byte(arr, iter), description: ""};
  680. switch(r.value){
  681. case 0: r.description = "SSH"; break;
  682. case 1: r.description = "SH"; break;
  683. case 2: r.description = "SS"; break;
  684. case 3: r.description = "S"; break;
  685. case 4: r.description = "A"; break;
  686. case 5: r.description = "B"; break;
  687. case 6: r.description = "C"; break;
  688. case 7: r.description = "D"; break;
  689. default: r.description = "not played";
  690. }
  691. return r;
  692. };
  693. const Short = (arr, iter) => (arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8);
  694. const Int = (arr, iter) => { return arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8 | arr[iter.nxtpos++] << 16 | arr[iter.nxtpos++] << 24; };
  695. const Long = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getBigUint64(0, true); iter.nxtpos += 8; return r; };
  696. const ULEB128 = (arr, iter) => {
  697. let value = 0n, shift = 0n, peek = 0n;
  698. do{
  699. peek = BigInt(arr[iter.nxtpos++]);
  700. value |= (peek & 0x7Fn) << shift;
  701. shift += 7n;
  702. }while((peek & 0x80n) !== 0n)
  703. return value;
  704. };
  705. const Single = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 4).getFloat32(0, true); iter.nxtpos += 4; return r; };
  706. const Double = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getFloat64(0, true); iter.nxtpos += 8; return r; };
  707. const Boolean = (arr, iter) => { return arr[iter.nxtpos++] !== 0x00; };
  708. const OString = (arr, iter) => {
  709. let value = "";
  710. switch(arr[iter.nxtpos++]){
  711. case 0: break;
  712. case 0x0b: {
  713. const l = ULEB128(arr, iter);
  714. const bv = new Uint8Array(arr.buffer, iter.nxtpos, Number(l));
  715. value = new TextDecoder().decode(bv);
  716. iter.nxtpos += Number(l);
  717. break;
  718. }
  719. default: console.assert(false, `error occurred while parsing osu string with the first byte.`);
  720. }
  721. return value;
  722. };
  723. const IntDouble = (arr, iter) => {
  724. const r = {int: 0, double: 0};
  725. const m1 = arr[iter.nxtpos++];
  726. console.assert(m1 === 0x08, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  727. r.int = Int(arr, iter);
  728. const m2 = arr[iter.nxtpos++];
  729. console.assert(m2 === 0x0d, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  730. r.double = Double(arr, iter);
  731. return r;
  732. };
  733. const IntDoubleArray = (arr, iter) => {
  734. const r = new Array(Int(arr, iter));
  735. for(let i = 0; i < r.length; i++) r[i] = IntDouble(arr, iter);
  736. return r;
  737. };
  738. const TimingPoint = (arr, iter) => {
  739. return {
  740. BPM: Double(arr, iter),
  741. offset: Double(arr, iter),
  742. notInherited: Boolean(arr, iter),
  743. };
  744. };
  745. const TimingPointArray = (arr, iter) => {
  746. const r = new Array(Int(arr, iter));
  747. for(let i = 0; i < r.length; i++) r[i] = TimingPoint(arr, iter);
  748. return r;
  749. };
  750. const DateTime = Long;
  751. const Beatmap = (arr, iter) => {
  752. return {
  753. bytes: (iter.osuVersion < 20191106) ? Int(arr, iter) : undefined,
  754. artistName: OString(arr, iter),
  755. artistNameUnicode: OString(arr, iter),
  756. songTitle: OString(arr, iter),
  757. songTitleUnicode: OString(arr, iter),
  758. creatorName: OString(arr, iter),
  759. difficultyName: OString(arr, iter),
  760. audioFilename: OString(arr, iter),
  761. MD5Hash: OString(arr, iter),
  762. beatmapFilename: OString(arr, iter),
  763. rankedStatus: RankedStatus(arr, iter),
  764. hitcircleCount: Short(arr, iter),
  765. sliderCount: Short(arr, iter),
  766. spinnerCount: Short(arr, iter),
  767. lastModified: Long(arr, iter),
  768. AR: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  769. CS: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  770. HP: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  771. OD: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  772. sliderVelocity: Double(arr, iter),
  773. osuSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  774. taikoSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  775. catchSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  776. maniaSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  777. drainTime: Int(arr, iter),
  778. totalTime: Int(arr, iter),
  779. audioPreviewTime: Int(arr, iter),
  780. timingPointArr: TimingPointArray(arr, iter),
  781. difficultyID: Int(arr, iter),
  782. beatmapID: Int(arr, iter),
  783. threadID: Int(arr, iter),
  784. osuGrade: Grade(arr, iter),
  785. taikoGrade: Grade(arr, iter),
  786. catchGrade: Grade(arr, iter),
  787. maniaGrade: Grade(arr, iter),
  788. offsetLocal: Short(arr, iter),
  789. stackLeniency: Single(arr, iter),
  790. mode: OsuMode(arr, iter),
  791. sourceStr: OString(arr, iter),
  792. tagStr: OString(arr, iter),
  793. offsetOnline: Short(arr, iter),
  794. titleFont: OString(arr, iter),
  795. unplayed: Boolean(arr, iter),
  796. lastTimePlayed: Long(arr, iter),
  797. isOsz2: Boolean(arr, iter),
  798. folderName: OString(arr, iter),
  799. lastTimeChecked: Long(arr, iter),
  800. ignoreBeatmapSound: Boolean(arr, iter),
  801. ignoreBeatmapSkin: Boolean(arr, iter),
  802. disableStoryboard: Boolean(arr, iter),
  803. disableVideo: Boolean(arr, iter),
  804. visualOverride: Boolean(arr, iter),
  805. uselessShort: (iter.osuVersion < 20140609) ? Short(arr, iter) : undefined,
  806. lastModified2: Int(arr, iter),
  807. scrollSpeedMania: Byte(arr, iter),
  808. };
  809. };
  810. class _ProgressBar{
  811. barEle = null;
  812. Show(){
  813. if(this.barEle) { this.barEle.style.setProperty("opacity", "1"); return; }
  814. this.barEle = HTML("div", {class: "owenhancement-progress-bar", style: "position: fixed; left: 0px; top: 0px; width: 0%; height: 3px; background-color: #fc2; opacity: 1; z-index: 999;"});
  815. document.body.insertAdjacentElement("beforebegin", this.barEle);
  816. }
  817. Progress(prog){
  818. if(this.barEle) this.barEle.style.setProperty("width", `${prog * 100}%`);
  819. if(prog >= 1) this.Hide();
  820. }
  821. Hide(){ this.barEle.style.setProperty("opacity", "0"); }
  822. };
  823. const ProgressBar = new _ProgressBar();
  824. const BeatmapArray = async (arr, iter) => {
  825. const t = 200;
  826. const r = new Array(Int(arr, iter));
  827. let l = performance.now();
  828. for(let i = 0; i < r.length; i++){
  829. r[i] = Beatmap(arr, iter);
  830. if(performance.now() - l > t){
  831. l = performance.now();
  832. ProgressBar.Progress((i + 1) / (r.length));
  833. await new Promise((res, rej) => setTimeout(() => res(), 0));
  834. }
  835. }
  836. return r;
  837. };
  838. const OsuDb = async (arr, iter) => {
  839. ProgressBar.Show();
  840. const r = {};
  841. r.version = Int(arr, iter);
  842. iter.osuVersion = r.version;
  843. r.folderCount = Int(arr, iter);
  844. r.accountUnlocked = Boolean(arr, iter);
  845. r.timeTillUnlock = DateTime(arr, iter);
  846. r.playerName = OString(arr, iter);
  847. r.beatmapArray = await BeatmapArray(arr, iter);
  848. r.permission = Int(arr, iter);
  849. ProgressBar.Hide();
  850. return r;
  851. };
  852. class ScoreDb{
  853. constructor(arr, iter){
  854.  
  855. }
  856. }
  857. const beatmapsets = new Set();
  858. const beatmaps = new Set();
  859. const bmsReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)/;
  860. const bmsdlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)\/download/;
  861. const bmReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/(?:[0-9]+)#(?:mania|osu|fruits|taiko)\/([0-9]+)/;
  862. const BeatmapsetRefresh = () => {
  863. for(const bm of window.osudb.beatmapArray){
  864. beatmaps.add(bm.difficultyID);
  865. beatmapsets.add(bm.beatmapID);
  866. }
  867. OnMutation();
  868. };
  869. const NewOsuDb = async (r) => {
  870. const start = performance.now();
  871. const result = new Uint8Array(r.result);
  872. const length = result.length;
  873. console.log(`start reading osu!.db(${length} Bytes).`);
  874. const iter = {
  875. nxtpos: 0,
  876. };
  877. window.osudb = await OsuDb(result, iter);
  878. if(iter.nxtpos !== length) ShowPopup(i18n("There are still remaining unread bytes, something may be wrong."), "danger");
  879. ShowPopup(i18n("Finished reading osu!.db in %{time} ms.", {time: performance.now() - start}));
  880. };
  881. let ReadOsuDbWorking = false;
  882. const ReadOsuDb = async (file) => {
  883. if(ReadOsuDbWorking){
  884. ShowPopup(i18n("Script is already busy reading a osu!.db file."), "warning");
  885. return;
  886. }
  887. ReadOsuDbWorking = true;
  888. if(file.name !== "osu!.db"){ console.assert( false, "filename should be 'osu!.db'."); return; }
  889. const r = new FileReader();
  890. r.onload = async () => {
  891. await NewOsuDb(r);
  892. BeatmapsetRefresh();
  893. ReadOsuDbWorking = false;
  894. };
  895. r.onerror = () => console.assert(false, "error occurred while reading file.");
  896. r.readAsArrayBuffer(file);
  897. };
  898. const SelectOsuDb = (event) => {
  899. const t = event.target;
  900. const l = t.files;
  901. console.assert(l && l.length === 1, "No file or multiple files are selected.");
  902. ReadOsuDb(l[0]);
  903. };
  904. const CheckForUpdate = () => {
  905. const verReg = /<dd class="script-show-version"><span>([0-9\.]+)<\/span><\/dd>/;
  906. fetch("https://greasyfork.org/en/scripts/475417-osu-web-enhancement", {
  907. credentials: "omit"
  908. }).then(response => response.text()).then((html) => {
  909. const ver = verReg.exec(html);
  910. if(ver){
  911. const result = (() => {
  912. const verList = ver[1].split(".");
  913. const thisVer = GM_info.script.version;
  914. console.log(`latest version is: ${ver[1]}, current version is: ${thisVer}`);
  915. const thisVerList = thisVer.split(".");
  916. for(let i = 0; i < verList.length; i++){
  917. if(Number(verList[i]) > Number(thisVerList[i] ?? 0)) return true;
  918. else if(Number(verList[i]) < Number(thisVerList[i] ?? 0)) return false;
  919. }
  920. return false;
  921. })();
  922. if(result){
  923. const a = HTML("a", {href: "https://greasyfork.org/scripts/475417-osu-web-enhancement/code/osu!web%20enhancement.user.js", download: "", style: "display:none;"});
  924. a.click();
  925. }
  926. else{
  927. ShowPopup(i18n("The latest version is already installed!"))
  928. }
  929. }
  930. });
  931. };
  932. const AddMenu = () => {
  933. const menuId = "osu-web-enhancement-toolbar";
  934. if(!window.menuEventListener){
  935. window.addEventListener("click", (ev) => {
  936. const fid = ev.target?.dataset?.functionId;
  937. if(fid) switch(fid){
  938. case "import-osu-db-button": document.getElementById("osu-db-input")?.click(); break;
  939. case "check-for-update-button": CheckForUpdate(); break;
  940. case "pp-gini-index-calculator": PPGiniIndex(); break;
  941. }
  942. });
  943. window.menuEventListener = true;
  944. }
  945. if(document.getElementById(menuId)) return;
  946. const anc = document.querySelector("div.nav2__col.nav2__col--menu.js-react--quick-search-button");
  947. const i = HTML("input", {type: "file", id: "osu-db-input", accept: ".db", eventListener: [{
  948. type: "change",
  949. listener: SelectOsuDb,
  950. options: false,
  951. }]});
  952. const menuClass = "simple-menu simple-menu--nav2 simple-menu--nav2-left-aligned simple-menu--nav2-transparent js-menu";
  953. const menuItemClass = "simple-menu__item u-section-community--before-bg-normal";
  954. const menuTgtId = "osu-web-enhancement";
  955. anc.insertAdjacentElement("beforebegin",
  956. HTML("div", {class: "nav2__col nav2__col--menu", id: menuId},
  957. HTML("div", {class: "nav2__menu-link-main js-menu", "data-menu-target": `nav2-menu-popup-${menuTgtId}`, "data-menu-show-delay":"0", style:"flex-direction: column; cursor: default;"},
  958. HTML("span", {style: "flex-grow: 1;"}),
  959. HTML("span", {style: "font-size: 10px;"}, HTML("osu!web")),
  960. HTML("span", {style: "font-size: 10px;"}, HTML("enhancement")),
  961. HTML("span", {style: "flex-grow: 1;"}),
  962. ),
  963. HTML("div", {class: "nav2__menu-popup"},
  964. HTML("div", {class: `${menuClass}`, "data-menu-id": `nav2-menu-popup-${menuTgtId}`, "data-visibility": "hidden"},
  965. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "import-osu-db-button", }, HTML(i18n("Import osu!.db"))),
  966. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update"))),
  967. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index"))),
  968. HTML("a", {class: `${menuItemClass}`, style: "cursor: pointer;", href: "https://greasyfork.org/en/scripts/475417-osu-web-enhancement", target: "_blank"}, HTML(i18n("Go to GreasyFork page")))
  969. ),
  970. )
  971. )
  972. );
  973. const mobMenuItmCls = "navbar-mobile-item__submenu-item js-click-menu--close";
  974. const mob = document.querySelector(`div.mobile-menu__item.js-click-menu[data-click-menu-id="mobile-nav"]`);
  975. mob.insertAdjacentElement("beforeend",
  976. HTML("div", {class: "navbar-mobile-item"},
  977. HTML("div", {class: "navbar-mobile-item__main js-click-menu", "data-click-menu-target": `nav-mobile-${menuTgtId}`, style: "cursor: pointer;"},
  978. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--closed"},
  979. HTML("i", {class: "fas fa-chevron-right"})
  980. ),
  981. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--opened"},
  982. HTML("i", {class: "fas fa-chevron-down"})
  983. ),
  984. HTML("osu!web enhancement"),
  985. ),
  986. HTML("ul", {class: "navbar-mobile-item__submenu js-click-menu", "data-click-menu-id": `nav-mobile-${menuTgtId}`, "data-visibility": "hidden"},
  987. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "import-osu-db-button",}, HTML(i18n("Import osu!.db")))),
  988. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update")))),
  989. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index")))),
  990. HTML("a", {class: `${mobMenuItmCls}`, style: "cursor: pointer;", href: "https://greasyfork.org/en/scripts/475417-osu-web-enhancement", target: "_blank"}, HTML(i18n("Go to GreasyFork page")))
  991. )
  992. )
  993. );
  994. document.body.appendChild(i);
  995. };
  996. const FilterBeatmapSet = () => {
  997. document.querySelectorAll(".beatmapset-panel").forEach((item) => {
  998. const bmsID = Number(bmsReg.exec(item.innerHTML)?.[1]);
  999. if(bmsID && beatmapsets.has(bmsID)){
  1000. item.setAttribute("owned-beatmapset", "");
  1001. }
  1002. });
  1003. document.querySelectorAll("div.bbcode a, a.osu-md__link").forEach(item => {
  1004. if(item.classList.contains("owned-beatmap-link") || item.classList.contains("beatmap-download-link")) return;
  1005. const e = bmsReg.exec(item.href);
  1006. if(e && beatmapsets.has(Number(e[1]))){
  1007. item.classList.add("owned-beatmap-link");
  1008. if(item.nextElementSibling?.classList?.contains("beatmap-download-link")) item.nextElementSibling.remove();
  1009. const box = item.getBoundingClientRect();
  1010. const size = Math.round(box.height / 16 * 14);
  1011. const vert = Math.round(size * 4 / 14) / 2;
  1012. item.after(HTML("img", {src: svg_green_tick, title: i18n("Owned"), alt: "owned beatmap", style: `margin: 0px 5px; width: ${size}px; height: ${size}px; vertical-align: -${vert}px;`}));
  1013. }else if(e && !item.nextElementSibling?.classList?.contains("beatmap-download-link")){
  1014. item.after(
  1015. HTML("a", {class: "beatmap-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""},
  1016. HTML("span", {class: "fas fa-file-download", title: i18n("Download")})
  1017. )
  1018. );
  1019. }
  1020. });
  1021. document.querySelectorAll("li.beatmap-pack-items__set").forEach(item => {
  1022. if(item.classList.contains("owned-beatmap-pack-item")) return;
  1023. const a = item.querySelector("a.beatmap-pack-items__link");
  1024. const e = bmsReg.exec(a.href);
  1025. if(e && beatmapsets.has(Number(e[1]))){
  1026. item.classList.add("owned-beatmap-pack-item");
  1027. const span = item.querySelector("span.fal");
  1028. span.setAttribute("title", i18n("Owned"));
  1029. span.dataset.origTitle = "owned";
  1030. span.setAttribute("class", "");
  1031. span.append(HTML("img", {src: svg_green_tick, alt: "owned beatmap", style: `width: 16px; height: 16px; vertical-align: -2px;`}));
  1032. const parent = item.querySelector(".beatmap-pack-item-download-link");
  1033. if(parent){
  1034. console.assert(parent.parentElement === item, "unexpected error occurred!");
  1035. item.insertBefore(span, parent);
  1036. parent.remove();
  1037. }
  1038. }else if(e){
  1039. const icon = item.querySelector(".beatmap-pack-items__icon");
  1040. icon.setAttribute("title", i18n("Download"));
  1041. icon.setAttribute("class", "fas fa-file-download beatmap-pack-items__icon");
  1042. if(icon.parentElement === item){
  1043. const dl = HTML("a", {class: "beatmap-pack-item-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""});
  1044. item.insertBefore(dl, icon);
  1045. dl.append(icon);
  1046. }
  1047. }
  1048. })
  1049. };
  1050. const AdjustStyle = (modestr, sectionName) => {
  1051. const styleSheetId = `userscript-generated-stylesheet-${sectionName}`;
  1052. let e = document.getElementById(styleSheetId);
  1053. if(!e){
  1054. e = document.createElement("style");
  1055. e.id = styleSheetId;
  1056. document.head.appendChild(e);
  1057. }
  1058. const s = e.sheet;
  1059. while(s.cssRules.length) s.deleteRule(0);
  1060. const sectionSelector = `div.js-sortable--page[data-page-id="${sectionName}"]`;
  1061. let ll = [];
  1062. switch(modestr){
  1063. case "mania": ll = [".mania-300", ".mania-200", ".mania-100", ".mania-50", ".mania-miss"]; break;
  1064. case "fruits": ll = [".fruits-300", ".fruits-100", ".fruits-50-miss", ".fruits-miss"]; break;
  1065. case "taiko": ll = [".taiko-300", ".taiko-150", ".taiko-miss"]; break;
  1066. case "osu": ll = [".osu-300", ".osu-100", ".osu-50", ".osu-miss"]; break;
  1067. }
  1068. class FasterCalc{
  1069. _map = new Map();
  1070. Calculate = (ele) => {
  1071. const t = ele.textContent;
  1072. let w = 0, changed = false;
  1073. for(const c of t){
  1074. let wc = this._map.get(c);
  1075. if(!wc){
  1076. if(!changed) changed = ele.cloneNode(true);
  1077. ele.textContent = c;
  1078. wc = ele.clientWidth;
  1079. this._map.set(c, wc);
  1080. }
  1081. w += wc;
  1082. }
  1083. if(changed){
  1084. ele.insertAdjacentElement("afterend", changed);
  1085. ele.remove();
  1086. }
  1087. return w;
  1088. };
  1089. };
  1090. let fc = new FasterCalc();
  1091. ll.forEach((str) =>
  1092. s.insertRule(
  1093. `${sectionSelector} ${str} + .score-detail-data-text {
  1094. width: ${[...document.querySelectorAll(`${sectionSelector} ${str} + .score-detail-data-text`)].reduce((max, ele) => { const w = fc.Calculate(ele); return w > max ? w : max }, 0) + 2}px;
  1095. }` ,0
  1096. )
  1097. );
  1098. fc = new FasterCalc();
  1099. [".play-detail__combo", ".play-detail__Accuracy", ".play-detail__Accuracy2"].forEach((str) =>
  1100. s.insertRule(
  1101. `${sectionSelector} ${str}{
  1102. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = fc.Calculate(ele); return w > max ? w : max;}, 0)) + 1}px;
  1103. }`
  1104. ,0
  1105. )
  1106. );
  1107. [".play-detail__pp"].forEach((str) =>
  1108. s.insertRule(
  1109. `${sectionSelector} ${str}{
  1110. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = ele.clientWidth; return w > max ? w : max;}, 0)) + 1}px;
  1111. }`
  1112. ,0
  1113. )
  1114. );
  1115. };
  1116. const PPGiniIndex = () => {
  1117. const vals = [...document.querySelectorAll(`div.js-sortable--page[data-page-id="top_ranks"] div.play-detail-list:nth-child(4) div.play-detail.play-detail--highlightable`)]
  1118. .map((ele) => {const ppele = ele.querySelector("div.play-detail__pp span"); return Number((ppele.title ? ppele.title : ppele.dataset.origTitle).replaceAll(",", ""))})
  1119. .sort((a, b) => b - a);
  1120. if(vals.length === 0) {
  1121. ShowPopup(i18n("Could not find best play data"), "danger");
  1122. return;
  1123. }
  1124. const min = vals[vals.length - 1];
  1125. let _ = 0; for(let i = vals.length - 1; i >= 0; i--) {
  1126. _ += vals[i] - min;
  1127. vals[i] = _;
  1128. }
  1129. const SB = vals.reduce((sum, val) => sum + val, -(vals[0] / 2));
  1130. const SAB = vals[0] / 2 * vals.length;
  1131. ShowPopup(i18n("Your pp Gini index of bp%{bp} is %{val}.", {bp: vals.length, val: (1 - SB/SAB).toPrecision(6)}));
  1132. }
  1133. const TopRanksWorker = (userId, modestr, addedNodes = [document.body]) => {
  1134. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1135. const subdomain = isLazer ? "lazer": "osu";
  1136. const sectionNames = new Set();
  1137. const GetSection = (ele) => {
  1138. let count = 0;
  1139. while(ele){
  1140. if(ele.tagName === "DIV" && ele.className === "js-sortable--page") return ele.dataset.pageId;
  1141. ele = ele.parentElement;
  1142. count++;
  1143. if(count > 50) console.log(ele);
  1144. }
  1145. };
  1146. addedNodes.forEach((eles) => {
  1147. if(eles instanceof Element) eles.querySelectorAll(":scope div.play-detail.play-detail--highlightable").forEach((ele) => {
  1148. if(ele.getAttribute("improved") !== null) return;
  1149. const a = ele.querySelector(":scope time.js-timeago");
  1150. const t = a.getAttribute("datetime");
  1151. const data = messageCache.get(`${userId},${modestr},${subdomain},${t}`);
  1152. if(data){
  1153. sectionNames.add(GetSection(ele));
  1154. ListItemWorker(ele, data, isLazer);
  1155. }
  1156. });
  1157. });
  1158. sectionNames.forEach(sectionName => AdjustStyle(modestr, sectionName));
  1159. };
  1160. const DiffToColour = (diff, stops = [0, 0.1, 1.25, 2, 2.5, 3.3, 4.2, 4.9, 5.8, 6.7, 7.7, 9], vals = ['#AAAAAA', '#4290FB', '#4FC0FF', '#4FFFD5', '#7CFF4F', '#F6F05C', '#FF8068', '#FF4E6F', '#C645B8', '#6563DE', '#18158E', '#000000']) => {
  1161. const len = stops.length;
  1162. diff = Math.min(Math.max(diff, stops[0]), stops[len - 1]);
  1163. let r = stops.findIndex(stop => stop > diff);
  1164. if(r === -1) r = len - 1;
  1165. const d = stops[r] - stops[r - 1];
  1166. return `#${[[1, 3], [3, 5], [5, 7]]
  1167. .map(_ => [Number.parseInt(vals[r].slice(..._), 16), Number.parseInt(vals[r-1].slice(..._), 16)])
  1168. .map(_ => Math.round((_[0] ** 2.2 * (diff - stops[r-1]) / d + _[1] ** 2.2 * (stops[r] - diff) / d) ** (1 / 2.2)).toString(16).padStart(2, "0"))
  1169. .join("")
  1170. }`;
  1171. };
  1172. const CustomToPrecision = (number, precision) => {
  1173. return number >= 1 ? number.toPrecision(precision) : (number < (10 ** (-precision + 1) / 2) ? 0 : number.toFixed(precision - 1));
  1174. }
  1175. const ListItemWorker = (ele, data, isLazer) => {
  1176. if(ele.getAttribute("improved") !== null) return;
  1177. ele.setAttribute("improved", "");
  1178. ele.setAttribute("data-replay-id", data.id);
  1179. if(data.pp){
  1180. data.pp = Number(data.pp);
  1181. const pptext = ele.querySelector(".play-detail__pp > span").childNodes[0];
  1182. pptext.nodeValue = CustomToPrecision(data.pp, 5);
  1183. if(data.weight) pptext.title = i18n("%{pc} of total pp", {pc: CustomToPrecision(data.weight.pp, 5)});
  1184. }
  1185. const left = ele.querySelector("div.play-detail__group.play-detail__group--top");
  1186. const leftc = HTML("div", {class: "play-detail__group--background", style: `background-image: url(https://assets.ppy.sh/beatmaps/${data.beatmap.beatmapset_id}/covers/card@2x.jpg);`});
  1187. left.insertAdjacentElement("beforebegin", leftc);
  1188. const detail = ele.querySelector("div.play-detail__score-detail-top-right");
  1189. const du = detail.children[0];
  1190. if(!detail.children[1]) detail.append(HTML("div", {classList: "play-detail__pp-weight"}));
  1191. const db = detail.children[1];
  1192. data.statistics.perfect ??= 0, data.statistics.great ??= 0, data.statistics.good ??= 0, data.statistics.ok ??= 0, data.statistics.meh ??= 0, data.statistics.miss ??= 0;
  1193. const bmName = ele.querySelector("span.play-detail__beatmap");
  1194. const sr = HTML("div", {class: `difficulty-badge ${data.beatmap.difficulty_rating >= 6.5 ? "difficulty-badge--expert-plus" : ""}`, style: `--bg: ${DiffToColour(data.beatmap.difficulty_rating)}`},
  1195. HTML("span", {class: "difficulty-badge__icon"}, HTML("span", {class: "fas fa-star"})),
  1196. HTML("span", {class: "difficulty-badge__rating"}, HTML(`${data.beatmap.difficulty_rating.toFixed(2)}`))
  1197. );
  1198. /*
  1199. const ic = ele;
  1200. ic.classList.add("audio-player", "js-audio--player");
  1201. ic.setAttribute("data-audio-url", `https://b.ppy.sh/preview/${data.beatmap.beatmapset_id}.mp3`)
  1202. ic.setAttribute("data-audio-state", "paused");
  1203. const gr = ele;
  1204. gr.classList.add("audio-player__button", "audio-player__button--play", "js-audio--play");
  1205. */
  1206. bmName.parentElement.insertBefore(sr, bmName);
  1207. const bma = ele.querySelector("a.play-detail__title");
  1208. // const modeName = ["STD", "TAIKO", "CTB", "MANIA"];
  1209. bma.onclick = (e) => {e.stopPropagation();};
  1210. switch(data.ruleset_id){
  1211. case 0:{
  1212. du.replaceChildren(
  1213. HTML("span", {class: "play-detail__before"}),
  1214. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1215. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1216. HTML("span", {class: `combo ${isLazer ?(data.max_combo === (data.maximum_statistics.great ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0) ? "legacy-perfect-combo" : ""):(data.legacy_perfect ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1217. isLazer ? HTML("/") : null,
  1218. isLazer ? HTML("span", {class: "max-combo"}, HTML(`${(data.maximum_statistics.great ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0)}`)) : null,
  1219. HTML("x"),
  1220. ),
  1221. );
  1222. const m_300 = HTML("span", {class: "score-detail score-detail-osu-300"},
  1223. HTML("span", {class: "osu-300"},
  1224. HTML("300")
  1225. ),
  1226. HTML("span", {class: "score-detail-data-text"},
  1227. HTML(`${data.statistics.great + data.statistics.perfect}`)
  1228. )
  1229. );
  1230. const s100 = HTML("span", {class: "score-detail score-detail-osu-100"},
  1231. HTML("span", {class: "osu-100"},
  1232. HTML("100")
  1233. ),
  1234. HTML("span", {class: "score-detail-data-text"},
  1235. HTML(`${data.statistics.ok + data.statistics.good}`)
  1236. )
  1237. );
  1238. const s50 = HTML("span", {class: "score-detail score-detail-osu-50"},
  1239. HTML("span", {class: "osu-50"},
  1240. HTML("50")
  1241. ),
  1242. HTML("span", {class: "score-detail-data-text"},
  1243. HTML(`${data.statistics.meh}`)
  1244. )
  1245. );
  1246. const s0 = HTML("span", {class: "score-detail score-detail-osu-miss"},
  1247. HTML("span", {class: "osu-miss"},
  1248. HTML("img", {src: svg_osu_miss, alt: "miss"})
  1249. ),
  1250. HTML("span", {class: "score-detail-data-text"},
  1251. HTML(`${data.statistics.miss}`)
  1252. )
  1253. );
  1254. db.replaceChildren(m_300, s100, s50, s0);
  1255. break;
  1256. }
  1257. case 1:{
  1258. const cur = [data.statistics.great ?? 0, data.statistics.ok ?? 0, data.statistics.miss ?? 0];
  1259. const mx = cur[0] + cur[1] + cur[2];
  1260. du.replaceChildren(
  1261. HTML("span", {class: "play-detail__before"}),
  1262. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1263. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1264. HTML("span", {class: `combo ${(data.max_combo === mx ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1265. HTML("/"),
  1266. HTML("span", {class: "max-combo"}, HTML(`${mx}`)),
  1267. HTML("x"),
  1268. ),
  1269. );
  1270. db.replaceChildren(
  1271. HTML("span", {class: "score-detail score-detail-taiko-300"},
  1272. HTML("span", {class: "taiko-300"}, HTML("300")),
  1273. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1274. ),
  1275. HTML("span", {class: "score-detail score-detail-taiko-150"},
  1276. HTML("span", {class: "taiko-150"}, HTML("150")),
  1277. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok ?? 0))
  1278. ),
  1279. HTML("span", {class: "score-detail score-detail-fruits-combo"},
  1280. HTML("span", {class: "taiko-miss"}, HTML("miss")),
  1281. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1282. ),
  1283. );
  1284. break;
  1285. }
  1286. case 2:{
  1287. if (isLazer) {
  1288. const cur = [data.statistics.great ?? 0, data.statistics.large_tick_hit ?? 0, data.statistics.small_tick_hit ?? 0];
  1289. const mx = [data.maximum_statistics.great ?? 0, data.maximum_statistics.large_tick_hit ?? 0, data.maximum_statistics.small_tick_hit ?? 0];
  1290. du.replaceChildren(
  1291. HTML("span", {class: "play-detail__before"}),
  1292. HTML("span", {class: "play-detail__Accuracy", title: i18n(`Lazer Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1293. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1294. HTML("span", {class: `combo ${(data.max_combo === mx[0] + mx[1] ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1295. HTML("/"),
  1296. HTML("span", {class: "max-combo"}, HTML(`${mx[0] + mx[1]}`)),
  1297. HTML("x"),
  1298. ),
  1299. );
  1300. db.replaceChildren(
  1301. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1302. HTML("span", {class: "fruits-300"}, HTML("fruits")),
  1303. HTML("span", {class: "score-detail-data-text"}, HTML(cur[0] + "/" + mx[0]))
  1304. ),
  1305. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1306. HTML("span", {class: "fruits-100"}, HTML("ticks")),
  1307. HTML("span", {class: "score-detail-data-text"}, HTML(cur[1] + "/" + mx[1]))
  1308. ),
  1309. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1310. HTML("span", {class: "fruits-50-miss"}, HTML("drops")),
  1311. HTML("span", {class: "score-detail-data-text"}, HTML(cur[2] + "/" + mx[2]))
  1312. )
  1313. );
  1314. } else {
  1315. du.replaceChildren(
  1316. HTML("span", {class: "play-detail__before"}),
  1317. HTML("span", {class: "play-detail__Accuracy", title: i18n(`V1 Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1318. HTML("span", {class: "play-detail__combo", title: i18n(`Combo`)},
  1319. HTML("span", {class: ""}, HTML(`${data.max_combo}`)),
  1320. HTML("x")
  1321. ),
  1322. );
  1323. db.replaceChildren(
  1324. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1325. HTML("span", {class: "fruits-300"}, HTML("FRUIT")),
  1326. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1327. ),
  1328. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1329. HTML("span", {class: "fruits-100"}, HTML("tick")),
  1330. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.large_tick_hit ?? 0))
  1331. ),
  1332. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1333. HTML("span", {class: "fruits-50-miss"}, HTML("miss")),
  1334. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.small_tick_miss ?? 0))
  1335. ),
  1336. HTML("span", {class: "score-detail score-detail-fruits-miss"},
  1337. HTML("span", {class: "fruits-miss"}, HTML("MISS")),
  1338. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1339. )
  1340. );
  1341. }
  1342. break;
  1343. }
  1344. case 3:{
  1345. const ppAcc = (320*data.statistics.perfect+300*data.statistics.great+200*data.statistics.good+100*data.statistics.ok+50*data.statistics.meh)/(320*(data.statistics.perfect+data.statistics.great+data.statistics.good+data.statistics.ok+data.statistics.meh+data.statistics.miss));
  1346. const v2Acc = (305*data.statistics.perfect+300*data.statistics.great+200*data.statistics.good+100*data.statistics.ok+50*data.statistics.meh)/(305*(data.statistics.perfect+data.statistics.great+data.statistics.good+data.statistics.ok+data.statistics.meh+data.statistics.miss));
  1347. const MCombo = (data.maximum_statistics.perfect ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0);
  1348. const isMCombo = isLazer ? data.max_combo >= MCombo : data.legacy_perfect;
  1349. du.replaceChildren(
  1350. HTML("span", {class: "play-detail__before"}),
  1351. HTML("span", {class: "play-detail__Accuracy2", title: i18n(`pp Accuracy`)}, HTML(`${(ppAcc * 100).toFixed(2)}%`)),
  1352. HTML("span", {class: "play-detail__Accuracy", title: i18n(`V2 Accuracy`)}, HTML(`${(((data.rank === "D" && data.accuracy === 0) ? v2Acc :data.accuracy) * 100).toFixed(2)}%`)),
  1353. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1354. HTML("span", {class: `combo ${isMCombo ? "legacy-perfect-combo" : ""}`}, HTML(`${data.max_combo}`)),
  1355. isLazer ? HTML("/") : null,
  1356. isLazer ? HTML("span", {class: "max-combo"}, HTML(MCombo)) : null,
  1357. HTML("x"),
  1358. ),
  1359. );
  1360. if(data.pp){
  1361. const lostpp = CustomToPrecision(data.pp * (0.2 / (Math.min(Math.max(ppAcc, 0.8), 1) - 0.8) - 1), 4);
  1362. ele.querySelector(".play-detail__pp").appendChild(HTML("span", {class: "lost-pp"}, HTML(lostpp === 0 ? "MAX" : `-${lostpp}`)));
  1363. }
  1364. const M_300 = Number(data.statistics.perfect) / Math.max(Number(data.statistics.great), 1);
  1365. db.replaceChildren(
  1366. HTML("span", {class: "score-detail score-detail-mania-max-300", title: i18n("MAX: %{perfect}, 300: %{great}", data.statistics)},
  1367. HTML("span", {class: "mania-max"}, HTML("M")),
  1368. HTML("/"),
  1369. HTML("span", {class: "mania-300"}, HTML("300")),
  1370. HTML("span", {class: "score-detail-data-text"}, HTML(`${M_300 >= 1000 ? Math.round(M_300) : (M_300 < 1 ? M_300.toFixed(2): M_300.toPrecision(3))}`))
  1371. ),
  1372. HTML("span", {class: "score-detail score-detail-mania-max-200"},
  1373. HTML("span", {class: "mania-200"}, HTML("200")),
  1374. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.good))
  1375. ),
  1376. HTML("span", {class: "score-detail score-detail-mania-max-100"},
  1377. HTML("span", {class: "mania-100"}, HTML("100")),
  1378. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok))
  1379. ),
  1380. HTML("span", {class: "score-detail score-detail-mania-max-50"},
  1381. HTML("span", {class: "mania-50"}, HTML("50")),
  1382. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.meh))
  1383. ),
  1384. HTML("span", {class: "score-detail score-detail-mania-max-0"},
  1385. HTML("span", {class: "mania-miss"}, HTML("miss")),
  1386. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss))
  1387. )
  1388. );
  1389. break;
  1390. }
  1391. default:;
  1392. }
  1393. }
  1394. let lastInitData = null;
  1395. const OsuLevelToExp = (n) => {
  1396. if(n <= 100) return 5000 / 3 * (4 * n ** 3 - 3 * n ** 2 - n) + 1.25 * 1.8 ** (n - 60);
  1397. else return 26_931_190_827 + 99_999_999_999 * (n - 100);
  1398. }
  1399. const OsuExpValToStr = (num) => {
  1400. const exp = Math.log10(num);
  1401. if(exp >= 12){
  1402. return `${(num / 10 ** 12).toPrecision(4)}T`;
  1403. }
  1404. else if(exp >= 9){
  1405. return `${(num / 10 ** 9).toPrecision(4)}B`;
  1406. }
  1407. else if(exp >= 6){
  1408. return `${(num / 10 ** 6).toPrecision(4)}M`;
  1409. }
  1410. else if(exp >= 4){
  1411. return `${(num / 10 ** 3).toPrecision(4)}K`;
  1412. }
  1413. else return `${num}`;
  1414. }
  1415. const messageCache = new Map();
  1416. window.messageCache = messageCache;
  1417. const profUrlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/users\/[0-9]+(?:|\/osu|\/taiko|\/fruits|\/mania)/;
  1418. class SortGroup {
  1419. rules = [];
  1420. constructor(){
  1421.  
  1422. }
  1423. Show = () => {
  1424. if(document.querySelector(".sort-detail__items")) return;
  1425. const h3 = document.querySelector('div.js-sortable--page[data-page-id="top_ranks"] h3.title.title--page-extra-small:nth-child(3)');
  1426. h3.insertAdjacentElement("afterend",
  1427. HTML("div", {class: "sort-detail__items"},
  1428. HTML("div", {class: "sort-detail__item sort-detail__item--title"}, i18n("Sort by")),
  1429. )
  1430. );
  1431. };
  1432. AddRule = (name) => {
  1433. this.rules.push(name);
  1434. };
  1435. };
  1436. const ImproveProfile = (mulist) => {
  1437. const wloc = window.location.toString();
  1438. if(!profUrlReg.test(wloc)) return;
  1439. //SortGroup.Show();
  1440. const initDataEle = document.querySelector(".js-react--profile-page.osu-layout.osu-layout--full");
  1441. if(!initDataEle) return;
  1442. const initData = JSON.parse(initDataEle.dataset.initialData);
  1443. const userId = initData.user.id, modestr = initData.current_mode;
  1444. if(initData !== lastInitData){
  1445. let ppDiv = null;
  1446. document.querySelectorAll("div.value-display.value-display--plain").forEach((ele) => {
  1447. if(ele.querySelector("div.value-display__label").textContent === "pp") ppDiv = ele;
  1448. });
  1449. if(ppDiv){
  1450. const ttscore = initData.user.statistics.total_score;
  1451. const lvl = initData.user.statistics.level.current;
  1452. const upgradescore = Math.round(OsuLevelToExp(lvl + 1) - OsuLevelToExp(lvl));
  1453. const lvlscore = ttscore - Math.round(OsuLevelToExp(lvl));
  1454. lastInitData = initData;
  1455. document.querySelector("div.bar__text").textContent = `${OsuExpValToStr(lvlscore)}/${OsuExpValToStr(upgradescore)} (${(lvlscore/upgradescore * 100).toPrecision(3)}%)`;
  1456. const _pp = initData.user.statistics.pp;
  1457. ppDiv.querySelector(".value-display__value > div").textContent = _pp >= 1 ? _pp.toPrecision(6) : (_pp < 0.000005 ? 0 : _pp.toFixed(5));
  1458. }
  1459. }
  1460. if(mulist !== undefined) mulist.forEach((record) => {
  1461. if(record.type === "childList" && record.addedNodes) TopRanksWorker(userId, modestr, record.addedNodes);
  1462. });
  1463. }
  1464. let wloc = "";
  1465. const WindowLocationChanged = () => {
  1466. if(window.location !== wloc){
  1467. wloc = window.location;
  1468. return true;
  1469. }
  1470. else return false;
  1471. }
  1472. const InsertStyleSheet = () => {
  1473. //const sheetId = "osu-web-enhancement-general-stylesheet";
  1474. const s = new CSSStyleSheet();
  1475. s.replaceSync(inj_style);
  1476. document.adoptedStyleSheets = [...document.adoptedStyleSheets, s];
  1477. }
  1478. const OnBeatmapsetDownload = (message) => {
  1479. beatmapsets.add(message.beatmapsetId);
  1480. }
  1481. const ImproveBeatmapPlaycountItems = () => {
  1482. for(const item of [...document.querySelectorAll("div.beatmap-playcount")]){
  1483. if(item.getAttribute("improved") !== null) continue;
  1484. item.setAttribute("improved", "");
  1485. const a = item.querySelector("a");
  1486. const bms = bmsReg.exec(a.href);
  1487. if(!bms?.[1]) continue;
  1488. const d = item.querySelector("div.beatmap-playcount__detail");
  1489. const b = HTML("div", {class: "beatmap-playcount__background", style: `background-image: url(https://assets.ppy.sh/beatmaps/${bms[1]}/covers/card@2x.jpg)`});
  1490. if(d.childElementCount > 0) d.insertBefore(b, d.children[0]);
  1491. else d.append(b);
  1492. }
  1493. }
  1494. const CopyToClipboard = (txt) => {
  1495. navigator.clipboard.writeText(txt).then(() => {
  1496. console.log(txt);
  1497. ShowPopup(i18n("Score details copied to clipboard!"))
  1498. }, (err) => {
  1499. console.log(err);
  1500. ShowPopup(i18n("Unable to copy score detail to clipboard, check console for more info."), "danger")
  1501. });
  1502. }
  1503. const MakeTextDetail = (data) => {
  1504. let detail = "";
  1505. const s = data.statistics; const m = data.maximum_statistics; const b = data.beatmap;
  1506. const secToMin = (t) => `${Math.floor(t/60)}:${String(t%60).padStart(2, '0')}`;
  1507. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1508. switch(data.ruleset_id){
  1509. case 0: detail =
  1510. `${(s.great ?? 0) + (s.perfect ?? 0)}-${(s.ok ?? 0) + (s.good ?? 0)}-${s.meh ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}${isLazer ? `/${(m.great ?? 0) + (m.legacy_combo_increase ?? 0)}` : ""}x
  1511. ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🔄 ${b.count_spinners ?? 0}
  1512. `; break;
  1513. case 1: detail =
  1514. `${s.great ?? 0}-${s.ok ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}/${(s.great ?? 0) + (s.ok ?? 0) + (s.miss ?? 0)}x
  1515. 🥁 ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🍥 ${b.count_spinners ?? 0}
  1516. `; break;
  1517. case 2: detail = isLazer ?
  1518. `${s.great ?? 0}/${m.great ?? 0}-${s.large_tick_hit ?? 0}/${m.large_tick_hit ?? 0}-${s.small_tick_hit ?? 0}/${m.small_tick_hit ?? 0} ${data.max_combo ?? 0}/${(m.large_tick_hit ?? 0)+(m.great ?? 0)}}x
  1519. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1520. ` :
  1521. `${s.great ?? 0}-${s.large_tick_hit ?? 0}-${s.small_tick_miss ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}x
  1522. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1523. `; break;
  1524. case 3: detail =
  1525. `${s.perfect ?? 0}-${s.great ?? 0}-${s.good ?? 0}-${s.ok ?? 0}-${s.meh ?? 0}-${s.miss ?? 0} ${data.max_combo}${isLazer ? `/${(m.perfect ?? 0) + (m.legacy_combo_increase ?? 0)}` : ""}x
  1526. 🍚 ${b.count_circles ?? 0} 🍜 ${b.count_sliders ?? 0}
  1527. `; break;
  1528. default:;
  1529. }
  1530. const scrMsg =
  1531. `${data.beatmapset.title}
  1532. [${data.beatmap.version}] ${secToMin(data.beatmap.total_length)}
  1533. ${data.total_score} ${data.rank} ${data.pp ? (data.pp >= 1 ? data.pp.toPrecision(5) : (data.pp < 0.00005 ? 0 : data.pp.toFixed(4))) : "-"}pp
  1534. ${detail}
  1535. `;
  1536. return scrMsg;
  1537. }
  1538. const CopyDetailsPopup = () => {
  1539. const ele = document.querySelector("div.play-detail.play-detail--active"); if(!ele) return;
  1540. const id = ele.dataset.replayId;
  1541. const data = messageCache.get(Number(id)); if(!data) return;
  1542. const msg = MakeTextDetail(data);
  1543. CopyToClipboard(msg);
  1544. };
  1545. const AddPopupButton = () => {
  1546. const p = document.querySelector("div.js-portal")?.querySelector("div.simple-menu");
  1547. if(!p || p.querySelector("button.score-card-popup-button")) return;
  1548. // p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: ShowScoreCardPopup}]}, HTML("Popup")));
  1549. p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: CopyDetailsPopup}]}, HTML(i18n("Copy Text Details"))));
  1550. };
  1551. const OnMutation = (mulist) => {
  1552. mut.disconnect();
  1553. AddMenu();
  1554. FilterBeatmapSet();
  1555. ImproveBeatmapPlaycountItems();
  1556. ImproveProfile(mulist);
  1557. AddPopupButton();
  1558. mut.observe(document, {childList: true, subtree: true});
  1559. };
  1560. const MessageFilter = (message) => {
  1561. const info = `${message.userId},${message.mode},${message.subdomain}`;
  1562. switch(message.type){
  1563. case "beatmapset_download_complete": OnBeatmapsetDownload(message); break;
  1564. case "top_ranks":
  1565. [message.data.pinned.items, message.data.best.items, message.data.firsts.items].forEach(items => items.forEach(item => {
  1566. messageCache.set(`${info},${item.ended_at}`, item);
  1567. messageCache.set(item.id, item);
  1568. }));
  1569. TopRanksWorker(message.userId, message.mode);
  1570. break;
  1571. case "firsts": case "pinned": case "best": case "recent":
  1572. message.data.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1573. TopRanksWorker(message.userId, message.mode);
  1574. break;
  1575. case "historical":
  1576. message.data.recent.items.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1577. TopRanksWorker(message.userId, message.mode);
  1578. break;
  1579. default:;
  1580. }
  1581. }
  1582. const WindowMessageFilter = (event) => {
  1583. if(event.source === window && event?.data?.id === "osu!web enhancement"){
  1584. MessageFilter(event.data);
  1585. }
  1586. }
  1587. const OnClick = (event) => {
  1588. let t = event.target;
  1589. while(t){
  1590. if(t.tagName === "A"){
  1591. const e = bmsdlReg.exec(t.href);
  1592. if(!e) continue;
  1593. beatmapsets.add(Number(e[1]));
  1594. FilterBeatmapSet();
  1595. break;
  1596. }
  1597. t = t.parentElement;
  1598. }
  1599. }
  1600. //document.addEventListener("click", OnClick);
  1601. const curLocale = window.currentLocale;
  1602. if (curLocale && locales[curLocale]) {
  1603. console.log("localization available");
  1604. i18n.translator.add(locales[curLocale]);
  1605. }
  1606. window.addEventListener("message", WindowMessageFilter);
  1607. const mut = new MutationObserver(OnMutation);
  1608. mut.observe(document, {childList: true, subtree: true});
  1609. InsertStyleSheet();
  1610. console.log("osu!web enhancement loaded");
  1611. // below are test code
  1612. /*
  1613. const osusrc = "https://i.ppy.sh/bde5906f8f985126f4ea624d3eb14c8702883aa2/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6f73752e706e67";
  1614. const taikosrc = "https://i.ppy.sh/c1a9502ea05c9fcde03a375ebf528a12ff30cae7/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d7461696b6f2e706e67";
  1615. const fruitsrc = "https://i.ppy.sh/e7cad0470810a868df06d597e3441812659c0bfa/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6672756974732e706e67";
  1616. const maniasrc = "https://i.ppy.sh/55d9494fcf7c3ef2d614695a9a951977a21f23f6/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6d616e69612e706e67";
  1617. const pngsrc = [osusrc, taikosrc, fruitsrc, maniasrc];
  1618. const png = [null, null, null, null];
  1619. let canvas, ctx, cw, ch;
  1620. const ToggleSnow = async (modeid) => {
  1621. if(canvas) {canvas.remove(); return;}
  1622. canvas = HTML("canvas", {style: `position: fixed; bottom: 0px; left: 0px;`, width: window.innerWidth, height: window.innerHeight});
  1623. document.body.append(canvas);
  1624. ctx = canvas.getContext("webgl2");
  1625. if(!png[modeid]){
  1626. const response = await fetch(pngsrc[modeid]);
  1627. png[modeid] = await response.blob();
  1628. }
  1629. }
  1630. */