From f6f56aa09c5184405b7bfe834e6d906a07bc4e04 Mon Sep 17 00:00:00 2001 From: Liam Date: Tue, 17 Oct 2023 23:38:18 +0100 Subject: [PATCH] add and run prettier --- LICENSE.md | 328 ++-- package.json | 1 + public/assets/ss-bulma.css | 1684 ++++++++++++----- public/assets/ssr.css | 197 +- public/assets/swiped-events.min.js | 87 +- public/index.html | 32 +- rollup.config.js | 261 +-- .../Charts/utils/legend-click-handler.js | 58 +- .../Player/Charts/utils/regions-plugin.js | 33 +- src/components/Player/utils/profile.js | 2 +- .../Player/utils/service-param-manager.js | 104 +- src/db/cache.js | 61 +- src/db/db.js | 318 ++-- src/db/fix-data.js | 300 +-- src/db/repositories-init.js | 40 +- src/db/repository/accsaber-categories.js | 4 +- src/db/repository/accsaber-players-history.js | 11 +- src/db/repository/accsaber-players.js | 15 +- src/db/repository/beat-savior-files.js | 4 +- src/db/repository/beat-savior-players.js | 4 +- src/db/repository/beat-savior.js | 11 +- src/db/repository/cache.js | 4 +- src/db/repository/generic.js | 177 +- src/db/repository/groups.js | 10 +- src/db/repository/key-value.js | 4 +- src/db/repository/players-history.js | 11 +- src/db/repository/players.js | 4 +- src/db/repository/rankeds-changes.js | 8 +- src/db/repository/rankeds.js | 4 +- src/db/repository/scores-update-queue.js | 13 +- src/db/repository/scores.js | 19 +- src/db/repository/songs-beatmaps.js | 5 +- src/db/repository/songs.js | 4 +- src/db/repository/twitch.js | 4 +- src/main.js | 55 +- src/network/cache.js | 86 +- .../clients/accsaber/api-categories.js | 19 +- .../clients/accsaber/api-leaderboard.js | 73 +- .../accsaber/api-player-rank-history.js | 51 +- src/network/clients/accsaber/api-ranking.js | 35 +- src/network/clients/accsaber/api-scores.js | 76 +- src/network/clients/beatmaps/api-hash.js | 14 +- src/network/clients/beatmaps/api-key.js | 14 +- src/network/clients/beatmaps/utils/process.js | 12 +- src/network/clients/beatsavior/api.js | 100 +- src/network/clients/generic.js | 38 +- .../leaderboard/page-leaderboard.js | 61 +- src/network/clients/scoresaber/player/api.js | 56 +- src/network/clients/scoresaber/player/page.js | 36 +- .../scoresaber/players/api-player-find.js | 14 +- .../players/api-ranking-global-pages.js | 15 +- .../scoresaber/players/api-ranking-global.js | 14 +- .../players/page-ranking-country.js | 24 +- .../scoresaber/players/utils/process.js | 43 +- .../clients/scoresaber/rankeds/page.js | 14 +- .../clients/scoresaber/scores/api-recent.js | 16 +- .../clients/scoresaber/scores/api-top.js | 16 +- .../scoresaber/scores/utils/process.js | 54 +- src/network/clients/twitch/api-profile.js | 23 +- src/network/clients/twitch/api-videos.js | 16 +- src/network/command-processor.js | 37 +- src/network/download-manager.js | 259 ++- src/network/errors.js | 27 +- src/network/fetch.js | 12 +- src/network/queues/accsaber/api-queue.js | 86 +- src/network/queues/beatmaps/api-queue.js | 22 +- src/network/queues/http-queue.js | 128 +- src/network/queues/queues.js | 114 +- src/network/queues/scoresaber/api-queue.js | 84 +- src/network/queues/scoresaber/page-queue.js | 128 +- src/network/queues/twitch/api-queue.js | 118 +- src/network/utils.js | 12 +- src/others/errors.js | 6 +- src/services/accsaber.js | 632 ++++--- src/services/beatmaps.js | 465 +++-- src/services/beatsavior.js | 370 ++-- src/services/config.js | 19 +- src/services/scoresaber/leaderboard.js | 151 +- src/services/scoresaber/player.js | 408 ++-- src/services/scoresaber/pp.js | 50 +- src/services/scoresaber/rankeds.js | 185 +- src/services/scoresaber/ranking.js | 80 +- src/services/scoresaber/scores.js | 980 ++++++---- src/services/twitch.js | 203 +- src/services/utils.js | 52 +- src/stores/config.js | 82 +- src/stores/container.js | 32 +- src/stores/http/enhancers/common/acc-calc.js | 20 +- src/stores/http/enhancers/common/beatmaps.js | 14 +- .../http/enhancers/leaderboard/rankeds.js | 23 +- src/stores/http/enhancers/scores/acc.js | 24 +- .../http/enhancers/scores/beatsavior.js | 20 +- src/stores/http/enhancers/scores/compare.js | 52 +- src/stores/http/enhancers/scores/diff.js | 40 +- .../http/enhancers/scores/pp-attribution.js | 20 +- src/stores/http/enhancers/scores/twitch.js | 29 +- src/stores/http/http-leaderboard-store.js | 157 +- src/stores/http/http-player-store.js | 25 +- .../http/http-player-with-scores-store.js | 126 +- src/stores/http/http-ranking-store.js | 47 +- src/stores/http/http-scores-store.js | 194 +- src/stores/http/http-store.js | 107 +- .../http/providers/api-player-with-scores.js | 50 +- src/stores/http/providers/api-ranking.js | 40 +- src/stores/http/providers/api-scores.js | 72 +- src/stores/http/providers/page-leaderboard.js | 49 +- .../http/providers/utils/scores-fetch.js | 59 +- src/stores/scoresaber/friends.js | 20 +- src/stores/scoresaber/players.js | 38 +- src/stores/scoresaber/rankeds.js | 40 +- src/svelte-utils/actions/hoverable.js | 65 +- src/svelte-utils/tweened.js | 7 +- src/utils/accsaber/consts.js | 2 +- src/utils/broadcast-channel-pubsub.js | 143 +- src/utils/browser.js | 8 +- src/utils/cf-email-decrypt.js | 77 +- src/utils/clipboard.js | 54 +- src/utils/date.js | 292 +-- src/utils/debounce.js | 25 +- src/utils/download.js | 22 +- src/utils/export-import.js | 451 +++-- src/utils/format.js | 26 +- src/utils/js.js | 56 +- src/utils/logger.js | 67 +- src/utils/pending-promises.js | 15 +- src/utils/promise.js | 27 +- src/utils/queue.js | 66 +- src/utils/scoresaber/consts.js | 2 +- src/utils/scoresaber/format.js | 84 +- src/utils/scoresaber/pp.js | 6 +- src/utils/scoresaber/song.js | 117 +- src/utils/uuid.js | 41 +- src/utils/worker-wrappers.js | 12 +- src/workers/stats-worker.js | 247 ++- tsconfig.json | 2 +- yarn.lock | 5 + 136 files changed, 8231 insertions(+), 4493 deletions(-) diff --git a/LICENSE.md b/LICENSE.md index f288702..a5eae15 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,190 +1,190 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. Preamble - The GNU General Public License is a free, copyleft license for +The GNU General Public License is a free, copyleft license for software and other kinds of works. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the +software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to +any other work released this way by its authors. You can apply it to your programs, too. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. - For example, if you distribute copies of such a program, whether +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they know their rights. - Developers that use the GNU GPL protect your rights with two steps: +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. - Some devices are designed to deny users access to install or run +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we +use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we +products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. - Finally, every program is threatened constantly by software patents. +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that +make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. - The precise terms and conditions for copying, distribution and +The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS - 0. Definitions. +0. Definitions. - "This License" refers to version 3 of the GNU General Public License. +"This License" refers to version 3 of the GNU General Public License. - "Copyright" also means copyright-like laws that apply to other kinds of +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. - To "modify" a work means to copy from or adapt all or part of the work +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the +exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. - A "covered work" means either the unmodified Program or a work based +A "covered work" means either the unmodified Program or a work based on the Program. - To "propagate" a work means to do anything with it that, without +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, +computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - An interactive user interface displays "Appropriate Legal Notices" +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If +work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - 1. Source Code. +1. Source Code. - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source form of a work. - A "Standard Interface" means an interface that either is an official +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - The "System Libraries" of an executable work include anything, other +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A +implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - The "Corresponding Source" for a work in object code form means all +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's +control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source +which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - The Corresponding Source need not include anything that users +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - The Corresponding Source for a work in source code form is that +The Corresponding Source for a work in source code form is that same work. - 2. Basic Permissions. +2. Basic Permissions. - All rights granted under this License are granted for the term of +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your +content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - You may make, run and propagate covered works that you do not +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose +in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works +not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - When you convey a covered work, you waive any legal power to forbid +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or @@ -192,9 +192,9 @@ modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - 4. Conveying Verbatim Copies. +4. Conveying Verbatim Copies. - You may convey verbatim copies of the Program's source code as you +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any @@ -202,12 +202,12 @@ non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - You may charge any price or no price for each copy that you convey, +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - 5. Conveying Modified Source Versions. +5. Conveying Modified Source Versions. - You may convey a work based on the Program, or the modifications to +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: @@ -232,19 +232,19 @@ terms of section 4, provided that you also meet all of these conditions: interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - A compilation of a covered work with other separate and independent +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work +beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - 6. Conveying Non-Source Forms. +6. Conveying Non-Source Forms. - You may convey a covered work in object code form under the terms +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: @@ -290,75 +290,75 @@ in one of these ways: Source of the work are being offered to the general public at no charge under subsection 6d. - A separable portion of the object code, whose source code is excluded +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - A "User Product" is either (1) a "consumer product", which means any +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product +actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - "Installation Information" for a User Product means any methods, +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must +a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - If you convey an object code work under this section in, or with, or +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply +by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - The requirement to provide Installation Information does not include a +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a +the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - Corresponding Source conveyed, and Installation Information provided, +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - 7. Additional Terms. +7. Additional Terms. - "Additional permissions" are terms that supplement the terms of this +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions +that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - When you convey a copy of a covered work, you may at your option +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - Notwithstanding any other provision of this License, for material you +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: @@ -385,74 +385,74 @@ that material) supplement the terms of this License with terms: any liability that these contractual assumptions directly impose on those licensors and authors. - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains +restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - If you add terms to a covered work in accord with this section, you +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - Additional terms, permissive or non-permissive, may be stated in the +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - 8. Termination. +8. Termination. - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - However, if you cease all violation of this License, then your +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - Moreover, your license from a particular copyright holder is +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - Termination of your rights under this section does not terminate the +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently +this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - 9. Acceptance Not Required for Having Copies. +9. Acceptance Not Required for Having Copies. - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, +to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - 10. Automatic Licensing of Downstream Recipients. +10. Automatic Licensing of Downstream Recipients. - Each time you convey a covered work, the recipient automatically +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible +propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - An "entity transaction" is a transaction transferring control of an +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered +organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could @@ -460,43 +460,43 @@ give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - 11. Patents. +11. Patents. - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - A contributor's "essential patent claims" are all patent claims +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For +consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - In the following three paragraphs, a "patent license" is any express +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a +sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - If you convey a covered work, knowingly relying on a patent license, +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, @@ -504,13 +504,13 @@ then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - If, pursuant to or in connection with a single transaction or +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify @@ -518,10 +518,10 @@ or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - A patent license is "discriminatory" if it does not include within +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered +specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying @@ -533,73 +533,73 @@ for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - Nothing in this License shall be construed as excluding or limiting +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - 12. No Surrender of Others' Freedom. +12. No Surrender of Others' Freedom. - If conditions are imposed on you (whether by court order, agreement or +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a +excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. +13. Use with the GNU Affero General Public License. - Notwithstanding any other provision of this License, you have +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this +combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. - 14. Revised Versions of this License. +14. Revised Versions of this License. - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the +Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. - If the Program specifies that a proxy can decide which future +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - 15. Disclaimer of Warranty. +15. Disclaimer of Warranty. - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - 16. Limitation of Liability. +16. Limitation of Liability. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE @@ -609,9 +609,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - 17. Interpretation of Sections 15 and 16. +17. Interpretation of Sections 15 and 16. - If the disclaimer of warranty and limitation of liability provided +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the @@ -622,11 +622,11 @@ copy of the Program in return for a fee. How to Apply These Terms to Your New Programs - If you develop a new program, and you want it to be of the greatest +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. - To do so, attach the following notices to the program. It is safest +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. @@ -649,7 +649,7 @@ the "copyright" line and a pointer to where the full notice is found. Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) @@ -658,17 +658,17 @@ notice like this when it starts in an interactive mode: under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands +parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". - You should also get your employer (if you work as a programmer) or school, +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you +The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read . diff --git a/package.json b/package.json index 14d2021..846905d 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "json-stable-stringify": "^1.0.1", "luxon": "^2.0.2", "p-queue": "^7.1.0", + "prettier": "3.0.3", "rollup": "^2.3.4", "rollup-plugin-css-only": "^3.1.0", "rollup-plugin-livereload": "^2.0.0", diff --git a/public/assets/ss-bulma.css b/public/assets/ss-bulma.css index 895f301..6c457b6 100644 --- a/public/assets/ss-bulma.css +++ b/public/assets/ss-bulma.css @@ -7,10 +7,17 @@ transform: rotate(359deg); } } -.tabs, .pagination-previous, +.tabs, +.pagination-previous, .pagination-next, .pagination-link, -.pagination-ellipsis, .breadcrumb, .file, .button, .is-unselectable, .modal-close, .delete { +.pagination-ellipsis, +.breadcrumb, +.file, +.button, +.is-unselectable, +.modal-close, +.delete { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; @@ -18,7 +25,8 @@ user-select: none; } -.navbar-link:not(.is-arrowless)::after, .select:not(.is-multiple):not(.is-loading)::after { +.navbar-link:not(.is-arrowless)::after, +.select:not(.is-multiple):not(.is-loading)::after { border: 3px solid transparent; border-radius: 2px; border-right: 0; @@ -35,12 +43,25 @@ width: 0.625em; } -.tabs:not(:last-child), .message:not(:last-child), .level:not(:last-child), .breadcrumb:not(:last-child), .highlight:not(:last-child), .block:not(:last-child), .title:not(:last-child), -.subtitle:not(:last-child), .table-container:not(:last-child), .table:not(:last-child), .progress:not(:last-child), .notification:not(:last-child), .content:not(:last-child), .box:not(:last-child) { +.tabs:not(:last-child), +.message:not(:last-child), +.level:not(:last-child), +.breadcrumb:not(:last-child), +.highlight:not(:last-child), +.block:not(:last-child), +.title:not(:last-child), +.subtitle:not(:last-child), +.table-container:not(:last-child), +.table:not(:last-child), +.progress:not(:last-child), +.notification:not(:last-child), +.content:not(:last-child), +.box:not(:last-child) { margin-bottom: 1.5rem; } -.modal-close, .delete { +.modal-close, +.delete { -moz-appearance: none; -webkit-appearance: none; background-color: rgba(10, 10, 10, 0.2); @@ -62,7 +83,10 @@ vertical-align: top; width: 20px; } -.modal-close::before, .delete::before, .modal-close::after, .delete::after { +.modal-close::before, +.delete::before, +.modal-close::after, +.delete::after { background-color: white; content: ""; display: block; @@ -72,21 +96,28 @@ transform: translateX(-50%) translateY(-50%) rotate(45deg); transform-origin: center center; } -.modal-close::before, .delete::before { +.modal-close::before, +.delete::before { height: 2px; width: 50%; } -.modal-close::after, .delete::after { +.modal-close::after, +.delete::after { height: 50%; width: 2px; } -.modal-close:hover, .delete:hover, .modal-close:focus, .delete:focus { +.modal-close:hover, +.delete:hover, +.modal-close:focus, +.delete:focus { background-color: rgba(10, 10, 10, 0.3); } -.modal-close:active, .delete:active { +.modal-close:active, +.delete:active { background-color: rgba(10, 10, 10, 0.4); } -.is-small.modal-close, .is-small.delete { +.is-small.modal-close, +.is-small.delete { height: 16px; max-height: 16px; max-width: 16px; @@ -94,7 +125,8 @@ min-width: 16px; width: 16px; } -.is-medium.modal-close, .is-medium.delete { +.is-medium.modal-close, +.is-medium.delete { height: 24px; max-height: 24px; max-width: 24px; @@ -102,7 +134,8 @@ min-width: 24px; width: 24px; } -.is-large.modal-close, .is-large.delete { +.is-large.modal-close, +.is-large.delete { height: 32px; max-height: 32px; max-width: 32px; @@ -111,7 +144,10 @@ width: 32px; } -.loader, .control.is-loading::after, .select.is-loading::after, .button.is-loading::after { +.loader, +.control.is-loading::after, +.select.is-loading::after, +.button.is-loading::after { animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; @@ -124,7 +160,26 @@ width: 1em; } -.hero-video, .modal-background, .modal, .image.is-square img, .image.is-1by1 img, .image.is-5by4 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-5by3 img, .image.is-16by9 img, .image.is-2by1 img, .image.is-3by1 img, .image.is-4by5 img, .image.is-3by4 img, .image.is-2by3 img, .image.is-3by5 img, .image.is-9by16 img, .image.is-1by2 img, .image.is-1by3 img, .is-overlay { +.hero-video, +.modal-background, +.modal, +.image.is-square img, +.image.is-1by1 img, +.image.is-5by4 img, +.image.is-4by3 img, +.image.is-3by2 img, +.image.is-5by3 img, +.image.is-16by9 img, +.image.is-2by1 img, +.image.is-3by1 img, +.image.is-4by5 img, +.image.is-3by4 img, +.image.is-2by3 img, +.image.is-3by5 img, +.image.is-9by16 img, +.image.is-1by2 img, +.image.is-1by3 img, +.is-overlay { bottom: 0; left: 0; position: absolute; @@ -135,9 +190,13 @@ .pagination-previous, .pagination-next, .pagination-link, -.pagination-ellipsis, .file-cta, -.file-name, .select select, .input, -.textarea, .button { +.pagination-ellipsis, +.file-cta, +.file-name, +.select select, +.input, +.textarea, +.button { -moz-appearance: none; -webkit-appearance: none; align-items: center; @@ -159,32 +218,55 @@ .pagination-previous:focus, .pagination-next:focus, .pagination-link:focus, -.pagination-ellipsis:focus, .file-cta:focus, -.file-name:focus, .select select:focus, .input:focus, -.textarea:focus, .button:focus, .is-focused.pagination-previous, +.pagination-ellipsis:focus, +.file-cta:focus, +.file-name:focus, +.select select:focus, +.input:focus, +.textarea:focus, +.button:focus, +.is-focused.pagination-previous, .is-focused.pagination-next, .is-focused.pagination-link, -.is-focused.pagination-ellipsis, .is-focused.file-cta, -.is-focused.file-name, .select select.is-focused, .is-focused.input, -.is-focused.textarea, .is-focused.button, .pagination-previous:active, +.is-focused.pagination-ellipsis, +.is-focused.file-cta, +.is-focused.file-name, +.select select.is-focused, +.is-focused.input, +.is-focused.textarea, +.is-focused.button, +.pagination-previous:active, .pagination-next:active, .pagination-link:active, -.pagination-ellipsis:active, .file-cta:active, -.file-name:active, .select select:active, .input:active, -.textarea:active, .button:active, .is-active.pagination-previous, +.pagination-ellipsis:active, +.file-cta:active, +.file-name:active, +.select select:active, +.input:active, +.textarea:active, +.button:active, +.is-active.pagination-previous, .is-active.pagination-next, .is-active.pagination-link, -.is-active.pagination-ellipsis, .is-active.file-cta, -.is-active.file-name, .select select.is-active, .is-active.input, -.is-active.textarea, .is-active.button { +.is-active.pagination-ellipsis, +.is-active.file-cta, +.is-active.file-name, +.select select.is-active, +.is-active.input, +.is-active.textarea, +.is-active.button { outline: none; } [disabled].pagination-previous, [disabled].pagination-next, [disabled].pagination-link, -[disabled].pagination-ellipsis, [disabled].file-cta, -[disabled].file-name, .select select[disabled], [disabled].input, -[disabled].textarea, [disabled].button { +[disabled].pagination-ellipsis, +[disabled].file-cta, +[disabled].file-name, +.select select[disabled], +[disabled].input, +[disabled].textarea, +[disabled].button { cursor: not-allowed; } @@ -196,10 +278,17 @@ transform: rotate(359deg); } } -.tabs, .pagination-previous, +.tabs, +.pagination-previous, .pagination-next, .pagination-link, -.pagination-ellipsis, .breadcrumb, .file, .button, .is-unselectable, .modal-close, .delete { +.pagination-ellipsis, +.breadcrumb, +.file, +.button, +.is-unselectable, +.modal-close, +.delete { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; @@ -207,7 +296,8 @@ user-select: none; } -.navbar-link:not(.is-arrowless)::after, .select:not(.is-multiple):not(.is-loading)::after { +.navbar-link:not(.is-arrowless)::after, +.select:not(.is-multiple):not(.is-loading)::after { border: 3px solid transparent; border-radius: 2px; border-right: 0; @@ -224,12 +314,25 @@ width: 0.625em; } -.tabs:not(:last-child), .message:not(:last-child), .level:not(:last-child), .breadcrumb:not(:last-child), .highlight:not(:last-child), .block:not(:last-child), .title:not(:last-child), -.subtitle:not(:last-child), .table-container:not(:last-child), .table:not(:last-child), .progress:not(:last-child), .notification:not(:last-child), .content:not(:last-child), .box:not(:last-child) { +.tabs:not(:last-child), +.message:not(:last-child), +.level:not(:last-child), +.breadcrumb:not(:last-child), +.highlight:not(:last-child), +.block:not(:last-child), +.title:not(:last-child), +.subtitle:not(:last-child), +.table-container:not(:last-child), +.table:not(:last-child), +.progress:not(:last-child), +.notification:not(:last-child), +.content:not(:last-child), +.box:not(:last-child) { margin-bottom: 1.5rem; } -.modal-close, .delete { +.modal-close, +.delete { -moz-appearance: none; -webkit-appearance: none; background-color: rgba(10, 10, 10, 0.2); @@ -251,7 +354,10 @@ vertical-align: top; width: 20px; } -.modal-close::before, .delete::before, .modal-close::after, .delete::after { +.modal-close::before, +.delete::before, +.modal-close::after, +.delete::after { background-color: white; content: ""; display: block; @@ -261,21 +367,28 @@ transform: translateX(-50%) translateY(-50%) rotate(45deg); transform-origin: center center; } -.modal-close::before, .delete::before { +.modal-close::before, +.delete::before { height: 2px; width: 50%; } -.modal-close::after, .delete::after { +.modal-close::after, +.delete::after { height: 50%; width: 2px; } -.modal-close:hover, .delete:hover, .modal-close:focus, .delete:focus { +.modal-close:hover, +.delete:hover, +.modal-close:focus, +.delete:focus { background-color: rgba(10, 10, 10, 0.3); } -.modal-close:active, .delete:active { +.modal-close:active, +.delete:active { background-color: rgba(10, 10, 10, 0.4); } -.is-small.modal-close, .is-small.delete { +.is-small.modal-close, +.is-small.delete { height: 16px; max-height: 16px; max-width: 16px; @@ -283,7 +396,8 @@ min-width: 16px; width: 16px; } -.is-medium.modal-close, .is-medium.delete { +.is-medium.modal-close, +.is-medium.delete { height: 24px; max-height: 24px; max-width: 24px; @@ -291,7 +405,8 @@ min-width: 24px; width: 24px; } -.is-large.modal-close, .is-large.delete { +.is-large.modal-close, +.is-large.delete { height: 32px; max-height: 32px; max-width: 32px; @@ -300,7 +415,10 @@ width: 32px; } -.loader, .control.is-loading::after, .select.is-loading::after, .button.is-loading::after { +.loader, +.control.is-loading::after, +.select.is-loading::after, +.button.is-loading::after { animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; @@ -313,7 +431,26 @@ width: 1em; } -.hero-video, .modal-background, .modal, .image.is-square img, .image.is-1by1 img, .image.is-5by4 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-5by3 img, .image.is-16by9 img, .image.is-2by1 img, .image.is-3by1 img, .image.is-4by5 img, .image.is-3by4 img, .image.is-2by3 img, .image.is-3by5 img, .image.is-9by16 img, .image.is-1by2 img, .image.is-1by3 img, .is-overlay { +.hero-video, +.modal-background, +.modal, +.image.is-square img, +.image.is-1by1 img, +.image.is-5by4 img, +.image.is-4by3 img, +.image.is-3by2 img, +.image.is-5by3 img, +.image.is-16by9 img, +.image.is-2by1 img, +.image.is-3by1 img, +.image.is-4by5 img, +.image.is-3by4 img, +.image.is-2by3 img, +.image.is-3by5 img, +.image.is-9by16 img, +.image.is-1by2 img, +.image.is-1by3 img, +.is-overlay { bottom: 0; left: 0; position: absolute; @@ -324,9 +461,13 @@ .pagination-previous, .pagination-next, .pagination-link, -.pagination-ellipsis, .file-cta, -.file-name, .select select, .input, -.textarea, .button { +.pagination-ellipsis, +.file-cta, +.file-name, +.select select, +.input, +.textarea, +.button { -moz-appearance: none; -webkit-appearance: none; align-items: center; @@ -348,32 +489,55 @@ .pagination-previous:focus, .pagination-next:focus, .pagination-link:focus, -.pagination-ellipsis:focus, .file-cta:focus, -.file-name:focus, .select select:focus, .input:focus, -.textarea:focus, .button:focus, .is-focused.pagination-previous, +.pagination-ellipsis:focus, +.file-cta:focus, +.file-name:focus, +.select select:focus, +.input:focus, +.textarea:focus, +.button:focus, +.is-focused.pagination-previous, .is-focused.pagination-next, .is-focused.pagination-link, -.is-focused.pagination-ellipsis, .is-focused.file-cta, -.is-focused.file-name, .select select.is-focused, .is-focused.input, -.is-focused.textarea, .is-focused.button, .pagination-previous:active, +.is-focused.pagination-ellipsis, +.is-focused.file-cta, +.is-focused.file-name, +.select select.is-focused, +.is-focused.input, +.is-focused.textarea, +.is-focused.button, +.pagination-previous:active, .pagination-next:active, .pagination-link:active, -.pagination-ellipsis:active, .file-cta:active, -.file-name:active, .select select:active, .input:active, -.textarea:active, .button:active, .is-active.pagination-previous, +.pagination-ellipsis:active, +.file-cta:active, +.file-name:active, +.select select:active, +.input:active, +.textarea:active, +.button:active, +.is-active.pagination-previous, .is-active.pagination-next, .is-active.pagination-link, -.is-active.pagination-ellipsis, .is-active.file-cta, -.is-active.file-name, .select select.is-active, .is-active.input, -.is-active.textarea, .is-active.button { +.is-active.pagination-ellipsis, +.is-active.file-cta, +.is-active.file-name, +.select select.is-active, +.is-active.input, +.is-active.textarea, +.is-active.button { outline: none; } [disabled].pagination-previous, [disabled].pagination-next, [disabled].pagination-link, -[disabled].pagination-ellipsis, [disabled].file-cta, -[disabled].file-name, .select select[disabled], [disabled].input, -[disabled].textarea, [disabled].button { +[disabled].pagination-ellipsis, +[disabled].file-cta, +[disabled].file-name, +.select select[disabled], +[disabled].input, +[disabled].textarea, +[disabled].button { cursor: not-allowed; } @@ -430,7 +594,9 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::before, +*::after { box-sizing: inherit; } @@ -483,7 +649,20 @@ button, input, select, textarea { - font-family: BlinkMacSystemFont, -apple-system, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif; + font-family: + BlinkMacSystemFont, + -apple-system, + "Segoe UI", + "Roboto", + "Oxygen", + "Ubuntu", + "Cantarell", + "Fira Sans", + "Droid Sans", + "Helvetica Neue", + "Helvetica", + "Arial", + sans-serif; } code, @@ -533,8 +712,8 @@ img { max-width: 100%; } -input[type=checkbox], -input[type=radio] { +input[type="checkbox"], +input[type="radio"] { vertical-align: baseline; } @@ -1014,7 +1193,8 @@ table th { color: white !important; } -a.has-text-white:hover, a.has-text-white:focus { +a.has-text-white:hover, +a.has-text-white:focus { color: #e6e6e6 !important; } @@ -1026,7 +1206,8 @@ a.has-text-white:hover, a.has-text-white:focus { color: #0a0a0a !important; } -a.has-text-black:hover, a.has-text-black:focus { +a.has-text-black:hover, +a.has-text-black:focus { color: black !important; } @@ -1038,7 +1219,8 @@ a.has-text-black:hover, a.has-text-black:focus { color: whitesmoke !important; } -a.has-text-light:hover, a.has-text-light:focus { +a.has-text-light:hover, +a.has-text-light:focus { color: #dbdbdb !important; } @@ -1050,7 +1232,8 @@ a.has-text-light:hover, a.has-text-light:focus { color: #363636 !important; } -a.has-text-dark:hover, a.has-text-dark:focus { +a.has-text-dark:hover, +a.has-text-dark:focus { color: #1c1c1c !important; } @@ -1062,7 +1245,8 @@ a.has-text-dark:hover, a.has-text-dark:focus { color: #00d1b2 !important; } -a.has-text-primary:hover, a.has-text-primary:focus { +a.has-text-primary:hover, +a.has-text-primary:focus { color: #009e86 !important; } @@ -1074,7 +1258,8 @@ a.has-text-primary:hover, a.has-text-primary:focus { color: #3273dc !important; } -a.has-text-link:hover, a.has-text-link:focus { +a.has-text-link:hover, +a.has-text-link:focus { color: #205bbc !important; } @@ -1086,7 +1271,8 @@ a.has-text-link:hover, a.has-text-link:focus { color: #209cee !important; } -a.has-text-info:hover, a.has-text-info:focus { +a.has-text-info:hover, +a.has-text-info:focus { color: #0f81cc !important; } @@ -1098,7 +1284,8 @@ a.has-text-info:hover, a.has-text-info:focus { color: #23d160 !important; } -a.has-text-success:hover, a.has-text-success:focus { +a.has-text-success:hover, +a.has-text-success:focus { color: #1ca64c !important; } @@ -1110,7 +1297,8 @@ a.has-text-success:hover, a.has-text-success:focus { color: #ffdd57 !important; } -a.has-text-warning:hover, a.has-text-warning:focus { +a.has-text-warning:hover, +a.has-text-warning:focus { color: #ffd324 !important; } @@ -1122,7 +1310,8 @@ a.has-text-warning:hover, a.has-text-warning:focus { color: #ff3860 !important; } -a.has-text-danger:hover, a.has-text-danger:focus { +a.has-text-danger:hover, +a.has-text-danger:focus { color: #ff0537 !important; } @@ -1591,17 +1780,24 @@ a.has-text-danger:hover, a.has-text-danger:focus { .box { background-color: white; border-radius: 6px; - box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); + box-shadow: + 0 2px 3px rgba(10, 10, 10, 0.1), + 0 0 0 1px rgba(10, 10, 10, 0.1); color: #4a4a4a; display: block; padding: 1.25rem; } -a.box:hover, a.box:focus { - box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px #3273dc; +a.box:hover, +a.box:focus { + box-shadow: + 0 2px 3px rgba(10, 10, 10, 0.1), + 0 0 0 1px #3273dc; } a.box:active { - box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2), 0 0 0 1px #3273dc; + box-shadow: + inset 0 1px 2px rgba(10, 10, 10, 0.2), + 0 0 0 1px #3273dc; } .button { @@ -1621,7 +1817,10 @@ a.box:active { .button strong { color: inherit; } -.button .icon, .button .icon.is-small, .button .icon.is-medium, .button .icon.is-large { +.button .icon, +.button .icon.is-small, +.button .icon.is-medium, +.button .icon.is-large { height: 1.5em; width: 1.5em; } @@ -1637,18 +1836,22 @@ a.box:active { margin-left: calc(-0.375em - 1px); margin-right: calc(-0.375em - 1px); } -.button:hover, .button.is-hovered { +.button:hover, +.button.is-hovered { border-color: #b5b5b5; color: #363636; } -.button:focus, .button.is-focused { +.button:focus, +.button.is-focused { border-color: #3273dc; color: #363636; } -.button:focus:not(:active), .button.is-focused:not(:active) { +.button:focus:not(:active), +.button.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } -.button:active, .button.is-active { +.button:active, +.button.is-active { border-color: #4a4a4a; color: #363636; } @@ -1658,11 +1861,15 @@ a.box:active { color: #4a4a4a; text-decoration: underline; } -.button.is-text:hover, .button.is-text.is-hovered, .button.is-text:focus, .button.is-text.is-focused { +.button.is-text:hover, +.button.is-text.is-hovered, +.button.is-text:focus, +.button.is-text.is-focused { background-color: whitesmoke; color: #363636; } -.button.is-text:active, .button.is-text.is-active { +.button.is-text:active, +.button.is-text.is-active { background-color: #e8e8e8; color: #363636; } @@ -1676,19 +1883,23 @@ a.box:active { border-color: transparent; color: #0a0a0a; } -.button.is-white:hover, .button.is-white.is-hovered { +.button.is-white:hover, +.button.is-white.is-hovered { background-color: #f9f9f9; border-color: transparent; color: #0a0a0a; } -.button.is-white:focus, .button.is-white.is-focused { +.button.is-white:focus, +.button.is-white.is-focused { border-color: transparent; color: #0a0a0a; } -.button.is-white:focus:not(:active), .button.is-white.is-focused:not(:active) { +.button.is-white:focus:not(:active), +.button.is-white.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); } -.button.is-white:active, .button.is-white.is-active { +.button.is-white:active, +.button.is-white.is-active { background-color: #f2f2f2; border-color: transparent; color: #0a0a0a; @@ -1719,7 +1930,8 @@ a.box:active { border-color: white; color: white; } -.button.is-white.is-outlined:hover, .button.is-white.is-outlined:focus { +.button.is-white.is-outlined:hover, +.button.is-white.is-outlined:focus { background-color: white; border-color: white; color: #0a0a0a; @@ -1738,7 +1950,8 @@ a.box:active { border-color: #0a0a0a; color: #0a0a0a; } -.button.is-white.is-inverted.is-outlined:hover, .button.is-white.is-inverted.is-outlined:focus { +.button.is-white.is-inverted.is-outlined:hover, +.button.is-white.is-inverted.is-outlined:focus { background-color: #0a0a0a; color: white; } @@ -1753,19 +1966,23 @@ a.box:active { border-color: transparent; color: white; } -.button.is-black:hover, .button.is-black.is-hovered { +.button.is-black:hover, +.button.is-black.is-hovered { background-color: #040404; border-color: transparent; color: white; } -.button.is-black:focus, .button.is-black.is-focused { +.button.is-black:focus, +.button.is-black.is-focused { border-color: transparent; color: white; } -.button.is-black:focus:not(:active), .button.is-black.is-focused:not(:active) { +.button.is-black:focus:not(:active), +.button.is-black.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); } -.button.is-black:active, .button.is-black.is-active { +.button.is-black:active, +.button.is-black.is-active { background-color: black; border-color: transparent; color: white; @@ -1796,7 +2013,8 @@ a.box:active { border-color: #0a0a0a; color: #0a0a0a; } -.button.is-black.is-outlined:hover, .button.is-black.is-outlined:focus { +.button.is-black.is-outlined:hover, +.button.is-black.is-outlined:focus { background-color: #0a0a0a; border-color: #0a0a0a; color: white; @@ -1815,7 +2033,8 @@ a.box:active { border-color: white; color: white; } -.button.is-black.is-inverted.is-outlined:hover, .button.is-black.is-inverted.is-outlined:focus { +.button.is-black.is-inverted.is-outlined:hover, +.button.is-black.is-inverted.is-outlined:focus { background-color: white; color: #0a0a0a; } @@ -1830,19 +2049,23 @@ a.box:active { border-color: transparent; color: #363636; } -.button.is-light:hover, .button.is-light.is-hovered { +.button.is-light:hover, +.button.is-light.is-hovered { background-color: #eeeeee; border-color: transparent; color: #363636; } -.button.is-light:focus, .button.is-light.is-focused { +.button.is-light:focus, +.button.is-light.is-focused { border-color: transparent; color: #363636; } -.button.is-light:focus:not(:active), .button.is-light.is-focused:not(:active) { +.button.is-light:focus:not(:active), +.button.is-light.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); } -.button.is-light:active, .button.is-light.is-active { +.button.is-light:active, +.button.is-light.is-active { background-color: #e8e8e8; border-color: transparent; color: #363636; @@ -1873,7 +2096,8 @@ a.box:active { border-color: whitesmoke; color: whitesmoke; } -.button.is-light.is-outlined:hover, .button.is-light.is-outlined:focus { +.button.is-light.is-outlined:hover, +.button.is-light.is-outlined:focus { background-color: whitesmoke; border-color: whitesmoke; color: #363636; @@ -1892,7 +2116,8 @@ a.box:active { border-color: #363636; color: #363636; } -.button.is-light.is-inverted.is-outlined:hover, .button.is-light.is-inverted.is-outlined:focus { +.button.is-light.is-inverted.is-outlined:hover, +.button.is-light.is-inverted.is-outlined:focus { background-color: #363636; color: whitesmoke; } @@ -1907,19 +2132,23 @@ a.box:active { border-color: transparent; color: whitesmoke; } -.button.is-dark:hover, .button.is-dark.is-hovered { +.button.is-dark:hover, +.button.is-dark.is-hovered { background-color: #2f2f2f; border-color: transparent; color: whitesmoke; } -.button.is-dark:focus, .button.is-dark.is-focused { +.button.is-dark:focus, +.button.is-dark.is-focused { border-color: transparent; color: whitesmoke; } -.button.is-dark:focus:not(:active), .button.is-dark.is-focused:not(:active) { +.button.is-dark:focus:not(:active), +.button.is-dark.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); } -.button.is-dark:active, .button.is-dark.is-active { +.button.is-dark:active, +.button.is-dark.is-active { background-color: #292929; border-color: transparent; color: whitesmoke; @@ -1950,7 +2179,8 @@ a.box:active { border-color: #363636; color: #363636; } -.button.is-dark.is-outlined:hover, .button.is-dark.is-outlined:focus { +.button.is-dark.is-outlined:hover, +.button.is-dark.is-outlined:focus { background-color: #363636; border-color: #363636; color: whitesmoke; @@ -1969,7 +2199,8 @@ a.box:active { border-color: whitesmoke; color: whitesmoke; } -.button.is-dark.is-inverted.is-outlined:hover, .button.is-dark.is-inverted.is-outlined:focus { +.button.is-dark.is-inverted.is-outlined:hover, +.button.is-dark.is-inverted.is-outlined:focus { background-color: whitesmoke; color: #363636; } @@ -1984,19 +2215,23 @@ a.box:active { border-color: transparent; color: #fff; } -.button.is-primary:hover, .button.is-primary.is-hovered { +.button.is-primary:hover, +.button.is-primary.is-hovered { background-color: #00c4a7; border-color: transparent; color: #fff; } -.button.is-primary:focus, .button.is-primary.is-focused { +.button.is-primary:focus, +.button.is-primary.is-focused { border-color: transparent; color: #fff; } -.button.is-primary:focus:not(:active), .button.is-primary.is-focused:not(:active) { +.button.is-primary:focus:not(:active), +.button.is-primary.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); } -.button.is-primary:active, .button.is-primary.is-active { +.button.is-primary:active, +.button.is-primary.is-active { background-color: #00b89c; border-color: transparent; color: #fff; @@ -2027,7 +2262,8 @@ a.box:active { border-color: #00d1b2; color: #00d1b2; } -.button.is-primary.is-outlined:hover, .button.is-primary.is-outlined:focus { +.button.is-primary.is-outlined:hover, +.button.is-primary.is-outlined:focus { background-color: #00d1b2; border-color: #00d1b2; color: #fff; @@ -2046,7 +2282,8 @@ a.box:active { border-color: #fff; color: #fff; } -.button.is-primary.is-inverted.is-outlined:hover, .button.is-primary.is-inverted.is-outlined:focus { +.button.is-primary.is-inverted.is-outlined:hover, +.button.is-primary.is-inverted.is-outlined:focus { background-color: #fff; color: #00d1b2; } @@ -2061,19 +2298,23 @@ a.box:active { border-color: transparent; color: #fff; } -.button.is-link:hover, .button.is-link.is-hovered { +.button.is-link:hover, +.button.is-link.is-hovered { background-color: #276cda; border-color: transparent; color: #fff; } -.button.is-link:focus, .button.is-link.is-focused { +.button.is-link:focus, +.button.is-link.is-focused { border-color: transparent; color: #fff; } -.button.is-link:focus:not(:active), .button.is-link.is-focused:not(:active) { +.button.is-link:focus:not(:active), +.button.is-link.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } -.button.is-link:active, .button.is-link.is-active { +.button.is-link:active, +.button.is-link.is-active { background-color: #2366d1; border-color: transparent; color: #fff; @@ -2104,7 +2345,8 @@ a.box:active { border-color: #3273dc; color: #3273dc; } -.button.is-link.is-outlined:hover, .button.is-link.is-outlined:focus { +.button.is-link.is-outlined:hover, +.button.is-link.is-outlined:focus { background-color: #3273dc; border-color: #3273dc; color: #fff; @@ -2123,7 +2365,8 @@ a.box:active { border-color: #fff; color: #fff; } -.button.is-link.is-inverted.is-outlined:hover, .button.is-link.is-inverted.is-outlined:focus { +.button.is-link.is-inverted.is-outlined:hover, +.button.is-link.is-inverted.is-outlined:focus { background-color: #fff; color: #3273dc; } @@ -2138,19 +2381,23 @@ a.box:active { border-color: transparent; color: #fff; } -.button.is-info:hover, .button.is-info.is-hovered { +.button.is-info:hover, +.button.is-info.is-hovered { background-color: #1496ed; border-color: transparent; color: #fff; } -.button.is-info:focus, .button.is-info.is-focused { +.button.is-info:focus, +.button.is-info.is-focused { border-color: transparent; color: #fff; } -.button.is-info:focus:not(:active), .button.is-info.is-focused:not(:active) { +.button.is-info:focus:not(:active), +.button.is-info.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); } -.button.is-info:active, .button.is-info.is-active { +.button.is-info:active, +.button.is-info.is-active { background-color: #118fe4; border-color: transparent; color: #fff; @@ -2181,7 +2428,8 @@ a.box:active { border-color: #209cee; color: #209cee; } -.button.is-info.is-outlined:hover, .button.is-info.is-outlined:focus { +.button.is-info.is-outlined:hover, +.button.is-info.is-outlined:focus { background-color: #209cee; border-color: #209cee; color: #fff; @@ -2200,7 +2448,8 @@ a.box:active { border-color: #fff; color: #fff; } -.button.is-info.is-inverted.is-outlined:hover, .button.is-info.is-inverted.is-outlined:focus { +.button.is-info.is-inverted.is-outlined:hover, +.button.is-info.is-inverted.is-outlined:focus { background-color: #fff; color: #209cee; } @@ -2215,19 +2464,23 @@ a.box:active { border-color: transparent; color: #fff; } -.button.is-success:hover, .button.is-success.is-hovered { +.button.is-success:hover, +.button.is-success.is-hovered { background-color: #22c65b; border-color: transparent; color: #fff; } -.button.is-success:focus, .button.is-success.is-focused { +.button.is-success:focus, +.button.is-success.is-focused { border-color: transparent; color: #fff; } -.button.is-success:focus:not(:active), .button.is-success.is-focused:not(:active) { +.button.is-success:focus:not(:active), +.button.is-success.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); } -.button.is-success:active, .button.is-success.is-active { +.button.is-success:active, +.button.is-success.is-active { background-color: #20bc56; border-color: transparent; color: #fff; @@ -2258,7 +2511,8 @@ a.box:active { border-color: #23d160; color: #23d160; } -.button.is-success.is-outlined:hover, .button.is-success.is-outlined:focus { +.button.is-success.is-outlined:hover, +.button.is-success.is-outlined:focus { background-color: #23d160; border-color: #23d160; color: #fff; @@ -2277,7 +2531,8 @@ a.box:active { border-color: #fff; color: #fff; } -.button.is-success.is-inverted.is-outlined:hover, .button.is-success.is-inverted.is-outlined:focus { +.button.is-success.is-inverted.is-outlined:hover, +.button.is-success.is-inverted.is-outlined:focus { background-color: #fff; color: #23d160; } @@ -2292,19 +2547,23 @@ a.box:active { border-color: transparent; color: rgba(0, 0, 0, 0.7); } -.button.is-warning:hover, .button.is-warning.is-hovered { +.button.is-warning:hover, +.button.is-warning.is-hovered { background-color: #ffdb4a; border-color: transparent; color: rgba(0, 0, 0, 0.7); } -.button.is-warning:focus, .button.is-warning.is-focused { +.button.is-warning:focus, +.button.is-warning.is-focused { border-color: transparent; color: rgba(0, 0, 0, 0.7); } -.button.is-warning:focus:not(:active), .button.is-warning.is-focused:not(:active) { +.button.is-warning:focus:not(:active), +.button.is-warning.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); } -.button.is-warning:active, .button.is-warning.is-active { +.button.is-warning:active, +.button.is-warning.is-active { background-color: #ffd83d; border-color: transparent; color: rgba(0, 0, 0, 0.7); @@ -2335,7 +2594,8 @@ a.box:active { border-color: #ffdd57; color: #ffdd57; } -.button.is-warning.is-outlined:hover, .button.is-warning.is-outlined:focus { +.button.is-warning.is-outlined:hover, +.button.is-warning.is-outlined:focus { background-color: #ffdd57; border-color: #ffdd57; color: rgba(0, 0, 0, 0.7); @@ -2354,7 +2614,8 @@ a.box:active { border-color: rgba(0, 0, 0, 0.7); color: rgba(0, 0, 0, 0.7); } -.button.is-warning.is-inverted.is-outlined:hover, .button.is-warning.is-inverted.is-outlined:focus { +.button.is-warning.is-inverted.is-outlined:hover, +.button.is-warning.is-inverted.is-outlined:focus { background-color: rgba(0, 0, 0, 0.7); color: #ffdd57; } @@ -2369,19 +2630,23 @@ a.box:active { border-color: transparent; color: #fff; } -.button.is-danger:hover, .button.is-danger.is-hovered { +.button.is-danger:hover, +.button.is-danger.is-hovered { background-color: #ff2b56; border-color: transparent; color: #fff; } -.button.is-danger:focus, .button.is-danger.is-focused { +.button.is-danger:focus, +.button.is-danger.is-focused { border-color: transparent; color: #fff; } -.button.is-danger:focus:not(:active), .button.is-danger.is-focused:not(:active) { +.button.is-danger:focus:not(:active), +.button.is-danger.is-focused:not(:active) { box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); } -.button.is-danger:active, .button.is-danger.is-active { +.button.is-danger:active, +.button.is-danger.is-active { background-color: #ff1f4b; border-color: transparent; color: #fff; @@ -2412,7 +2677,8 @@ a.box:active { border-color: #ff3860; color: #ff3860; } -.button.is-danger.is-outlined:hover, .button.is-danger.is-outlined:focus { +.button.is-danger.is-outlined:hover, +.button.is-danger.is-outlined:focus { background-color: #ff3860; border-color: #ff3860; color: #fff; @@ -2431,7 +2697,8 @@ a.box:active { border-color: #fff; color: #fff; } -.button.is-danger.is-inverted.is-outlined:hover, .button.is-danger.is-inverted.is-outlined:focus { +.button.is-danger.is-inverted.is-outlined:hover, +.button.is-danger.is-inverted.is-outlined:focus { background-color: #fff; color: #ff3860; } @@ -2514,13 +2781,22 @@ a.box:active { .buttons.has-addons .button:last-child { margin-right: 0; } -.buttons.has-addons .button:hover, .buttons.has-addons .button.is-hovered { +.buttons.has-addons .button:hover, +.buttons.has-addons .button.is-hovered { z-index: 2; } -.buttons.has-addons .button:focus, .buttons.has-addons .button.is-focused, .buttons.has-addons .button:active, .buttons.has-addons .button.is-active, .buttons.has-addons .button.is-selected { +.buttons.has-addons .button:focus, +.buttons.has-addons .button.is-focused, +.buttons.has-addons .button:active, +.buttons.has-addons .button.is-active, +.buttons.has-addons .button.is-selected { z-index: 3; } -.buttons.has-addons .button:focus:hover, .buttons.has-addons .button.is-focused:hover, .buttons.has-addons .button:active:hover, .buttons.has-addons .button.is-active:hover, .buttons.has-addons .button.is-selected:hover { +.buttons.has-addons .button:focus:hover, +.buttons.has-addons .button.is-focused:hover, +.buttons.has-addons .button:active:hover, +.buttons.has-addons .button.is-active:hover, +.buttons.has-addons .button.is-selected:hover { z-index: 4; } .buttons.has-addons .button.is-expanded { @@ -2745,12 +3021,16 @@ a.box:active { .textarea:-ms-input-placeholder { color: rgba(54, 54, 54, 0.3); } -.input:hover, .input.is-hovered, +.input:hover, +.input.is-hovered, .textarea:hover, .textarea.is-hovered { border-color: #b5b5b5; } -.input:focus, .input.is-focused, .input:active, .input.is-active, +.input:focus, +.input.is-focused, +.input:active, +.input.is-active, .textarea:focus, .textarea.is-focused, .textarea:active, @@ -2789,7 +3069,10 @@ a.box:active { .textarea.is-white { border-color: white; } -.input.is-white:focus, .input.is-white.is-focused, .input.is-white:active, .input.is-white.is-active, +.input.is-white:focus, +.input.is-white.is-focused, +.input.is-white:active, +.input.is-white.is-active, .textarea.is-white:focus, .textarea.is-white.is-focused, .textarea.is-white:active, @@ -2800,7 +3083,10 @@ a.box:active { .textarea.is-black { border-color: #0a0a0a; } -.input.is-black:focus, .input.is-black.is-focused, .input.is-black:active, .input.is-black.is-active, +.input.is-black:focus, +.input.is-black.is-focused, +.input.is-black:active, +.input.is-black.is-active, .textarea.is-black:focus, .textarea.is-black.is-focused, .textarea.is-black:active, @@ -2811,7 +3097,10 @@ a.box:active { .textarea.is-light { border-color: whitesmoke; } -.input.is-light:focus, .input.is-light.is-focused, .input.is-light:active, .input.is-light.is-active, +.input.is-light:focus, +.input.is-light.is-focused, +.input.is-light:active, +.input.is-light.is-active, .textarea.is-light:focus, .textarea.is-light.is-focused, .textarea.is-light:active, @@ -2822,7 +3111,10 @@ a.box:active { .textarea.is-dark { border-color: #363636; } -.input.is-dark:focus, .input.is-dark.is-focused, .input.is-dark:active, .input.is-dark.is-active, +.input.is-dark:focus, +.input.is-dark.is-focused, +.input.is-dark:active, +.input.is-dark.is-active, .textarea.is-dark:focus, .textarea.is-dark.is-focused, .textarea.is-dark:active, @@ -2833,7 +3125,10 @@ a.box:active { .textarea.is-primary { border-color: #00d1b2; } -.input.is-primary:focus, .input.is-primary.is-focused, .input.is-primary:active, .input.is-primary.is-active, +.input.is-primary:focus, +.input.is-primary.is-focused, +.input.is-primary:active, +.input.is-primary.is-active, .textarea.is-primary:focus, .textarea.is-primary.is-focused, .textarea.is-primary:active, @@ -2844,7 +3139,10 @@ a.box:active { .textarea.is-link { border-color: #3273dc; } -.input.is-link:focus, .input.is-link.is-focused, .input.is-link:active, .input.is-link.is-active, +.input.is-link:focus, +.input.is-link.is-focused, +.input.is-link:active, +.input.is-link.is-active, .textarea.is-link:focus, .textarea.is-link.is-focused, .textarea.is-link:active, @@ -2855,7 +3153,10 @@ a.box:active { .textarea.is-info { border-color: #209cee; } -.input.is-info:focus, .input.is-info.is-focused, .input.is-info:active, .input.is-info.is-active, +.input.is-info:focus, +.input.is-info.is-focused, +.input.is-info:active, +.input.is-info.is-active, .textarea.is-info:focus, .textarea.is-info.is-focused, .textarea.is-info:active, @@ -2866,7 +3167,10 @@ a.box:active { .textarea.is-success { border-color: #23d160; } -.input.is-success:focus, .input.is-success.is-focused, .input.is-success:active, .input.is-success.is-active, +.input.is-success:focus, +.input.is-success.is-focused, +.input.is-success:active, +.input.is-success.is-active, .textarea.is-success:focus, .textarea.is-success.is-focused, .textarea.is-success:active, @@ -2877,7 +3181,10 @@ a.box:active { .textarea.is-warning { border-color: #ffdd57; } -.input.is-warning:focus, .input.is-warning.is-focused, .input.is-warning:active, .input.is-warning.is-active, +.input.is-warning:focus, +.input.is-warning.is-focused, +.input.is-warning:active, +.input.is-warning.is-active, .textarea.is-warning:focus, .textarea.is-warning.is-focused, .textarea.is-warning:active, @@ -2888,7 +3195,10 @@ a.box:active { .textarea.is-danger { border-color: #ff3860; } -.input.is-danger:focus, .input.is-danger.is-focused, .input.is-danger:active, .input.is-danger.is-active, +.input.is-danger:focus, +.input.is-danger.is-focused, +.input.is-danger:active, +.input.is-danger.is-active, .textarea.is-danger:focus, .textarea.is-danger.is-focused, .textarea.is-danger:active, @@ -3015,10 +3325,14 @@ a.box:active { .select select:-ms-input-placeholder { color: rgba(54, 54, 54, 0.3); } -.select select:hover, .select select.is-hovered { +.select select:hover, +.select select.is-hovered { border-color: #b5b5b5; } -.select select:focus, .select select.is-focused, .select select:active, .select select.is-active { +.select select:focus, +.select select.is-focused, +.select select:active, +.select select.is-active { border-color: #3273dc; box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } @@ -3065,10 +3379,14 @@ a.box:active { .select.is-white select { border-color: white; } -.select.is-white select:hover, .select.is-white select.is-hovered { +.select.is-white select:hover, +.select.is-white select.is-hovered { border-color: #f2f2f2; } -.select.is-white select:focus, .select.is-white select.is-focused, .select.is-white select:active, .select.is-white select.is-active { +.select.is-white select:focus, +.select.is-white select.is-focused, +.select.is-white select:active, +.select.is-white select.is-active { box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); } .select.is-black:not(:hover)::after { @@ -3077,10 +3395,14 @@ a.box:active { .select.is-black select { border-color: #0a0a0a; } -.select.is-black select:hover, .select.is-black select.is-hovered { +.select.is-black select:hover, +.select.is-black select.is-hovered { border-color: black; } -.select.is-black select:focus, .select.is-black select.is-focused, .select.is-black select:active, .select.is-black select.is-active { +.select.is-black select:focus, +.select.is-black select.is-focused, +.select.is-black select:active, +.select.is-black select.is-active { box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); } .select.is-light:not(:hover)::after { @@ -3089,10 +3411,14 @@ a.box:active { .select.is-light select { border-color: whitesmoke; } -.select.is-light select:hover, .select.is-light select.is-hovered { +.select.is-light select:hover, +.select.is-light select.is-hovered { border-color: #e8e8e8; } -.select.is-light select:focus, .select.is-light select.is-focused, .select.is-light select:active, .select.is-light select.is-active { +.select.is-light select:focus, +.select.is-light select.is-focused, +.select.is-light select:active, +.select.is-light select.is-active { box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); } .select.is-dark:not(:hover)::after { @@ -3101,10 +3427,14 @@ a.box:active { .select.is-dark select { border-color: #363636; } -.select.is-dark select:hover, .select.is-dark select.is-hovered { +.select.is-dark select:hover, +.select.is-dark select.is-hovered { border-color: #292929; } -.select.is-dark select:focus, .select.is-dark select.is-focused, .select.is-dark select:active, .select.is-dark select.is-active { +.select.is-dark select:focus, +.select.is-dark select.is-focused, +.select.is-dark select:active, +.select.is-dark select.is-active { box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); } .select.is-primary:not(:hover)::after { @@ -3113,10 +3443,14 @@ a.box:active { .select.is-primary select { border-color: #00d1b2; } -.select.is-primary select:hover, .select.is-primary select.is-hovered { +.select.is-primary select:hover, +.select.is-primary select.is-hovered { border-color: #00b89c; } -.select.is-primary select:focus, .select.is-primary select.is-focused, .select.is-primary select:active, .select.is-primary select.is-active { +.select.is-primary select:focus, +.select.is-primary select.is-focused, +.select.is-primary select:active, +.select.is-primary select.is-active { box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); } .select.is-link:not(:hover)::after { @@ -3125,10 +3459,14 @@ a.box:active { .select.is-link select { border-color: #3273dc; } -.select.is-link select:hover, .select.is-link select.is-hovered { +.select.is-link select:hover, +.select.is-link select.is-hovered { border-color: #2366d1; } -.select.is-link select:focus, .select.is-link select.is-focused, .select.is-link select:active, .select.is-link select.is-active { +.select.is-link select:focus, +.select.is-link select.is-focused, +.select.is-link select:active, +.select.is-link select.is-active { box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .select.is-info:not(:hover)::after { @@ -3137,10 +3475,14 @@ a.box:active { .select.is-info select { border-color: #209cee; } -.select.is-info select:hover, .select.is-info select.is-hovered { +.select.is-info select:hover, +.select.is-info select.is-hovered { border-color: #118fe4; } -.select.is-info select:focus, .select.is-info select.is-focused, .select.is-info select:active, .select.is-info select.is-active { +.select.is-info select:focus, +.select.is-info select.is-focused, +.select.is-info select:active, +.select.is-info select.is-active { box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); } .select.is-success:not(:hover)::after { @@ -3149,10 +3491,14 @@ a.box:active { .select.is-success select { border-color: #23d160; } -.select.is-success select:hover, .select.is-success select.is-hovered { +.select.is-success select:hover, +.select.is-success select.is-hovered { border-color: #20bc56; } -.select.is-success select:focus, .select.is-success select.is-focused, .select.is-success select:active, .select.is-success select.is-active { +.select.is-success select:focus, +.select.is-success select.is-focused, +.select.is-success select:active, +.select.is-success select.is-active { box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); } .select.is-warning:not(:hover)::after { @@ -3161,10 +3507,14 @@ a.box:active { .select.is-warning select { border-color: #ffdd57; } -.select.is-warning select:hover, .select.is-warning select.is-hovered { +.select.is-warning select:hover, +.select.is-warning select.is-hovered { border-color: #ffd83d; } -.select.is-warning select:focus, .select.is-warning select.is-focused, .select.is-warning select:active, .select.is-warning select.is-active { +.select.is-warning select:focus, +.select.is-warning select.is-focused, +.select.is-warning select:active, +.select.is-warning select.is-active { box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); } .select.is-danger:not(:hover)::after { @@ -3173,10 +3523,14 @@ a.box:active { .select.is-danger select { border-color: #ff3860; } -.select.is-danger select:hover, .select.is-danger select.is-hovered { +.select.is-danger select:hover, +.select.is-danger select.is-hovered { border-color: #ff1f4b; } -.select.is-danger select:focus, .select.is-danger select.is-focused, .select.is-danger select:active, .select.is-danger select.is-active { +.select.is-danger select:focus, +.select.is-danger select.is-focused, +.select.is-danger select:active, +.select.is-danger select.is-active { box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); } .select.is-small { @@ -3226,17 +3580,20 @@ a.box:active { border-color: transparent; color: #0a0a0a; } -.file.is-white:hover .file-cta, .file.is-white.is-hovered .file-cta { +.file.is-white:hover .file-cta, +.file.is-white.is-hovered .file-cta { background-color: #f9f9f9; border-color: transparent; color: #0a0a0a; } -.file.is-white:focus .file-cta, .file.is-white.is-focused .file-cta { +.file.is-white:focus .file-cta, +.file.is-white.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.25); color: #0a0a0a; } -.file.is-white:active .file-cta, .file.is-white.is-active .file-cta { +.file.is-white:active .file-cta, +.file.is-white.is-active .file-cta { background-color: #f2f2f2; border-color: transparent; color: #0a0a0a; @@ -3246,17 +3603,20 @@ a.box:active { border-color: transparent; color: white; } -.file.is-black:hover .file-cta, .file.is-black.is-hovered .file-cta { +.file.is-black:hover .file-cta, +.file.is-black.is-hovered .file-cta { background-color: #040404; border-color: transparent; color: white; } -.file.is-black:focus .file-cta, .file.is-black.is-focused .file-cta { +.file.is-black:focus .file-cta, +.file.is-black.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.25); color: white; } -.file.is-black:active .file-cta, .file.is-black.is-active .file-cta { +.file.is-black:active .file-cta, +.file.is-black.is-active .file-cta { background-color: black; border-color: transparent; color: white; @@ -3266,17 +3626,20 @@ a.box:active { border-color: transparent; color: #363636; } -.file.is-light:hover .file-cta, .file.is-light.is-hovered .file-cta { +.file.is-light:hover .file-cta, +.file.is-light.is-hovered .file-cta { background-color: #eeeeee; border-color: transparent; color: #363636; } -.file.is-light:focus .file-cta, .file.is-light.is-focused .file-cta { +.file.is-light:focus .file-cta, +.file.is-light.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.25); color: #363636; } -.file.is-light:active .file-cta, .file.is-light.is-active .file-cta { +.file.is-light:active .file-cta, +.file.is-light.is-active .file-cta { background-color: #e8e8e8; border-color: transparent; color: #363636; @@ -3286,17 +3649,20 @@ a.box:active { border-color: transparent; color: whitesmoke; } -.file.is-dark:hover .file-cta, .file.is-dark.is-hovered .file-cta { +.file.is-dark:hover .file-cta, +.file.is-dark.is-hovered .file-cta { background-color: #2f2f2f; border-color: transparent; color: whitesmoke; } -.file.is-dark:focus .file-cta, .file.is-dark.is-focused .file-cta { +.file.is-dark:focus .file-cta, +.file.is-dark.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.25); color: whitesmoke; } -.file.is-dark:active .file-cta, .file.is-dark.is-active .file-cta { +.file.is-dark:active .file-cta, +.file.is-dark.is-active .file-cta { background-color: #292929; border-color: transparent; color: whitesmoke; @@ -3306,17 +3672,20 @@ a.box:active { border-color: transparent; color: #fff; } -.file.is-primary:hover .file-cta, .file.is-primary.is-hovered .file-cta { +.file.is-primary:hover .file-cta, +.file.is-primary.is-hovered .file-cta { background-color: #00c4a7; border-color: transparent; color: #fff; } -.file.is-primary:focus .file-cta, .file.is-primary.is-focused .file-cta { +.file.is-primary:focus .file-cta, +.file.is-primary.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(0, 209, 178, 0.25); color: #fff; } -.file.is-primary:active .file-cta, .file.is-primary.is-active .file-cta { +.file.is-primary:active .file-cta, +.file.is-primary.is-active .file-cta { background-color: #00b89c; border-color: transparent; color: #fff; @@ -3326,17 +3695,20 @@ a.box:active { border-color: transparent; color: #fff; } -.file.is-link:hover .file-cta, .file.is-link.is-hovered .file-cta { +.file.is-link:hover .file-cta, +.file.is-link.is-hovered .file-cta { background-color: #276cda; border-color: transparent; color: #fff; } -.file.is-link:focus .file-cta, .file.is-link.is-focused .file-cta { +.file.is-link:focus .file-cta, +.file.is-link.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(50, 115, 220, 0.25); color: #fff; } -.file.is-link:active .file-cta, .file.is-link.is-active .file-cta { +.file.is-link:active .file-cta, +.file.is-link.is-active .file-cta { background-color: #2366d1; border-color: transparent; color: #fff; @@ -3346,17 +3718,20 @@ a.box:active { border-color: transparent; color: #fff; } -.file.is-info:hover .file-cta, .file.is-info.is-hovered .file-cta { +.file.is-info:hover .file-cta, +.file.is-info.is-hovered .file-cta { background-color: #1496ed; border-color: transparent; color: #fff; } -.file.is-info:focus .file-cta, .file.is-info.is-focused .file-cta { +.file.is-info:focus .file-cta, +.file.is-info.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(32, 156, 238, 0.25); color: #fff; } -.file.is-info:active .file-cta, .file.is-info.is-active .file-cta { +.file.is-info:active .file-cta, +.file.is-info.is-active .file-cta { background-color: #118fe4; border-color: transparent; color: #fff; @@ -3366,17 +3741,20 @@ a.box:active { border-color: transparent; color: #fff; } -.file.is-success:hover .file-cta, .file.is-success.is-hovered .file-cta { +.file.is-success:hover .file-cta, +.file.is-success.is-hovered .file-cta { background-color: #22c65b; border-color: transparent; color: #fff; } -.file.is-success:focus .file-cta, .file.is-success.is-focused .file-cta { +.file.is-success:focus .file-cta, +.file.is-success.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.25); color: #fff; } -.file.is-success:active .file-cta, .file.is-success.is-active .file-cta { +.file.is-success:active .file-cta, +.file.is-success.is-active .file-cta { background-color: #20bc56; border-color: transparent; color: #fff; @@ -3386,17 +3764,20 @@ a.box:active { border-color: transparent; color: rgba(0, 0, 0, 0.7); } -.file.is-warning:hover .file-cta, .file.is-warning.is-hovered .file-cta { +.file.is-warning:hover .file-cta, +.file.is-warning.is-hovered .file-cta { background-color: #ffdb4a; border-color: transparent; color: rgba(0, 0, 0, 0.7); } -.file.is-warning:focus .file-cta, .file.is-warning.is-focused .file-cta { +.file.is-warning:focus .file-cta, +.file.is-warning.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.25); color: rgba(0, 0, 0, 0.7); } -.file.is-warning:active .file-cta, .file.is-warning.is-active .file-cta { +.file.is-warning:active .file-cta, +.file.is-warning.is-active .file-cta { background-color: #ffd83d; border-color: transparent; color: rgba(0, 0, 0, 0.7); @@ -3406,17 +3787,20 @@ a.box:active { border-color: transparent; color: #fff; } -.file.is-danger:hover .file-cta, .file.is-danger.is-hovered .file-cta { +.file.is-danger:hover .file-cta, +.file.is-danger.is-hovered .file-cta { background-color: #ff2b56; border-color: transparent; color: #fff; } -.file.is-danger:focus .file-cta, .file.is-danger.is-focused .file-cta { +.file.is-danger:focus .file-cta, +.file.is-danger.is-focused .file-cta { border-color: transparent; box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.25); color: #fff; } -.file.is-danger:active .file-cta, .file.is-danger.is-active .file-cta { +.file.is-danger:active .file-cta, +.file.is-danger.is-active .file-cta { background-color: #ff1f4b; border-color: transparent; color: #fff; @@ -3658,14 +4042,18 @@ a.box:active { border-bottom-left-radius: 0; border-top-left-radius: 0; } -.field.has-addons .control .button:not([disabled]):hover, .field.has-addons .control .button:not([disabled]).is-hovered, +.field.has-addons .control .button:not([disabled]):hover, +.field.has-addons .control .button:not([disabled]).is-hovered, .field.has-addons .control .input:not([disabled]):hover, .field.has-addons .control .input:not([disabled]).is-hovered, .field.has-addons .control .select select:not([disabled]):hover, .field.has-addons .control .select select:not([disabled]).is-hovered { z-index: 2; } -.field.has-addons .control .button:not([disabled]):focus, .field.has-addons .control .button:not([disabled]).is-focused, .field.has-addons .control .button:not([disabled]):active, .field.has-addons .control .button:not([disabled]).is-active, +.field.has-addons .control .button:not([disabled]):focus, +.field.has-addons .control .button:not([disabled]).is-focused, +.field.has-addons .control .button:not([disabled]):active, +.field.has-addons .control .button:not([disabled]).is-active, .field.has-addons .control .input:not([disabled]):focus, .field.has-addons .control .input:not([disabled]).is-focused, .field.has-addons .control .input:not([disabled]):active, @@ -3676,7 +4064,10 @@ a.box:active { .field.has-addons .control .select select:not([disabled]).is-active { z-index: 3; } -.field.has-addons .control .button:not([disabled]):focus:hover, .field.has-addons .control .button:not([disabled]).is-focused:hover, .field.has-addons .control .button:not([disabled]):active:hover, .field.has-addons .control .button:not([disabled]).is-active:hover, +.field.has-addons .control .button:not([disabled]):focus:hover, +.field.has-addons .control .button:not([disabled]).is-focused:hover, +.field.has-addons .control .button:not([disabled]):active:hover, +.field.has-addons .control .button:not([disabled]).is-active:hover, .field.has-addons .control .input:not([disabled]):focus:hover, .field.has-addons .control .input:not([disabled]).is-focused:hover, .field.has-addons .control .input:not([disabled]):active:hover, @@ -3724,7 +4115,8 @@ a.box:active { .field.is-grouped.is-grouped-multiline { flex-wrap: wrap; } -.field.is-grouped.is-grouped-multiline > .control:last-child, .field.is-grouped.is-grouped-multiline > .control:not(:last-child) { +.field.is-grouped.is-grouped-multiline > .control:last-child, +.field.is-grouped.is-grouped-multiline > .control:not(:last-child) { margin-bottom: 0.75rem; } .field.is-grouped.is-grouped-multiline:last-child { @@ -3836,26 +4228,31 @@ a.box:active { padding-right: 2.25em; } .control.has-icons-left .input:focus ~ .icon, -.control.has-icons-left .select:focus ~ .icon, .control.has-icons-right .input:focus ~ .icon, +.control.has-icons-left .select:focus ~ .icon, +.control.has-icons-right .input:focus ~ .icon, .control.has-icons-right .select:focus ~ .icon { color: #7a7a7a; } .control.has-icons-left .input.is-small ~ .icon, -.control.has-icons-left .select.is-small ~ .icon, .control.has-icons-right .input.is-small ~ .icon, +.control.has-icons-left .select.is-small ~ .icon, +.control.has-icons-right .input.is-small ~ .icon, .control.has-icons-right .select.is-small ~ .icon { font-size: 0.75rem; } .control.has-icons-left .input.is-medium ~ .icon, -.control.has-icons-left .select.is-medium ~ .icon, .control.has-icons-right .input.is-medium ~ .icon, +.control.has-icons-left .select.is-medium ~ .icon, +.control.has-icons-right .input.is-medium ~ .icon, .control.has-icons-right .select.is-medium ~ .icon { font-size: 1.25rem; } .control.has-icons-left .input.is-large ~ .icon, -.control.has-icons-left .select.is-large ~ .icon, .control.has-icons-right .input.is-large ~ .icon, +.control.has-icons-left .select.is-large ~ .icon, +.control.has-icons-right .input.is-large ~ .icon, .control.has-icons-right .select.is-large ~ .icon { font-size: 1.5rem; } -.control.has-icons-left .icon, .control.has-icons-right .icon { +.control.has-icons-left .icon, +.control.has-icons-right .icon { color: #dbdbdb; height: 2.25em; pointer-events: none; @@ -3926,11 +4323,27 @@ a.box:active { .image img.is-rounded { border-radius: 290486px; } -.image.is-square img, .image.is-1by1 img, .image.is-5by4 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-5by3 img, .image.is-16by9 img, .image.is-2by1 img, .image.is-3by1 img, .image.is-4by5 img, .image.is-3by4 img, .image.is-2by3 img, .image.is-3by5 img, .image.is-9by16 img, .image.is-1by2 img, .image.is-1by3 img { +.image.is-square img, +.image.is-1by1 img, +.image.is-5by4 img, +.image.is-4by3 img, +.image.is-3by2 img, +.image.is-5by3 img, +.image.is-16by9 img, +.image.is-2by1 img, +.image.is-3by1 img, +.image.is-4by5 img, +.image.is-3by4 img, +.image.is-2by3 img, +.image.is-3by5 img, +.image.is-9by16 img, +.image.is-1by2 img, +.image.is-1by3 img { height: 100%; width: 100%; } -.image.is-square, .image.is-1by1 { +.image.is-square, +.image.is-1by1 { padding-top: 100%; } .image.is-5by4 { @@ -4477,7 +4890,8 @@ a.box:active { position: relative; width: 2em; } -.tag:not(body).is-delete::before, .tag:not(body).is-delete::after { +.tag:not(body).is-delete::before, +.tag:not(body).is-delete::after { background-color: currentColor; content: ""; display: block; @@ -4495,7 +4909,8 @@ a.box:active { height: 50%; width: 1px; } -.tag:not(body).is-delete:hover, .tag:not(body).is-delete:focus { +.tag:not(body).is-delete:hover, +.tag:not(body).is-delete:focus { background-color: #e8e8e8; } .tag:not(body).is-delete:active { @@ -4714,7 +5129,9 @@ a.tag:hover { .card { background-color: white; - box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); + box-shadow: + 0 2px 3px rgba(10, 10, 10, 0.1), + 0 0 0 1px rgba(10, 10, 10, 0.1); color: #4a4a4a; max-width: 100%; position: relative; @@ -4786,7 +5203,8 @@ a.tag:hover { position: relative; vertical-align: top; } -.dropdown.is-active .dropdown-menu, .dropdown.is-hoverable:hover .dropdown-menu { +.dropdown.is-active .dropdown-menu, +.dropdown.is-hoverable:hover .dropdown-menu { display: block; } .dropdown.is-right .dropdown-menu { @@ -4813,7 +5231,9 @@ a.tag:hover { .dropdown-content { background-color: white; border-radius: 4px; - box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); + box-shadow: + 0 2px 3px rgba(10, 10, 10, 0.1), + 0 0 0 1px rgba(10, 10, 10, 0.1); padding-bottom: 0.5rem; padding-top: 0.5rem; } @@ -4917,7 +5337,7 @@ a.dropdown-item.is-active { } @media screen and (min-width: 769px), print { .level-left .level-item:not(:last-child), -.level-right .level-item:not(:last-child) { + .level-right .level-item:not(:last-child) { margin-right: 0.75rem; } } @@ -5254,7 +5674,7 @@ a.dropdown-item.is-active { } @media screen and (min-width: 769px), print { .modal-content, -.modal-card { + .modal-card { margin: 0 auto; max-height: calc(100vh - 40px); width: 640px; @@ -5335,7 +5755,8 @@ a.dropdown-item.is-active { .navbar.is-white .navbar-brand .navbar-link { color: #0a0a0a; } -.navbar.is-white .navbar-brand > a.navbar-item:hover, .navbar.is-white .navbar-brand > a.navbar-item.is-active, +.navbar.is-white .navbar-brand > a.navbar-item:hover, +.navbar.is-white .navbar-brand > a.navbar-item.is-active, .navbar.is-white .navbar-brand .navbar-link:hover, .navbar.is-white .navbar-brand .navbar-link.is-active { background-color: #f2f2f2; @@ -5346,27 +5767,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-white .navbar-start > .navbar-item, -.navbar.is-white .navbar-start .navbar-link, -.navbar.is-white .navbar-end > .navbar-item, -.navbar.is-white .navbar-end .navbar-link { + .navbar.is-white .navbar-start .navbar-link, + .navbar.is-white .navbar-end > .navbar-item, + .navbar.is-white .navbar-end .navbar-link { color: #0a0a0a; } - .navbar.is-white .navbar-start > a.navbar-item:hover, .navbar.is-white .navbar-start > a.navbar-item.is-active, -.navbar.is-white .navbar-start .navbar-link:hover, -.navbar.is-white .navbar-start .navbar-link.is-active, -.navbar.is-white .navbar-end > a.navbar-item:hover, -.navbar.is-white .navbar-end > a.navbar-item.is-active, -.navbar.is-white .navbar-end .navbar-link:hover, -.navbar.is-white .navbar-end .navbar-link.is-active { + .navbar.is-white .navbar-start > a.navbar-item:hover, + .navbar.is-white .navbar-start > a.navbar-item.is-active, + .navbar.is-white .navbar-start .navbar-link:hover, + .navbar.is-white .navbar-start .navbar-link.is-active, + .navbar.is-white .navbar-end > a.navbar-item:hover, + .navbar.is-white .navbar-end > a.navbar-item.is-active, + .navbar.is-white .navbar-end .navbar-link:hover, + .navbar.is-white .navbar-end .navbar-link.is-active { background-color: #f2f2f2; color: #0a0a0a; } .navbar.is-white .navbar-start .navbar-link::after, -.navbar.is-white .navbar-end .navbar-link::after { + .navbar.is-white .navbar-end .navbar-link::after { border-color: #0a0a0a; } .navbar.is-white .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-white .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-white .navbar-item.has-dropdown.is-active .navbar-link { background-color: #f2f2f2; color: #0a0a0a; } @@ -5383,7 +5805,8 @@ a.dropdown-item.is-active { .navbar.is-black .navbar-brand .navbar-link { color: white; } -.navbar.is-black .navbar-brand > a.navbar-item:hover, .navbar.is-black .navbar-brand > a.navbar-item.is-active, +.navbar.is-black .navbar-brand > a.navbar-item:hover, +.navbar.is-black .navbar-brand > a.navbar-item.is-active, .navbar.is-black .navbar-brand .navbar-link:hover, .navbar.is-black .navbar-brand .navbar-link.is-active { background-color: black; @@ -5394,27 +5817,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-black .navbar-start > .navbar-item, -.navbar.is-black .navbar-start .navbar-link, -.navbar.is-black .navbar-end > .navbar-item, -.navbar.is-black .navbar-end .navbar-link { + .navbar.is-black .navbar-start .navbar-link, + .navbar.is-black .navbar-end > .navbar-item, + .navbar.is-black .navbar-end .navbar-link { color: white; } - .navbar.is-black .navbar-start > a.navbar-item:hover, .navbar.is-black .navbar-start > a.navbar-item.is-active, -.navbar.is-black .navbar-start .navbar-link:hover, -.navbar.is-black .navbar-start .navbar-link.is-active, -.navbar.is-black .navbar-end > a.navbar-item:hover, -.navbar.is-black .navbar-end > a.navbar-item.is-active, -.navbar.is-black .navbar-end .navbar-link:hover, -.navbar.is-black .navbar-end .navbar-link.is-active { + .navbar.is-black .navbar-start > a.navbar-item:hover, + .navbar.is-black .navbar-start > a.navbar-item.is-active, + .navbar.is-black .navbar-start .navbar-link:hover, + .navbar.is-black .navbar-start .navbar-link.is-active, + .navbar.is-black .navbar-end > a.navbar-item:hover, + .navbar.is-black .navbar-end > a.navbar-item.is-active, + .navbar.is-black .navbar-end .navbar-link:hover, + .navbar.is-black .navbar-end .navbar-link.is-active { background-color: black; color: white; } .navbar.is-black .navbar-start .navbar-link::after, -.navbar.is-black .navbar-end .navbar-link::after { + .navbar.is-black .navbar-end .navbar-link::after { border-color: white; } .navbar.is-black .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-black .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-black .navbar-item.has-dropdown.is-active .navbar-link { background-color: black; color: white; } @@ -5431,7 +5855,8 @@ a.dropdown-item.is-active { .navbar.is-light .navbar-brand .navbar-link { color: #363636; } -.navbar.is-light .navbar-brand > a.navbar-item:hover, .navbar.is-light .navbar-brand > a.navbar-item.is-active, +.navbar.is-light .navbar-brand > a.navbar-item:hover, +.navbar.is-light .navbar-brand > a.navbar-item.is-active, .navbar.is-light .navbar-brand .navbar-link:hover, .navbar.is-light .navbar-brand .navbar-link.is-active { background-color: #e8e8e8; @@ -5442,27 +5867,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-light .navbar-start > .navbar-item, -.navbar.is-light .navbar-start .navbar-link, -.navbar.is-light .navbar-end > .navbar-item, -.navbar.is-light .navbar-end .navbar-link { + .navbar.is-light .navbar-start .navbar-link, + .navbar.is-light .navbar-end > .navbar-item, + .navbar.is-light .navbar-end .navbar-link { color: #363636; } - .navbar.is-light .navbar-start > a.navbar-item:hover, .navbar.is-light .navbar-start > a.navbar-item.is-active, -.navbar.is-light .navbar-start .navbar-link:hover, -.navbar.is-light .navbar-start .navbar-link.is-active, -.navbar.is-light .navbar-end > a.navbar-item:hover, -.navbar.is-light .navbar-end > a.navbar-item.is-active, -.navbar.is-light .navbar-end .navbar-link:hover, -.navbar.is-light .navbar-end .navbar-link.is-active { + .navbar.is-light .navbar-start > a.navbar-item:hover, + .navbar.is-light .navbar-start > a.navbar-item.is-active, + .navbar.is-light .navbar-start .navbar-link:hover, + .navbar.is-light .navbar-start .navbar-link.is-active, + .navbar.is-light .navbar-end > a.navbar-item:hover, + .navbar.is-light .navbar-end > a.navbar-item.is-active, + .navbar.is-light .navbar-end .navbar-link:hover, + .navbar.is-light .navbar-end .navbar-link.is-active { background-color: #e8e8e8; color: #363636; } .navbar.is-light .navbar-start .navbar-link::after, -.navbar.is-light .navbar-end .navbar-link::after { + .navbar.is-light .navbar-end .navbar-link::after { border-color: #363636; } .navbar.is-light .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-light .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-light .navbar-item.has-dropdown.is-active .navbar-link { background-color: #e8e8e8; color: #363636; } @@ -5479,7 +5905,8 @@ a.dropdown-item.is-active { .navbar.is-dark .navbar-brand .navbar-link { color: whitesmoke; } -.navbar.is-dark .navbar-brand > a.navbar-item:hover, .navbar.is-dark .navbar-brand > a.navbar-item.is-active, +.navbar.is-dark .navbar-brand > a.navbar-item:hover, +.navbar.is-dark .navbar-brand > a.navbar-item.is-active, .navbar.is-dark .navbar-brand .navbar-link:hover, .navbar.is-dark .navbar-brand .navbar-link.is-active { background-color: #292929; @@ -5490,27 +5917,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-dark .navbar-start > .navbar-item, -.navbar.is-dark .navbar-start .navbar-link, -.navbar.is-dark .navbar-end > .navbar-item, -.navbar.is-dark .navbar-end .navbar-link { + .navbar.is-dark .navbar-start .navbar-link, + .navbar.is-dark .navbar-end > .navbar-item, + .navbar.is-dark .navbar-end .navbar-link { color: whitesmoke; } - .navbar.is-dark .navbar-start > a.navbar-item:hover, .navbar.is-dark .navbar-start > a.navbar-item.is-active, -.navbar.is-dark .navbar-start .navbar-link:hover, -.navbar.is-dark .navbar-start .navbar-link.is-active, -.navbar.is-dark .navbar-end > a.navbar-item:hover, -.navbar.is-dark .navbar-end > a.navbar-item.is-active, -.navbar.is-dark .navbar-end .navbar-link:hover, -.navbar.is-dark .navbar-end .navbar-link.is-active { + .navbar.is-dark .navbar-start > a.navbar-item:hover, + .navbar.is-dark .navbar-start > a.navbar-item.is-active, + .navbar.is-dark .navbar-start .navbar-link:hover, + .navbar.is-dark .navbar-start .navbar-link.is-active, + .navbar.is-dark .navbar-end > a.navbar-item:hover, + .navbar.is-dark .navbar-end > a.navbar-item.is-active, + .navbar.is-dark .navbar-end .navbar-link:hover, + .navbar.is-dark .navbar-end .navbar-link.is-active { background-color: #292929; color: whitesmoke; } .navbar.is-dark .navbar-start .navbar-link::after, -.navbar.is-dark .navbar-end .navbar-link::after { + .navbar.is-dark .navbar-end .navbar-link::after { border-color: whitesmoke; } .navbar.is-dark .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-dark .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-dark .navbar-item.has-dropdown.is-active .navbar-link { background-color: #292929; color: whitesmoke; } @@ -5527,7 +5955,8 @@ a.dropdown-item.is-active { .navbar.is-primary .navbar-brand .navbar-link { color: #fff; } -.navbar.is-primary .navbar-brand > a.navbar-item:hover, .navbar.is-primary .navbar-brand > a.navbar-item.is-active, +.navbar.is-primary .navbar-brand > a.navbar-item:hover, +.navbar.is-primary .navbar-brand > a.navbar-item.is-active, .navbar.is-primary .navbar-brand .navbar-link:hover, .navbar.is-primary .navbar-brand .navbar-link.is-active { background-color: #00b89c; @@ -5538,27 +5967,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-primary .navbar-start > .navbar-item, -.navbar.is-primary .navbar-start .navbar-link, -.navbar.is-primary .navbar-end > .navbar-item, -.navbar.is-primary .navbar-end .navbar-link { + .navbar.is-primary .navbar-start .navbar-link, + .navbar.is-primary .navbar-end > .navbar-item, + .navbar.is-primary .navbar-end .navbar-link { color: #fff; } - .navbar.is-primary .navbar-start > a.navbar-item:hover, .navbar.is-primary .navbar-start > a.navbar-item.is-active, -.navbar.is-primary .navbar-start .navbar-link:hover, -.navbar.is-primary .navbar-start .navbar-link.is-active, -.navbar.is-primary .navbar-end > a.navbar-item:hover, -.navbar.is-primary .navbar-end > a.navbar-item.is-active, -.navbar.is-primary .navbar-end .navbar-link:hover, -.navbar.is-primary .navbar-end .navbar-link.is-active { + .navbar.is-primary .navbar-start > a.navbar-item:hover, + .navbar.is-primary .navbar-start > a.navbar-item.is-active, + .navbar.is-primary .navbar-start .navbar-link:hover, + .navbar.is-primary .navbar-start .navbar-link.is-active, + .navbar.is-primary .navbar-end > a.navbar-item:hover, + .navbar.is-primary .navbar-end > a.navbar-item.is-active, + .navbar.is-primary .navbar-end .navbar-link:hover, + .navbar.is-primary .navbar-end .navbar-link.is-active { background-color: #00b89c; color: #fff; } .navbar.is-primary .navbar-start .navbar-link::after, -.navbar.is-primary .navbar-end .navbar-link::after { + .navbar.is-primary .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-primary .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-primary .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-primary .navbar-item.has-dropdown.is-active .navbar-link { background-color: #00b89c; color: #fff; } @@ -5575,7 +6005,8 @@ a.dropdown-item.is-active { .navbar.is-link .navbar-brand .navbar-link { color: #fff; } -.navbar.is-link .navbar-brand > a.navbar-item:hover, .navbar.is-link .navbar-brand > a.navbar-item.is-active, +.navbar.is-link .navbar-brand > a.navbar-item:hover, +.navbar.is-link .navbar-brand > a.navbar-item.is-active, .navbar.is-link .navbar-brand .navbar-link:hover, .navbar.is-link .navbar-brand .navbar-link.is-active { background-color: #2366d1; @@ -5586,27 +6017,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-link .navbar-start > .navbar-item, -.navbar.is-link .navbar-start .navbar-link, -.navbar.is-link .navbar-end > .navbar-item, -.navbar.is-link .navbar-end .navbar-link { + .navbar.is-link .navbar-start .navbar-link, + .navbar.is-link .navbar-end > .navbar-item, + .navbar.is-link .navbar-end .navbar-link { color: #fff; } - .navbar.is-link .navbar-start > a.navbar-item:hover, .navbar.is-link .navbar-start > a.navbar-item.is-active, -.navbar.is-link .navbar-start .navbar-link:hover, -.navbar.is-link .navbar-start .navbar-link.is-active, -.navbar.is-link .navbar-end > a.navbar-item:hover, -.navbar.is-link .navbar-end > a.navbar-item.is-active, -.navbar.is-link .navbar-end .navbar-link:hover, -.navbar.is-link .navbar-end .navbar-link.is-active { + .navbar.is-link .navbar-start > a.navbar-item:hover, + .navbar.is-link .navbar-start > a.navbar-item.is-active, + .navbar.is-link .navbar-start .navbar-link:hover, + .navbar.is-link .navbar-start .navbar-link.is-active, + .navbar.is-link .navbar-end > a.navbar-item:hover, + .navbar.is-link .navbar-end > a.navbar-item.is-active, + .navbar.is-link .navbar-end .navbar-link:hover, + .navbar.is-link .navbar-end .navbar-link.is-active { background-color: #2366d1; color: #fff; } .navbar.is-link .navbar-start .navbar-link::after, -.navbar.is-link .navbar-end .navbar-link::after { + .navbar.is-link .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-link .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-link .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-link .navbar-item.has-dropdown.is-active .navbar-link { background-color: #2366d1; color: #fff; } @@ -5623,7 +6055,8 @@ a.dropdown-item.is-active { .navbar.is-info .navbar-brand .navbar-link { color: #fff; } -.navbar.is-info .navbar-brand > a.navbar-item:hover, .navbar.is-info .navbar-brand > a.navbar-item.is-active, +.navbar.is-info .navbar-brand > a.navbar-item:hover, +.navbar.is-info .navbar-brand > a.navbar-item.is-active, .navbar.is-info .navbar-brand .navbar-link:hover, .navbar.is-info .navbar-brand .navbar-link.is-active { background-color: #118fe4; @@ -5634,27 +6067,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-info .navbar-start > .navbar-item, -.navbar.is-info .navbar-start .navbar-link, -.navbar.is-info .navbar-end > .navbar-item, -.navbar.is-info .navbar-end .navbar-link { + .navbar.is-info .navbar-start .navbar-link, + .navbar.is-info .navbar-end > .navbar-item, + .navbar.is-info .navbar-end .navbar-link { color: #fff; } - .navbar.is-info .navbar-start > a.navbar-item:hover, .navbar.is-info .navbar-start > a.navbar-item.is-active, -.navbar.is-info .navbar-start .navbar-link:hover, -.navbar.is-info .navbar-start .navbar-link.is-active, -.navbar.is-info .navbar-end > a.navbar-item:hover, -.navbar.is-info .navbar-end > a.navbar-item.is-active, -.navbar.is-info .navbar-end .navbar-link:hover, -.navbar.is-info .navbar-end .navbar-link.is-active { + .navbar.is-info .navbar-start > a.navbar-item:hover, + .navbar.is-info .navbar-start > a.navbar-item.is-active, + .navbar.is-info .navbar-start .navbar-link:hover, + .navbar.is-info .navbar-start .navbar-link.is-active, + .navbar.is-info .navbar-end > a.navbar-item:hover, + .navbar.is-info .navbar-end > a.navbar-item.is-active, + .navbar.is-info .navbar-end .navbar-link:hover, + .navbar.is-info .navbar-end .navbar-link.is-active { background-color: #118fe4; color: #fff; } .navbar.is-info .navbar-start .navbar-link::after, -.navbar.is-info .navbar-end .navbar-link::after { + .navbar.is-info .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-info .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-info .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-info .navbar-item.has-dropdown.is-active .navbar-link { background-color: #118fe4; color: #fff; } @@ -5671,7 +6105,8 @@ a.dropdown-item.is-active { .navbar.is-success .navbar-brand .navbar-link { color: #fff; } -.navbar.is-success .navbar-brand > a.navbar-item:hover, .navbar.is-success .navbar-brand > a.navbar-item.is-active, +.navbar.is-success .navbar-brand > a.navbar-item:hover, +.navbar.is-success .navbar-brand > a.navbar-item.is-active, .navbar.is-success .navbar-brand .navbar-link:hover, .navbar.is-success .navbar-brand .navbar-link.is-active { background-color: #20bc56; @@ -5682,27 +6117,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-success .navbar-start > .navbar-item, -.navbar.is-success .navbar-start .navbar-link, -.navbar.is-success .navbar-end > .navbar-item, -.navbar.is-success .navbar-end .navbar-link { + .navbar.is-success .navbar-start .navbar-link, + .navbar.is-success .navbar-end > .navbar-item, + .navbar.is-success .navbar-end .navbar-link { color: #fff; } - .navbar.is-success .navbar-start > a.navbar-item:hover, .navbar.is-success .navbar-start > a.navbar-item.is-active, -.navbar.is-success .navbar-start .navbar-link:hover, -.navbar.is-success .navbar-start .navbar-link.is-active, -.navbar.is-success .navbar-end > a.navbar-item:hover, -.navbar.is-success .navbar-end > a.navbar-item.is-active, -.navbar.is-success .navbar-end .navbar-link:hover, -.navbar.is-success .navbar-end .navbar-link.is-active { + .navbar.is-success .navbar-start > a.navbar-item:hover, + .navbar.is-success .navbar-start > a.navbar-item.is-active, + .navbar.is-success .navbar-start .navbar-link:hover, + .navbar.is-success .navbar-start .navbar-link.is-active, + .navbar.is-success .navbar-end > a.navbar-item:hover, + .navbar.is-success .navbar-end > a.navbar-item.is-active, + .navbar.is-success .navbar-end .navbar-link:hover, + .navbar.is-success .navbar-end .navbar-link.is-active { background-color: #20bc56; color: #fff; } .navbar.is-success .navbar-start .navbar-link::after, -.navbar.is-success .navbar-end .navbar-link::after { + .navbar.is-success .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-success .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-success .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-success .navbar-item.has-dropdown.is-active .navbar-link { background-color: #20bc56; color: #fff; } @@ -5719,7 +6155,8 @@ a.dropdown-item.is-active { .navbar.is-warning .navbar-brand .navbar-link { color: rgba(0, 0, 0, 0.7); } -.navbar.is-warning .navbar-brand > a.navbar-item:hover, .navbar.is-warning .navbar-brand > a.navbar-item.is-active, +.navbar.is-warning .navbar-brand > a.navbar-item:hover, +.navbar.is-warning .navbar-brand > a.navbar-item.is-active, .navbar.is-warning .navbar-brand .navbar-link:hover, .navbar.is-warning .navbar-brand .navbar-link.is-active { background-color: #ffd83d; @@ -5730,27 +6167,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-warning .navbar-start > .navbar-item, -.navbar.is-warning .navbar-start .navbar-link, -.navbar.is-warning .navbar-end > .navbar-item, -.navbar.is-warning .navbar-end .navbar-link { + .navbar.is-warning .navbar-start .navbar-link, + .navbar.is-warning .navbar-end > .navbar-item, + .navbar.is-warning .navbar-end .navbar-link { color: rgba(0, 0, 0, 0.7); } - .navbar.is-warning .navbar-start > a.navbar-item:hover, .navbar.is-warning .navbar-start > a.navbar-item.is-active, -.navbar.is-warning .navbar-start .navbar-link:hover, -.navbar.is-warning .navbar-start .navbar-link.is-active, -.navbar.is-warning .navbar-end > a.navbar-item:hover, -.navbar.is-warning .navbar-end > a.navbar-item.is-active, -.navbar.is-warning .navbar-end .navbar-link:hover, -.navbar.is-warning .navbar-end .navbar-link.is-active { + .navbar.is-warning .navbar-start > a.navbar-item:hover, + .navbar.is-warning .navbar-start > a.navbar-item.is-active, + .navbar.is-warning .navbar-start .navbar-link:hover, + .navbar.is-warning .navbar-start .navbar-link.is-active, + .navbar.is-warning .navbar-end > a.navbar-item:hover, + .navbar.is-warning .navbar-end > a.navbar-item.is-active, + .navbar.is-warning .navbar-end .navbar-link:hover, + .navbar.is-warning .navbar-end .navbar-link.is-active { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-start .navbar-link::after, -.navbar.is-warning .navbar-end .navbar-link::after { + .navbar.is-warning .navbar-end .navbar-link::after { border-color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-warning .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-warning .navbar-item.has-dropdown.is-active .navbar-link { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } @@ -5767,7 +6205,8 @@ a.dropdown-item.is-active { .navbar.is-danger .navbar-brand .navbar-link { color: #fff; } -.navbar.is-danger .navbar-brand > a.navbar-item:hover, .navbar.is-danger .navbar-brand > a.navbar-item.is-active, +.navbar.is-danger .navbar-brand > a.navbar-item:hover, +.navbar.is-danger .navbar-brand > a.navbar-item.is-active, .navbar.is-danger .navbar-brand .navbar-link:hover, .navbar.is-danger .navbar-brand .navbar-link.is-active { background-color: #ff1f4b; @@ -5778,27 +6217,28 @@ a.dropdown-item.is-active { } @media screen and (min-width: 1024px) { .navbar.is-danger .navbar-start > .navbar-item, -.navbar.is-danger .navbar-start .navbar-link, -.navbar.is-danger .navbar-end > .navbar-item, -.navbar.is-danger .navbar-end .navbar-link { + .navbar.is-danger .navbar-start .navbar-link, + .navbar.is-danger .navbar-end > .navbar-item, + .navbar.is-danger .navbar-end .navbar-link { color: #fff; } - .navbar.is-danger .navbar-start > a.navbar-item:hover, .navbar.is-danger .navbar-start > a.navbar-item.is-active, -.navbar.is-danger .navbar-start .navbar-link:hover, -.navbar.is-danger .navbar-start .navbar-link.is-active, -.navbar.is-danger .navbar-end > a.navbar-item:hover, -.navbar.is-danger .navbar-end > a.navbar-item.is-active, -.navbar.is-danger .navbar-end .navbar-link:hover, -.navbar.is-danger .navbar-end .navbar-link.is-active { + .navbar.is-danger .navbar-start > a.navbar-item:hover, + .navbar.is-danger .navbar-start > a.navbar-item.is-active, + .navbar.is-danger .navbar-start .navbar-link:hover, + .navbar.is-danger .navbar-start .navbar-link.is-active, + .navbar.is-danger .navbar-end > a.navbar-item:hover, + .navbar.is-danger .navbar-end > a.navbar-item.is-active, + .navbar.is-danger .navbar-end .navbar-link:hover, + .navbar.is-danger .navbar-end .navbar-link.is-active { background-color: #ff1f4b; color: #fff; } .navbar.is-danger .navbar-start .navbar-link::after, -.navbar.is-danger .navbar-end .navbar-link::after { + .navbar.is-danger .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-danger .navbar-item.has-dropdown:hover .navbar-link, -.navbar.is-danger .navbar-item.has-dropdown.is-active .navbar-link { + .navbar.is-danger .navbar-item.has-dropdown.is-active .navbar-link { background-color: #ff1f4b; color: #fff; } @@ -5816,7 +6256,8 @@ a.dropdown-item.is-active { .navbar.has-shadow { box-shadow: 0 2px 0 0 whitesmoke; } -.navbar.is-fixed-bottom, .navbar.is-fixed-top { +.navbar.is-fixed-bottom, +.navbar.is-fixed-top { left: 0; position: fixed; right: 0; @@ -5925,7 +6366,8 @@ a.navbar-item, .navbar-link { cursor: pointer; } -a.navbar-item:hover, a.navbar-item.is-active, +a.navbar-item:hover, +a.navbar-item.is-active, .navbar-link:hover, .navbar-link.is-active { background-color: #fafafa; @@ -6003,7 +6445,7 @@ a.navbar-item:hover, a.navbar-item.is-active, } .navbar-brand .navbar-item, -.navbar-tabs .navbar-item { + .navbar-tabs .navbar-item { align-items: center; display: flex; } @@ -6021,7 +6463,8 @@ a.navbar-item:hover, a.navbar-item.is-active, display: block; } - .navbar.is-fixed-bottom-touch, .navbar.is-fixed-top-touch { + .navbar.is-fixed-bottom-touch, + .navbar.is-fixed-top-touch { left: 0; position: fixed; right: 0; @@ -6036,26 +6479,27 @@ a.navbar-item:hover, a.navbar-item.is-active, .navbar.is-fixed-top-touch { top: 0; } - .navbar.is-fixed-top .navbar-menu, .navbar.is-fixed-top-touch .navbar-menu { + .navbar.is-fixed-top .navbar-menu, + .navbar.is-fixed-top-touch .navbar-menu { -webkit-overflow-scrolling: touch; max-height: calc(100vh - 3.25rem); overflow: auto; } html.has-navbar-fixed-top-touch, -body.has-navbar-fixed-top-touch { + body.has-navbar-fixed-top-touch { padding-top: 3.25rem; } html.has-navbar-fixed-bottom-touch, -body.has-navbar-fixed-bottom-touch { + body.has-navbar-fixed-bottom-touch { padding-bottom: 3.25rem; } } @media screen and (min-width: 1024px) { .navbar, -.navbar-menu, -.navbar-start, -.navbar-end { + .navbar-menu, + .navbar-start, + .navbar-end { align-items: stretch; display: flex; } @@ -6067,19 +6511,23 @@ body.has-navbar-fixed-bottom-touch { padding: 1rem 2rem; } .navbar.is-spaced .navbar-start, -.navbar.is-spaced .navbar-end { + .navbar.is-spaced .navbar-end { align-items: center; } .navbar.is-spaced a.navbar-item, -.navbar.is-spaced .navbar-link { + .navbar.is-spaced .navbar-link { border-radius: 4px; } - .navbar.is-transparent a.navbar-item:hover, .navbar.is-transparent a.navbar-item.is-active, -.navbar.is-transparent .navbar-link:hover, -.navbar.is-transparent .navbar-link.is-active { + .navbar.is-transparent a.navbar-item:hover, + .navbar.is-transparent a.navbar-item.is-active, + .navbar.is-transparent .navbar-link:hover, + .navbar.is-transparent .navbar-link.is-active { background-color: transparent !important; } - .navbar.is-transparent .navbar-item.has-dropdown.is-active .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:hover .navbar-link { + .navbar.is-transparent .navbar-item.has-dropdown.is-active .navbar-link, + .navbar.is-transparent + .navbar-item.has-dropdown.is-hoverable:hover + .navbar-link { background-color: transparent !important; } .navbar.is-transparent .navbar-dropdown a.navbar-item:hover { @@ -6096,7 +6544,7 @@ body.has-navbar-fixed-bottom-touch { } .navbar-item, -.navbar-link { + .navbar-link { align-items: center; display: flex; } @@ -6118,10 +6566,14 @@ body.has-navbar-fixed-bottom-touch { box-shadow: 0 -8px 8px rgba(10, 10, 10, 0.1); top: auto; } - .navbar-item.is-active .navbar-dropdown, .navbar-item.is-hoverable:hover .navbar-dropdown { + .navbar-item.is-active .navbar-dropdown, + .navbar-item.is-hoverable:hover .navbar-dropdown { display: block; } - .navbar.is-spaced .navbar-item.is-active .navbar-dropdown, .navbar-item.is-active .navbar-dropdown.is-boxed, .navbar.is-spaced .navbar-item.is-hoverable:hover .navbar-dropdown, .navbar-item.is-hoverable:hover .navbar-dropdown.is-boxed { + .navbar.is-spaced .navbar-item.is-active .navbar-dropdown, + .navbar-item.is-active .navbar-dropdown.is-boxed, + .navbar.is-spaced .navbar-item.is-hoverable:hover .navbar-dropdown, + .navbar-item.is-hoverable:hover .navbar-dropdown.is-boxed { opacity: 1; pointer-events: auto; transform: translateY(0); @@ -6171,10 +6623,13 @@ body.has-navbar-fixed-bottom-touch { background-color: whitesmoke; color: #3273dc; } - .navbar.is-spaced .navbar-dropdown, .navbar-dropdown.is-boxed { + .navbar.is-spaced .navbar-dropdown, + .navbar-dropdown.is-boxed { border-radius: 6px; border-top: none; - box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); + box-shadow: + 0 8px 8px rgba(10, 10, 10, 0.1), + 0 0 0 1px rgba(10, 10, 10, 0.1); display: block; opacity: 0; pointer-events: none; @@ -6193,15 +6648,16 @@ body.has-navbar-fixed-bottom-touch { } .navbar > .container .navbar-brand, -.container > .navbar .navbar-brand { + .container > .navbar .navbar-brand { margin-left: -0.75rem; } .navbar > .container .navbar-menu, -.container > .navbar .navbar-menu { + .container > .navbar .navbar-menu { margin-right: -0.75rem; } - .navbar.is-fixed-bottom-desktop, .navbar.is-fixed-top-desktop { + .navbar.is-fixed-bottom-desktop, + .navbar.is-fixed-top-desktop { left: 0; position: fixed; right: 0; @@ -6218,32 +6674,33 @@ body.has-navbar-fixed-bottom-touch { } html.has-navbar-fixed-top-desktop, -body.has-navbar-fixed-top-desktop { + body.has-navbar-fixed-top-desktop { padding-top: 3.25rem; } html.has-navbar-fixed-bottom-desktop, -body.has-navbar-fixed-bottom-desktop { + body.has-navbar-fixed-bottom-desktop { padding-bottom: 3.25rem; } html.has-spaced-navbar-fixed-top, -body.has-spaced-navbar-fixed-top { + body.has-spaced-navbar-fixed-top { padding-top: 5.25rem; } html.has-spaced-navbar-fixed-bottom, -body.has-spaced-navbar-fixed-bottom { + body.has-spaced-navbar-fixed-bottom { padding-bottom: 5.25rem; } a.navbar-item.is-active, -.navbar-link.is-active { + .navbar-link.is-active { color: #0a0a0a; } a.navbar-item.is-active:not(:hover), -.navbar-link.is-active:not(:hover) { + .navbar-link.is-active:not(:hover) { background-color: transparent; } - .navbar-item.has-dropdown:hover .navbar-link, .navbar-item.has-dropdown.is-active .navbar-link { + .navbar-item.has-dropdown:hover .navbar-link, + .navbar-item.has-dropdown.is-active .navbar-link { background-color: #fafafa; } } @@ -6351,7 +6808,7 @@ body.has-spaced-navbar-fixed-bottom { } .pagination-previous, -.pagination-next { + .pagination-next { flex-grow: 1; flex-shrink: 1; } @@ -6461,7 +6918,7 @@ body.has-spaced-navbar-fixed-bottom { justify-content: flex-start; padding: 0.5em 0.75em; } -.panel-block input[type=checkbox] { +.panel-block input[type="checkbox"] { margin-right: 0.75em; } .panel-block > .control { @@ -6958,158 +7415,202 @@ label.panel-block:hover { } } @media screen and (min-width: 769px), print { - .column.is-narrow, .column.is-narrow-tablet { + .column.is-narrow, + .column.is-narrow-tablet { flex: none; } - .column.is-full, .column.is-full-tablet { + .column.is-full, + .column.is-full-tablet { flex: none; width: 100%; } - .column.is-three-quarters, .column.is-three-quarters-tablet { + .column.is-three-quarters, + .column.is-three-quarters-tablet { flex: none; width: 75%; } - .column.is-two-thirds, .column.is-two-thirds-tablet { + .column.is-two-thirds, + .column.is-two-thirds-tablet { flex: none; width: 66.6666%; } - .column.is-half, .column.is-half-tablet { + .column.is-half, + .column.is-half-tablet { flex: none; width: 50%; } - .column.is-one-third, .column.is-one-third-tablet { + .column.is-one-third, + .column.is-one-third-tablet { flex: none; width: 33.3333%; } - .column.is-one-quarter, .column.is-one-quarter-tablet { + .column.is-one-quarter, + .column.is-one-quarter-tablet { flex: none; width: 25%; } - .column.is-one-fifth, .column.is-one-fifth-tablet { + .column.is-one-fifth, + .column.is-one-fifth-tablet { flex: none; width: 20%; } - .column.is-two-fifths, .column.is-two-fifths-tablet { + .column.is-two-fifths, + .column.is-two-fifths-tablet { flex: none; width: 40%; } - .column.is-three-fifths, .column.is-three-fifths-tablet { + .column.is-three-fifths, + .column.is-three-fifths-tablet { flex: none; width: 60%; } - .column.is-four-fifths, .column.is-four-fifths-tablet { + .column.is-four-fifths, + .column.is-four-fifths-tablet { flex: none; width: 80%; } - .column.is-offset-three-quarters, .column.is-offset-three-quarters-tablet { + .column.is-offset-three-quarters, + .column.is-offset-three-quarters-tablet { margin-left: 75%; } - .column.is-offset-two-thirds, .column.is-offset-two-thirds-tablet { + .column.is-offset-two-thirds, + .column.is-offset-two-thirds-tablet { margin-left: 66.6666%; } - .column.is-offset-half, .column.is-offset-half-tablet { + .column.is-offset-half, + .column.is-offset-half-tablet { margin-left: 50%; } - .column.is-offset-one-third, .column.is-offset-one-third-tablet { + .column.is-offset-one-third, + .column.is-offset-one-third-tablet { margin-left: 33.3333%; } - .column.is-offset-one-quarter, .column.is-offset-one-quarter-tablet { + .column.is-offset-one-quarter, + .column.is-offset-one-quarter-tablet { margin-left: 25%; } - .column.is-offset-one-fifth, .column.is-offset-one-fifth-tablet { + .column.is-offset-one-fifth, + .column.is-offset-one-fifth-tablet { margin-left: 20%; } - .column.is-offset-two-fifths, .column.is-offset-two-fifths-tablet { + .column.is-offset-two-fifths, + .column.is-offset-two-fifths-tablet { margin-left: 40%; } - .column.is-offset-three-fifths, .column.is-offset-three-fifths-tablet { + .column.is-offset-three-fifths, + .column.is-offset-three-fifths-tablet { margin-left: 60%; } - .column.is-offset-four-fifths, .column.is-offset-four-fifths-tablet { + .column.is-offset-four-fifths, + .column.is-offset-four-fifths-tablet { margin-left: 80%; } - .column.is-1, .column.is-1-tablet { + .column.is-1, + .column.is-1-tablet { flex: none; width: 8.3333333333%; } - .column.is-offset-1, .column.is-offset-1-tablet { + .column.is-offset-1, + .column.is-offset-1-tablet { margin-left: 8.3333333333%; } - .column.is-2, .column.is-2-tablet { + .column.is-2, + .column.is-2-tablet { flex: none; width: 16.6666666667%; } - .column.is-offset-2, .column.is-offset-2-tablet { + .column.is-offset-2, + .column.is-offset-2-tablet { margin-left: 16.6666666667%; } - .column.is-3, .column.is-3-tablet { + .column.is-3, + .column.is-3-tablet { flex: none; width: 25%; } - .column.is-offset-3, .column.is-offset-3-tablet { + .column.is-offset-3, + .column.is-offset-3-tablet { margin-left: 25%; } - .column.is-4, .column.is-4-tablet { + .column.is-4, + .column.is-4-tablet { flex: none; width: 33.3333333333%; } - .column.is-offset-4, .column.is-offset-4-tablet { + .column.is-offset-4, + .column.is-offset-4-tablet { margin-left: 33.3333333333%; } - .column.is-5, .column.is-5-tablet { + .column.is-5, + .column.is-5-tablet { flex: none; width: 41.6666666667%; } - .column.is-offset-5, .column.is-offset-5-tablet { + .column.is-offset-5, + .column.is-offset-5-tablet { margin-left: 41.6666666667%; } - .column.is-6, .column.is-6-tablet { + .column.is-6, + .column.is-6-tablet { flex: none; width: 50%; } - .column.is-offset-6, .column.is-offset-6-tablet { + .column.is-offset-6, + .column.is-offset-6-tablet { margin-left: 50%; } - .column.is-7, .column.is-7-tablet { + .column.is-7, + .column.is-7-tablet { flex: none; width: 58.3333333333%; } - .column.is-offset-7, .column.is-offset-7-tablet { + .column.is-offset-7, + .column.is-offset-7-tablet { margin-left: 58.3333333333%; } - .column.is-8, .column.is-8-tablet { + .column.is-8, + .column.is-8-tablet { flex: none; width: 66.6666666667%; } - .column.is-offset-8, .column.is-offset-8-tablet { + .column.is-offset-8, + .column.is-offset-8-tablet { margin-left: 66.6666666667%; } - .column.is-9, .column.is-9-tablet { + .column.is-9, + .column.is-9-tablet { flex: none; width: 75%; } - .column.is-offset-9, .column.is-offset-9-tablet { + .column.is-offset-9, + .column.is-offset-9-tablet { margin-left: 75%; } - .column.is-10, .column.is-10-tablet { + .column.is-10, + .column.is-10-tablet { flex: none; width: 83.3333333333%; } - .column.is-offset-10, .column.is-offset-10-tablet { + .column.is-offset-10, + .column.is-offset-10-tablet { margin-left: 83.3333333333%; } - .column.is-11, .column.is-11-tablet { + .column.is-11, + .column.is-11-tablet { flex: none; width: 91.6666666667%; } - .column.is-offset-11, .column.is-offset-11-tablet { + .column.is-offset-11, + .column.is-offset-11-tablet { margin-left: 91.6666666667%; } - .column.is-12, .column.is-12-tablet { + .column.is-12, + .column.is-12-tablet { flex: none; width: 100%; } - .column.is-offset-12, .column.is-offset-12-tablet { + .column.is-offset-12, + .column.is-offset-12-tablet { margin-left: 100%; } } @@ -8353,7 +8854,8 @@ label.panel-block:hover { .hero.is-white .navbar-link { color: rgba(10, 10, 10, 0.7); } -.hero.is-white a.navbar-item:hover, .hero.is-white a.navbar-item.is-active, +.hero.is-white a.navbar-item:hover, +.hero.is-white a.navbar-item.is-active, .hero.is-white .navbar-link:hover, .hero.is-white .navbar-link.is-active { background-color: #f2f2f2; @@ -8369,13 +8871,18 @@ label.panel-block:hover { .hero.is-white .tabs li.is-active a { opacity: 1; } -.hero.is-white .tabs.is-boxed a, .hero.is-white .tabs.is-toggle a { +.hero.is-white .tabs.is-boxed a, +.hero.is-white .tabs.is-toggle a { color: #0a0a0a; } -.hero.is-white .tabs.is-boxed a:hover, .hero.is-white .tabs.is-toggle a:hover { +.hero.is-white .tabs.is-boxed a:hover, +.hero.is-white .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-white .tabs.is-boxed li.is-active a, .hero.is-white .tabs.is-boxed li.is-active a:hover, .hero.is-white .tabs.is-toggle li.is-active a, .hero.is-white .tabs.is-toggle li.is-active a:hover { +.hero.is-white .tabs.is-boxed li.is-active a, +.hero.is-white .tabs.is-boxed li.is-active a:hover, +.hero.is-white .tabs.is-toggle li.is-active a, +.hero.is-white .tabs.is-toggle li.is-active a:hover { background-color: #0a0a0a; border-color: #0a0a0a; color: white; @@ -8385,7 +8892,12 @@ label.panel-block:hover { } @media screen and (max-width: 768px) { .hero.is-white.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #e8e3e4 0%, white 71%, white 100%); + background-image: linear-gradient( + 141deg, + #e8e3e4 0%, + white 71%, + white 100% + ); } } .hero.is-black { @@ -8415,7 +8927,8 @@ label.panel-block:hover { .hero.is-black .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-black a.navbar-item:hover, .hero.is-black a.navbar-item.is-active, +.hero.is-black a.navbar-item:hover, +.hero.is-black a.navbar-item.is-active, .hero.is-black .navbar-link:hover, .hero.is-black .navbar-link.is-active { background-color: black; @@ -8431,23 +8944,38 @@ label.panel-block:hover { .hero.is-black .tabs li.is-active a { opacity: 1; } -.hero.is-black .tabs.is-boxed a, .hero.is-black .tabs.is-toggle a { +.hero.is-black .tabs.is-boxed a, +.hero.is-black .tabs.is-toggle a { color: white; } -.hero.is-black .tabs.is-boxed a:hover, .hero.is-black .tabs.is-toggle a:hover { +.hero.is-black .tabs.is-boxed a:hover, +.hero.is-black .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-black .tabs.is-boxed li.is-active a, .hero.is-black .tabs.is-boxed li.is-active a:hover, .hero.is-black .tabs.is-toggle li.is-active a, .hero.is-black .tabs.is-toggle li.is-active a:hover { +.hero.is-black .tabs.is-boxed li.is-active a, +.hero.is-black .tabs.is-boxed li.is-active a:hover, +.hero.is-black .tabs.is-toggle li.is-active a, +.hero.is-black .tabs.is-toggle li.is-active a:hover { background-color: white; border-color: white; color: #0a0a0a; } .hero.is-black.is-bold { - background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); + background-image: linear-gradient( + 141deg, + black 0%, + #0a0a0a 71%, + #181616 100% + ); } @media screen and (max-width: 768px) { .hero.is-black.is-bold .navbar-menu { - background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); + background-image: linear-gradient( + 141deg, + black 0%, + #0a0a0a 71%, + #181616 100% + ); } } .hero.is-light { @@ -8477,7 +9005,8 @@ label.panel-block:hover { .hero.is-light .navbar-link { color: rgba(54, 54, 54, 0.7); } -.hero.is-light a.navbar-item:hover, .hero.is-light a.navbar-item.is-active, +.hero.is-light a.navbar-item:hover, +.hero.is-light a.navbar-item.is-active, .hero.is-light .navbar-link:hover, .hero.is-light .navbar-link.is-active { background-color: #e8e8e8; @@ -8493,23 +9022,38 @@ label.panel-block:hover { .hero.is-light .tabs li.is-active a { opacity: 1; } -.hero.is-light .tabs.is-boxed a, .hero.is-light .tabs.is-toggle a { +.hero.is-light .tabs.is-boxed a, +.hero.is-light .tabs.is-toggle a { color: #363636; } -.hero.is-light .tabs.is-boxed a:hover, .hero.is-light .tabs.is-toggle a:hover { +.hero.is-light .tabs.is-boxed a:hover, +.hero.is-light .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-light .tabs.is-boxed li.is-active a, .hero.is-light .tabs.is-boxed li.is-active a:hover, .hero.is-light .tabs.is-toggle li.is-active a, .hero.is-light .tabs.is-toggle li.is-active a:hover { +.hero.is-light .tabs.is-boxed li.is-active a, +.hero.is-light .tabs.is-boxed li.is-active a:hover, +.hero.is-light .tabs.is-toggle li.is-active a, +.hero.is-light .tabs.is-toggle li.is-active a:hover { background-color: #363636; border-color: #363636; color: whitesmoke; } .hero.is-light.is-bold { - background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); + background-image: linear-gradient( + 141deg, + #dfd8d9 0%, + whitesmoke 71%, + white 100% + ); } @media screen and (max-width: 768px) { .hero.is-light.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); + background-image: linear-gradient( + 141deg, + #dfd8d9 0%, + whitesmoke 71%, + white 100% + ); } } .hero.is-dark { @@ -8539,7 +9083,8 @@ label.panel-block:hover { .hero.is-dark .navbar-link { color: rgba(245, 245, 245, 0.7); } -.hero.is-dark a.navbar-item:hover, .hero.is-dark a.navbar-item.is-active, +.hero.is-dark a.navbar-item:hover, +.hero.is-dark a.navbar-item.is-active, .hero.is-dark .navbar-link:hover, .hero.is-dark .navbar-link.is-active { background-color: #292929; @@ -8555,23 +9100,38 @@ label.panel-block:hover { .hero.is-dark .tabs li.is-active a { opacity: 1; } -.hero.is-dark .tabs.is-boxed a, .hero.is-dark .tabs.is-toggle a { +.hero.is-dark .tabs.is-boxed a, +.hero.is-dark .tabs.is-toggle a { color: whitesmoke; } -.hero.is-dark .tabs.is-boxed a:hover, .hero.is-dark .tabs.is-toggle a:hover { +.hero.is-dark .tabs.is-boxed a:hover, +.hero.is-dark .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-dark .tabs.is-boxed li.is-active a, .hero.is-dark .tabs.is-boxed li.is-active a:hover, .hero.is-dark .tabs.is-toggle li.is-active a, .hero.is-dark .tabs.is-toggle li.is-active a:hover { +.hero.is-dark .tabs.is-boxed li.is-active a, +.hero.is-dark .tabs.is-boxed li.is-active a:hover, +.hero.is-dark .tabs.is-toggle li.is-active a, +.hero.is-dark .tabs.is-toggle li.is-active a:hover { background-color: whitesmoke; border-color: whitesmoke; color: #363636; } .hero.is-dark.is-bold { - background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); + background-image: linear-gradient( + 141deg, + #1f191a 0%, + #363636 71%, + #46403f 100% + ); } @media screen and (max-width: 768px) { .hero.is-dark.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); + background-image: linear-gradient( + 141deg, + #1f191a 0%, + #363636 71%, + #46403f 100% + ); } } .hero.is-primary { @@ -8601,7 +9161,8 @@ label.panel-block:hover { .hero.is-primary .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-primary a.navbar-item:hover, .hero.is-primary a.navbar-item.is-active, +.hero.is-primary a.navbar-item:hover, +.hero.is-primary a.navbar-item.is-active, .hero.is-primary .navbar-link:hover, .hero.is-primary .navbar-link.is-active { background-color: #00b89c; @@ -8617,23 +9178,38 @@ label.panel-block:hover { .hero.is-primary .tabs li.is-active a { opacity: 1; } -.hero.is-primary .tabs.is-boxed a, .hero.is-primary .tabs.is-toggle a { +.hero.is-primary .tabs.is-boxed a, +.hero.is-primary .tabs.is-toggle a { color: #fff; } -.hero.is-primary .tabs.is-boxed a:hover, .hero.is-primary .tabs.is-toggle a:hover { +.hero.is-primary .tabs.is-boxed a:hover, +.hero.is-primary .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-primary .tabs.is-boxed li.is-active a, .hero.is-primary .tabs.is-boxed li.is-active a:hover, .hero.is-primary .tabs.is-toggle li.is-active a, .hero.is-primary .tabs.is-toggle li.is-active a:hover { +.hero.is-primary .tabs.is-boxed li.is-active a, +.hero.is-primary .tabs.is-boxed li.is-active a:hover, +.hero.is-primary .tabs.is-toggle li.is-active a, +.hero.is-primary .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #00d1b2; } .hero.is-primary.is-bold { - background-image: linear-gradient(141deg, #009e6c 0%, #00d1b2 71%, #00e7eb 100%); + background-image: linear-gradient( + 141deg, + #009e6c 0%, + #00d1b2 71%, + #00e7eb 100% + ); } @media screen and (max-width: 768px) { .hero.is-primary.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #009e6c 0%, #00d1b2 71%, #00e7eb 100%); + background-image: linear-gradient( + 141deg, + #009e6c 0%, + #00d1b2 71%, + #00e7eb 100% + ); } } .hero.is-link { @@ -8663,7 +9239,8 @@ label.panel-block:hover { .hero.is-link .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-link a.navbar-item:hover, .hero.is-link a.navbar-item.is-active, +.hero.is-link a.navbar-item:hover, +.hero.is-link a.navbar-item.is-active, .hero.is-link .navbar-link:hover, .hero.is-link .navbar-link.is-active { background-color: #2366d1; @@ -8679,23 +9256,38 @@ label.panel-block:hover { .hero.is-link .tabs li.is-active a { opacity: 1; } -.hero.is-link .tabs.is-boxed a, .hero.is-link .tabs.is-toggle a { +.hero.is-link .tabs.is-boxed a, +.hero.is-link .tabs.is-toggle a { color: #fff; } -.hero.is-link .tabs.is-boxed a:hover, .hero.is-link .tabs.is-toggle a:hover { +.hero.is-link .tabs.is-boxed a:hover, +.hero.is-link .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-link .tabs.is-boxed li.is-active a, .hero.is-link .tabs.is-boxed li.is-active a:hover, .hero.is-link .tabs.is-toggle li.is-active a, .hero.is-link .tabs.is-toggle li.is-active a:hover { +.hero.is-link .tabs.is-boxed li.is-active a, +.hero.is-link .tabs.is-boxed li.is-active a:hover, +.hero.is-link .tabs.is-toggle li.is-active a, +.hero.is-link .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #3273dc; } .hero.is-link.is-bold { - background-image: linear-gradient(141deg, #1577c6 0%, #3273dc 71%, #4366e5 100%); + background-image: linear-gradient( + 141deg, + #1577c6 0%, + #3273dc 71%, + #4366e5 100% + ); } @media screen and (max-width: 768px) { .hero.is-link.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #1577c6 0%, #3273dc 71%, #4366e5 100%); + background-image: linear-gradient( + 141deg, + #1577c6 0%, + #3273dc 71%, + #4366e5 100% + ); } } .hero.is-info { @@ -8725,7 +9317,8 @@ label.panel-block:hover { .hero.is-info .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-info a.navbar-item:hover, .hero.is-info a.navbar-item.is-active, +.hero.is-info a.navbar-item:hover, +.hero.is-info a.navbar-item.is-active, .hero.is-info .navbar-link:hover, .hero.is-info .navbar-link.is-active { background-color: #118fe4; @@ -8741,23 +9334,38 @@ label.panel-block:hover { .hero.is-info .tabs li.is-active a { opacity: 1; } -.hero.is-info .tabs.is-boxed a, .hero.is-info .tabs.is-toggle a { +.hero.is-info .tabs.is-boxed a, +.hero.is-info .tabs.is-toggle a { color: #fff; } -.hero.is-info .tabs.is-boxed a:hover, .hero.is-info .tabs.is-toggle a:hover { +.hero.is-info .tabs.is-boxed a:hover, +.hero.is-info .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-info .tabs.is-boxed li.is-active a, .hero.is-info .tabs.is-boxed li.is-active a:hover, .hero.is-info .tabs.is-toggle li.is-active a, .hero.is-info .tabs.is-toggle li.is-active a:hover { +.hero.is-info .tabs.is-boxed li.is-active a, +.hero.is-info .tabs.is-boxed li.is-active a:hover, +.hero.is-info .tabs.is-toggle li.is-active a, +.hero.is-info .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #209cee; } .hero.is-info.is-bold { - background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); + background-image: linear-gradient( + 141deg, + #04a6d7 0%, + #209cee 71%, + #3287f5 100% + ); } @media screen and (max-width: 768px) { .hero.is-info.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); + background-image: linear-gradient( + 141deg, + #04a6d7 0%, + #209cee 71%, + #3287f5 100% + ); } } .hero.is-success { @@ -8787,7 +9395,8 @@ label.panel-block:hover { .hero.is-success .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-success a.navbar-item:hover, .hero.is-success a.navbar-item.is-active, +.hero.is-success a.navbar-item:hover, +.hero.is-success a.navbar-item.is-active, .hero.is-success .navbar-link:hover, .hero.is-success .navbar-link.is-active { background-color: #20bc56; @@ -8803,23 +9412,38 @@ label.panel-block:hover { .hero.is-success .tabs li.is-active a { opacity: 1; } -.hero.is-success .tabs.is-boxed a, .hero.is-success .tabs.is-toggle a { +.hero.is-success .tabs.is-boxed a, +.hero.is-success .tabs.is-toggle a { color: #fff; } -.hero.is-success .tabs.is-boxed a:hover, .hero.is-success .tabs.is-toggle a:hover { +.hero.is-success .tabs.is-boxed a:hover, +.hero.is-success .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-success .tabs.is-boxed li.is-active a, .hero.is-success .tabs.is-boxed li.is-active a:hover, .hero.is-success .tabs.is-toggle li.is-active a, .hero.is-success .tabs.is-toggle li.is-active a:hover { +.hero.is-success .tabs.is-boxed li.is-active a, +.hero.is-success .tabs.is-boxed li.is-active a:hover, +.hero.is-success .tabs.is-toggle li.is-active a, +.hero.is-success .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #23d160; } .hero.is-success.is-bold { - background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); + background-image: linear-gradient( + 141deg, + #12af2f 0%, + #23d160 71%, + #2ce28a 100% + ); } @media screen and (max-width: 768px) { .hero.is-success.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); + background-image: linear-gradient( + 141deg, + #12af2f 0%, + #23d160 71%, + #2ce28a 100% + ); } } .hero.is-warning { @@ -8849,7 +9473,8 @@ label.panel-block:hover { .hero.is-warning .navbar-link { color: rgba(0, 0, 0, 0.7); } -.hero.is-warning a.navbar-item:hover, .hero.is-warning a.navbar-item.is-active, +.hero.is-warning a.navbar-item:hover, +.hero.is-warning a.navbar-item.is-active, .hero.is-warning .navbar-link:hover, .hero.is-warning .navbar-link.is-active { background-color: #ffd83d; @@ -8865,23 +9490,38 @@ label.panel-block:hover { .hero.is-warning .tabs li.is-active a { opacity: 1; } -.hero.is-warning .tabs.is-boxed a, .hero.is-warning .tabs.is-toggle a { +.hero.is-warning .tabs.is-boxed a, +.hero.is-warning .tabs.is-toggle a { color: rgba(0, 0, 0, 0.7); } -.hero.is-warning .tabs.is-boxed a:hover, .hero.is-warning .tabs.is-toggle a:hover { +.hero.is-warning .tabs.is-boxed a:hover, +.hero.is-warning .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-warning .tabs.is-boxed li.is-active a, .hero.is-warning .tabs.is-boxed li.is-active a:hover, .hero.is-warning .tabs.is-toggle li.is-active a, .hero.is-warning .tabs.is-toggle li.is-active a:hover { +.hero.is-warning .tabs.is-boxed li.is-active a, +.hero.is-warning .tabs.is-boxed li.is-active a:hover, +.hero.is-warning .tabs.is-toggle li.is-active a, +.hero.is-warning .tabs.is-toggle li.is-active a:hover { background-color: rgba(0, 0, 0, 0.7); border-color: rgba(0, 0, 0, 0.7); color: #ffdd57; } .hero.is-warning.is-bold { - background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); + background-image: linear-gradient( + 141deg, + #ffaf24 0%, + #ffdd57 71%, + #fffa70 100% + ); } @media screen and (max-width: 768px) { .hero.is-warning.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); + background-image: linear-gradient( + 141deg, + #ffaf24 0%, + #ffdd57 71%, + #fffa70 100% + ); } } .hero.is-danger { @@ -8911,7 +9551,8 @@ label.panel-block:hover { .hero.is-danger .navbar-link { color: rgba(255, 255, 255, 0.7); } -.hero.is-danger a.navbar-item:hover, .hero.is-danger a.navbar-item.is-active, +.hero.is-danger a.navbar-item:hover, +.hero.is-danger a.navbar-item.is-active, .hero.is-danger .navbar-link:hover, .hero.is-danger .navbar-link.is-active { background-color: #ff1f4b; @@ -8927,23 +9568,38 @@ label.panel-block:hover { .hero.is-danger .tabs li.is-active a { opacity: 1; } -.hero.is-danger .tabs.is-boxed a, .hero.is-danger .tabs.is-toggle a { +.hero.is-danger .tabs.is-boxed a, +.hero.is-danger .tabs.is-toggle a { color: #fff; } -.hero.is-danger .tabs.is-boxed a:hover, .hero.is-danger .tabs.is-toggle a:hover { +.hero.is-danger .tabs.is-boxed a:hover, +.hero.is-danger .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } -.hero.is-danger .tabs.is-boxed li.is-active a, .hero.is-danger .tabs.is-boxed li.is-active a:hover, .hero.is-danger .tabs.is-toggle li.is-active a, .hero.is-danger .tabs.is-toggle li.is-active a:hover { +.hero.is-danger .tabs.is-boxed li.is-active a, +.hero.is-danger .tabs.is-boxed li.is-active a:hover, +.hero.is-danger .tabs.is-toggle li.is-active a, +.hero.is-danger .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #ff3860; } .hero.is-danger.is-bold { - background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); + background-image: linear-gradient( + 141deg, + #ff0561 0%, + #ff3860 71%, + #ff5257 100% + ); } @media screen and (max-width: 768px) { .hero.is-danger.is-bold .navbar-menu { - background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); + background-image: linear-gradient( + 141deg, + #ff0561 0%, + #ff3860 71%, + #ff5257 100% + ); } } .hero.is-small .hero-body { @@ -8962,11 +9618,13 @@ label.panel-block:hover { padding-top: 18rem; } } -.hero.is-halfheight .hero-body, .hero.is-fullheight .hero-body { +.hero.is-halfheight .hero-body, +.hero.is-fullheight .hero-body { align-items: center; display: flex; } -.hero.is-halfheight .hero-body > .container, .hero.is-fullheight .hero-body > .container { +.hero.is-halfheight .hero-body > .container, +.hero.is-fullheight .hero-body > .container { flex-grow: 1; flex-shrink: 1; } @@ -9052,7 +9710,7 @@ label.panel-block:hover { :root { --background: #222; --foreground: #252525; - --textColor: #EEE; + --textColor: #eee; --ppColour: #8992e8; --alternate: #72a8ff; @@ -9074,11 +9732,15 @@ body { background-color: var(--foreground) !important; color: var(--textColor) !important; - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.23), 0 5px 15px rgba(0, 0, 0, 0.18); + box-shadow: + 0 8px 20px rgba(0, 0, 0, 0.23), + 0 5px 15px rgba(0, 0, 0, 0.18); } .box.has-shadow:hover { - box-shadow: 0 15px 25px rgba(23, 23, 23, 0.63), 0 8px 15px rgba(0, 0, 0, 0.4) + box-shadow: + 0 15px 25px rgba(23, 23, 23, 0.63), + 0 8px 15px rgba(0, 0, 0, 0.4); } a { @@ -9117,7 +9779,7 @@ a.pagination-link { color: var(--textColor) !important; } -.diff{ +.diff { text-align: center !important; } @@ -9174,4 +9836,4 @@ label { .select select { background-color: #2d2d2d !important; color: var(--textColor) !important; -} \ No newline at end of file +} diff --git a/public/assets/ssr.css b/public/assets/ssr.css index 0d24ea1..e42f876 100644 --- a/public/assets/ssr.css +++ b/public/assets/ssr.css @@ -1,206 +1,207 @@ :root { - --background: #222; - --foreground: #252525; - --textColor: #eee; - --ppColour: #8992e8; - --alternate: #72a8ff; - --selected: #3273dc; - --hover: #333; - --highlight: #484848; - --decrease: #f94022; - --increase: #42b129; - --dimmed: #3e3e3e; - --faded: #666; - --color-ahead: rgb(0, 128, 0); - --color-behind: rgb(128, 0, 0); - --color-highlight: darkgreen; - --error: red; + --background: #222; + --foreground: #252525; + --textColor: #eee; + --ppColour: #8992e8; + --alternate: #72a8ff; + --selected: #3273dc; + --hover: #333; + --highlight: #484848; + --decrease: #f94022; + --increase: #42b129; + --dimmed: #3e3e3e; + --faded: #666; + --color-ahead: rgb(0, 128, 0); + --color-behind: rgb(128, 0, 0); + --color-highlight: darkgreen; + --error: red; } html { - height: --webkit-fill-available; + height: --webkit-fill-available; } body { - color: var(--textColor); - background-color: var(--background)!important; - margin: 0 auto; - padding: 0 1rem; - min-height: 100vh; - min-height: -webkit-fill-available; + color: var(--textColor); + background-color: var(--background) !important; + margin: 0 auto; + padding: 0 1rem; + min-height: 100vh; + min-height: -webkit-fill-available; } select { - color: var(--textColor); - background-color: var(--foreground); - outline: none; + color: var(--textColor); + background-color: var(--foreground); + outline: none; } .ssr-page-container { - width: 100%; - max-width: 1200px; - margin: 0 auto; + width: 100%; + max-width: 1200px; + margin: 0 auto; } .box { - padding: 1rem; + padding: 1rem; } .inc { - color: var(--increase); + color: var(--increase); } .dec { - color: var(--decrease); + color: var(--decrease); } -*[title]:not([title=""]):not(.clickable) {cursor: help;} +*[title]:not([title=""]):not(.clickable) { + cursor: help; +} .scoresaber-icon { - width: 100%; - height: 100%; - background-size: cover; - background-repeat: no-repeat; - background-image: url("./scoresaber-logo.svg"); + width: 100%; + height: 100%; + background-size: cover; + background-repeat: no-repeat; + background-image: url("./scoresaber-logo.svg"); } .beatsavior-icon { - width: 100%; - height: 100%; - background-size: cover; - background-repeat: no-repeat; - background-image: url("data:image/svg+xml,%3Csvg xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns%23' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns%23' xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' width='72.723976mm' height='63.291668mm' viewBox='0 0 72.723976 63.291668' version='1.1' id='svg3827' sodipodi:docname='bsicon_ter.svg' inkscape:version='0.92.4 (5da689c313, 2019-01-14)'%3E%3Cdefs id='defs3821' /%3E%3Csodipodi:namedview id='base' pagecolor='%23ffffff' bordercolor='%23666666' borderopacity='1.0' inkscape:pageopacity='0.0' inkscape:pageshadow='2' inkscape:zoom='1.4' inkscape:cx='40.905424' inkscape:cy='61.353566' inkscape:document-units='mm' inkscape:current-layer='layer1' showgrid='false' inkscape:window-width='1920' inkscape:window-height='1017' inkscape:window-x='-8' inkscape:window-y='-8' inkscape:window-maximized='1' /%3E%3Cmetadata id='metadata3824'%3E%3Crdf:RDF%3E%3Ccc:Work rdf:about=''%3E%3Cdc:format%3Eimage/svg+xml%3C/dc:format%3E%3Cdc:type rdf:resource='http://purl.org/dc/dcmitype/StillImage' /%3E%3Cdc:title%3E%3C/dc:title%3E%3C/cc:Work%3E%3C/rdf:RDF%3E%3C/metadata%3E%3Cg inkscape:label='Calque 1' inkscape:groupmode='layer' id='layer1' style='opacity:1' transform='translate(-0.72553574,-0.71711111)'%3E%3Crect style='fill:%23000200;fill-opacity:1;stroke:%23000000;stroke-width:1.98928511;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4531' width='63.5' height='10.583332' x='5.4550524' y='10.242103' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Crect style='fill:%23ffffff;fill-opacity:1;stroke:none;stroke-width:3.35483217;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4533' width='6.6145835' height='6.6145835' x='25.298788' y='11.565023' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Crect style='fill:%23ffffff;fill-opacity:1;stroke:none;stroke-width:3.92078424;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4533-5' width='6.6145835' height='6.6145835' x='42.496708' y='11.565023' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Cg id='g4614' transform='rotate(-23.417079,-23.695385,307.31208)' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757'%3E%3Crect y='86.127083' x='125.67709' height='1.3229166' width='50.270832' id='rect4610' style='fill:%230000ff;fill-opacity:1;stroke:%230000ff;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3Crect y='85.333328' x='109.80208' height='2.6458333' width='15.875' id='rect4605' style='fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3C/g%3E%3Cg transform='rotate(-156.98422,82.908484,73.919009)' id='g4614-3' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757'%3E%3Crect y='86.127083' x='125.67709' height='1.3229166' width='50.270832' id='rect4610-6' style='fill:%23ff0000;fill-opacity:1;stroke:%23ff0000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3Crect y='85.333328' x='109.80208' height='2.6458333' width='15.875' id='rect4605-7' style='fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A" - ); + width: 100%; + height: 100%; + background-size: cover; + background-repeat: no-repeat; + background-image: url("data:image/svg+xml,%3Csvg xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns%23' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns%23' xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' width='72.723976mm' height='63.291668mm' viewBox='0 0 72.723976 63.291668' version='1.1' id='svg3827' sodipodi:docname='bsicon_ter.svg' inkscape:version='0.92.4 (5da689c313, 2019-01-14)'%3E%3Cdefs id='defs3821' /%3E%3Csodipodi:namedview id='base' pagecolor='%23ffffff' bordercolor='%23666666' borderopacity='1.0' inkscape:pageopacity='0.0' inkscape:pageshadow='2' inkscape:zoom='1.4' inkscape:cx='40.905424' inkscape:cy='61.353566' inkscape:document-units='mm' inkscape:current-layer='layer1' showgrid='false' inkscape:window-width='1920' inkscape:window-height='1017' inkscape:window-x='-8' inkscape:window-y='-8' inkscape:window-maximized='1' /%3E%3Cmetadata id='metadata3824'%3E%3Crdf:RDF%3E%3Ccc:Work rdf:about=''%3E%3Cdc:format%3Eimage/svg+xml%3C/dc:format%3E%3Cdc:type rdf:resource='http://purl.org/dc/dcmitype/StillImage' /%3E%3Cdc:title%3E%3C/dc:title%3E%3C/cc:Work%3E%3C/rdf:RDF%3E%3C/metadata%3E%3Cg inkscape:label='Calque 1' inkscape:groupmode='layer' id='layer1' style='opacity:1' transform='translate(-0.72553574,-0.71711111)'%3E%3Crect style='fill:%23000200;fill-opacity:1;stroke:%23000000;stroke-width:1.98928511;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4531' width='63.5' height='10.583332' x='5.4550524' y='10.242103' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Crect style='fill:%23ffffff;fill-opacity:1;stroke:none;stroke-width:3.35483217;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4533' width='6.6145835' height='6.6145835' x='25.298788' y='11.565023' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Crect style='fill:%23ffffff;fill-opacity:1;stroke:none;stroke-width:3.92078424;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal' id='rect4533-5' width='6.6145835' height='6.6145835' x='42.496708' y='11.565023' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757' /%3E%3Cg id='g4614' transform='rotate(-23.417079,-23.695385,307.31208)' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757'%3E%3Crect y='86.127083' x='125.67709' height='1.3229166' width='50.270832' id='rect4610' style='fill:%230000ff;fill-opacity:1;stroke:%230000ff;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3Crect y='85.333328' x='109.80208' height='2.6458333' width='15.875' id='rect4605' style='fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3C/g%3E%3Cg transform='rotate(-156.98422,82.908484,73.919009)' id='g4614-3' inkscape:export-xdpi='81.844757' inkscape:export-ydpi='81.844757'%3E%3Crect y='86.127083' x='125.67709' height='1.3229166' width='50.270832' id='rect4610-6' style='fill:%23ff0000;fill-opacity:1;stroke:%23ff0000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3Crect y='85.333328' x='109.80208' height='2.6458333' width='15.875' id='rect4605-7' style='fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:2.64583325;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1' /%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A"); } .accsaber-icon { - width: 100%; - height: 100%; - background-size: cover; - background-repeat: no-repeat; - background-image: url("./accsaber-logo.png"); + width: 100%; + height: 100%; + background-size: cover; + background-repeat: no-repeat; + background-image: url("./accsaber-logo.png"); } .grid-transition-helper { - display: grid; - grid-template-columns: 1fr; - grid-template-rows: 1fr; + display: grid; + grid-template-columns: 1fr; + grid-template-rows: 1fr; } .grid-transition-helper > * { - grid-column: 1/1; + grid-column: 1/1; } .grid-transition-helper > .row-0 { - grid-row: 1/1; + grid-row: 1/1; } .grid-transition-helper > .row-1 { - grid-row: 2/2; + grid-row: 2/2; } .grid-transition-helper > .row-2 { - grid-row: 3/3; + grid-row: 3/3; } .grid-transition-helper > .row-3 { - grid-row: 4/4; + grid-row: 4/4; } .grid-transition-helper > .row-4 { - grid-row: 5/5; + grid-row: 5/5; } .grid-transition-helper > .row-5 { - grid-row: 6/6; + grid-row: 6/6; } .grid-transition-helper > .row-6 { - grid-row: 7/7; + grid-row: 7/7; } .grid-transition-helper > .row-7 { - grid-row: 8/8; + grid-row: 8/8; } .grid-transition-helper > .row-8 { - grid-row: 9/9; + grid-row: 9/9; } .grid-transition-helper > .row-9 { - grid-row: 10/10; + grid-row: 10/10; } .grid-transition-helper > .row-10 { - grid-row: 11/11; + grid-row: 11/11; } .grid-transition-helper > .row-11 { - grid-row: 12/12; + grid-row: 12/12; } .has-pointer-events { - pointer-events: fill; + pointer-events: fill; } .mobile-only { - display: none; + display: none; } .tablet-only { - display: none; + display: none; } .up-to-tablet { - display: none; + display: none; } @media screen and (max-width: 767px) { - .mobile-only { - display: block; - } + .mobile-only { + display: block; + } - .tablet-and-up { - display: none!important; - } + .tablet-and-up { + display: none !important; + } } @media screen and (max-width: 768px) { - .above-tablet { - display: none; - } + .above-tablet { + display: none; + } } -@media screen and (min-width:768px) and (max-width: 1023px) { - .tablet-only { - display: block; - } +@media screen and (min-width: 768px) and (max-width: 1023px) { + .tablet-only { + display: block; + } } @media screen and (max-width: 1023px) { - .up-to-tablet { - display: block; - } + .up-to-tablet { + display: block; + } - .desktop-and-up { - display: none!important; - } + .desktop-and-up { + display: none !important; + } } @media screen and (min-width: 1750px) { - body:not(.slim) .ssr-page-container { - max-width: 1750px !important; - } + body:not(.slim) .ssr-page-container { + max-width: 1750px !important; + } } @media screen and (max-width: 360px) { - body { - padding: 0; - } + body { + padding: 0; + } } @media screen and (max-width: 320px) { - html { - font-size: 15px; - } -} \ No newline at end of file + html { + font-size: 15px; + } +} diff --git a/public/assets/swiped-events.min.js b/public/assets/swiped-events.min.js index 7106ddd..f87c421 100644 --- a/public/assets/swiped-events.min.js +++ b/public/assets/swiped-events.min.js @@ -6,4 +6,89 @@ * @author John Doherty * @license MIT */ -!function(t,e){"use strict";"function"!=typeof t.CustomEvent&&(t.CustomEvent=function(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var a=e.createEvent("CustomEvent");return a.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),a},t.CustomEvent.prototype=t.Event.prototype),e.addEventListener("touchstart",function(t){if("true"===t.target.getAttribute("data-swipe-ignore"))return;s=t.target,r=Date.now(),n=t.touches[0].clientX,a=t.touches[0].clientY,u=0,i=0},!1),e.addEventListener("touchmove",function(t){if(!n||!a)return;var e=t.touches[0].clientX,r=t.touches[0].clientY;u=n-e,i=a-r},!1),e.addEventListener("touchend",function(t){if(s!==t.target)return;var e=parseInt(l(s,"data-swipe-threshold","20"),10),o=parseInt(l(s,"data-swipe-timeout","500"),10),c=Date.now()-r,d="",p=t.changedTouches||t.touches||[];Math.abs(u)>Math.abs(i)?Math.abs(u)>e&&c0?"swiped-left":"swiped-right"):Math.abs(i)>e&&c0?"swiped-up":"swiped-down");if(""!==d){var b={dir:d.replace(/swiped-/,""),xStart:parseInt(n,10),xEnd:parseInt((p[0]||{}).clientX||-1,10),yStart:parseInt(a,10),yEnd:parseInt((p[0]||{}).clientY||-1,10)};s.dispatchEvent(new CustomEvent("swiped",{bubbles:!0,cancelable:!0,detail:b})),s.dispatchEvent(new CustomEvent(d,{bubbles:!0,cancelable:!0,detail:b}))}n=null,a=null,r=null},!1);var n=null,a=null,u=null,i=null,r=null,s=null;function l(t,n,a){for(;t&&t!==e.documentElement;){var u=t.getAttribute(n);if(u)return u;t=t.parentNode}return a}}(window,document); \ No newline at end of file +!(function (t, e) { + "use strict"; + "function" != typeof t.CustomEvent && + ((t.CustomEvent = function (t, n) { + n = n || { bubbles: !1, cancelable: !1, detail: void 0 }; + var a = e.createEvent("CustomEvent"); + return a.initCustomEvent(t, n.bubbles, n.cancelable, n.detail), a; + }), + (t.CustomEvent.prototype = t.Event.prototype)), + e.addEventListener( + "touchstart", + function (t) { + if ("true" === t.target.getAttribute("data-swipe-ignore")) return; + (s = t.target), + (r = Date.now()), + (n = t.touches[0].clientX), + (a = t.touches[0].clientY), + (u = 0), + (i = 0); + }, + !1, + ), + e.addEventListener( + "touchmove", + function (t) { + if (!n || !a) return; + var e = t.touches[0].clientX, + r = t.touches[0].clientY; + (u = n - e), (i = a - r); + }, + !1, + ), + e.addEventListener( + "touchend", + function (t) { + if (s !== t.target) return; + var e = parseInt(l(s, "data-swipe-threshold", "20"), 10), + o = parseInt(l(s, "data-swipe-timeout", "500"), 10), + c = Date.now() - r, + d = "", + p = t.changedTouches || t.touches || []; + Math.abs(u) > Math.abs(i) + ? Math.abs(u) > e && + c < o && + (d = u > 0 ? "swiped-left" : "swiped-right") + : Math.abs(i) > e && + c < o && + (d = i > 0 ? "swiped-up" : "swiped-down"); + if ("" !== d) { + var b = { + dir: d.replace(/swiped-/, ""), + xStart: parseInt(n, 10), + xEnd: parseInt((p[0] || {}).clientX || -1, 10), + yStart: parseInt(a, 10), + yEnd: parseInt((p[0] || {}).clientY || -1, 10), + }; + s.dispatchEvent( + new CustomEvent("swiped", { + bubbles: !0, + cancelable: !0, + detail: b, + }), + ), + s.dispatchEvent( + new CustomEvent(d, { bubbles: !0, cancelable: !0, detail: b }), + ); + } + (n = null), (a = null), (r = null); + }, + !1, + ); + var n = null, + a = null, + u = null, + i = null, + r = null, + s = null; + function l(t, n, a) { + for (; t && t !== e.documentElement; ) { + var u = t.getAttribute(n); + if (u) return u; + t = t.parentNode; + } + return a; + } +})(window, document); diff --git a/public/index.html b/public/index.html index 832b7c8..5d98853 100644 --- a/public/index.html +++ b/public/index.html @@ -1,21 +1,23 @@ - + - - - + + + - ScoreSaber Reloaded + ScoreSaber Reloaded - - - - - + + + + + - - - + + + - - + diff --git a/rollup.config.js b/rollup.config.js index b651306..445e5f3 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,150 +1,159 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); const { execSync } = require("child_process"); -import svelte from 'rollup-plugin-svelte'; -import commonjs from '@rollup/plugin-commonjs'; -import resolve from '@rollup/plugin-node-resolve'; -import livereload from 'rollup-plugin-livereload'; -import { terser } from 'rollup-plugin-terser'; -import sveltePreprocess from 'svelte-preprocess'; -import css from 'rollup-plugin-css-only'; -import svg from 'rollup-plugin-svg'; +import svelte from "rollup-plugin-svelte"; +import commonjs from "@rollup/plugin-commonjs"; +import resolve from "@rollup/plugin-node-resolve"; +import livereload from "rollup-plugin-livereload"; +import { terser } from "rollup-plugin-terser"; +import sveltePreprocess from "svelte-preprocess"; +import css from "rollup-plugin-css-only"; +import svg from "rollup-plugin-svg"; const production = !process.env.ROLLUP_WATCH; const buildVersion = execSync("git rev-parse --short HEAD").toString(); -fs.writeFileSync('build-info.js', 'export default ' + JSON.stringify({ - buildDate: (new Date()).toISOString().substr(0, 19).replace('T', ' ') + ' UTC', - buildVersion -})) +fs.writeFileSync( + "build-info.js", + "export default " + + JSON.stringify({ + buildDate: + new Date().toISOString().substr(0, 19).replace("T", " ") + " UTC", + buildVersion, + }), +); function serve() { - let server; + let server; - function toExit() { - if (server) server.kill(0); - } + function toExit() { + if (server) server.kill(0); + } - return { - writeBundle() { - if (server) return; - server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], { - stdio: ['ignore', 'inherit', 'inherit'], - shell: true - }); + return { + writeBundle() { + if (server) return; + server = require("child_process").spawn( + "npm", + ["run", "start", "--", "--dev"], + { + stdio: ["ignore", "inherit", "inherit"], + shell: true, + }, + ); - process.on('SIGTERM', toExit); - process.on('exit', toExit); - } - }; + process.on("SIGTERM", toExit); + process.on("exit", toExit); + }, + }; } export default [ - { - input: 'src/main.js', - output: { - sourcemap: true, - format: 'iife', - name: 'app', - file: 'public/build/bundle.js', - }, - plugins: [ - svelte({ - preprocess: sveltePreprocess({sourceMap: !production}), - compilerOptions: { - // enable run-time checks when not in production - dev: !production, - }, - }), - // we'll extract any component CSS out into - // a separate file - better for performance - css({output: 'bundle.css'}), + { + input: "src/main.js", + output: { + sourcemap: true, + format: "iife", + name: "app", + file: "public/build/bundle.js", + }, + plugins: [ + svelte({ + preprocess: sveltePreprocess({ sourceMap: !production }), + compilerOptions: { + // enable run-time checks when not in production + dev: !production, + }, + }), + // we'll extract any component CSS out into + // a separate file - better for performance + css({ output: "bundle.css" }), - svg(), + svg(), - // If you have external dependencies installed from - // npm, you'll most likely need these plugins. In - // some cases you'll need additional configuration - - // consult the documentation for details: - // https://github.com/rollup/plugins/tree/master/packages/commonjs - resolve({ - browser: true, - dedupe: ['svelte'], - }), - commonjs(), + // If you have external dependencies installed from + // npm, you'll most likely need these plugins. In + // some cases you'll need additional configuration - + // consult the documentation for details: + // https://github.com/rollup/plugins/tree/master/packages/commonjs + resolve({ + browser: true, + dedupe: ["svelte"], + }), + commonjs(), - // In dev mode, call `npm run start` once - // the bundle has been generated - !production && serve(), + // In dev mode, call `npm run start` once + // the bundle has been generated + !production && serve(), - // Watch the `public` directory and refresh the - // browser on changes when not in production - !production && livereload('public'), + // Watch the `public` directory and refresh the + // browser on changes when not in production + !production && livereload("public"), - // If we're building for production (npm run build - // instead of npm run dev), minify - production && terser(), + // If we're building for production (npm run build + // instead of npm run dev), minify + production && terser(), - { - name: 'copy-comlink', - generateBundle() { - const buildDir = './public/build' - if (!fs.existsSync(buildDir)){ - fs.mkdirSync(buildDir); - } + { + name: "copy-comlink", + generateBundle() { + const buildDir = "./public/build"; + if (!fs.existsSync(buildDir)) { + fs.mkdirSync(buildDir); + } - fs.copyFileSync( - path.resolve('./node_modules/comlink/dist/umd/comlink.min.js'), - path.resolve('./public/build/comlink.min.js'), - ); - }, - }, - ], - watch: { - clearScreen: false, - }, - }, + fs.copyFileSync( + path.resolve("./node_modules/comlink/dist/umd/comlink.min.js"), + path.resolve("./public/build/comlink.min.js"), + ); + }, + }, + ], + watch: { + clearScreen: false, + }, + }, - { - input: 'src/workers/stats-worker.js', - output: { - sourcemap: true, - format: 'iife', - name: 'app', - file: 'public/build/stats-worker.js', - }, - plugins: [ - // If you have external dependencies installed from - // npm, you'll most likely need these plugins. In - // some cases you'll need additional configuration - - // consult the documentation for details: - // https://github.com/rollup/plugins/tree/master/packages/commonjs - resolve({ - browser: true, - dedupe: ['svelte'], - }), - commonjs(), + { + input: "src/workers/stats-worker.js", + output: { + sourcemap: true, + format: "iife", + name: "app", + file: "public/build/stats-worker.js", + }, + plugins: [ + // If you have external dependencies installed from + // npm, you'll most likely need these plugins. In + // some cases you'll need additional configuration - + // consult the documentation for details: + // https://github.com/rollup/plugins/tree/master/packages/commonjs + resolve({ + browser: true, + dedupe: ["svelte"], + }), + commonjs(), - // If we're building for production (npm run build - // instead of npm run dev), minify - production && terser(), - { - name: 'copy-test-worker', - load() { - this.addWatchFile(path.resolve('./src/workers/stats-worker.js')); - }, - generateBundle() { - const buildDir = './public/build' - if (!fs.existsSync(buildDir)){ - fs.mkdirSync(buildDir); - } + // If we're building for production (npm run build + // instead of npm run dev), minify + production && terser(), + { + name: "copy-test-worker", + load() { + this.addWatchFile(path.resolve("./src/workers/stats-worker.js")); + }, + generateBundle() { + const buildDir = "./public/build"; + if (!fs.existsSync(buildDir)) { + fs.mkdirSync(buildDir); + } - fs.copyFileSync( - path.resolve('./src/workers/stats-worker.js'), - path.resolve('./public/build/stats-worker.js'), - ); - }, - }, - ], - }, + fs.copyFileSync( + path.resolve("./src/workers/stats-worker.js"), + path.resolve("./public/build/stats-worker.js"), + ); + }, + }, + ], + }, ]; diff --git a/src/components/Player/Charts/utils/legend-click-handler.js b/src/components/Player/Charts/utils/legend-click-handler.js index d063d59..fe3caad 100644 --- a/src/components/Player/Charts/utils/legend-click-handler.js +++ b/src/components/Player/Charts/utils/legend-click-handler.js @@ -5,7 +5,7 @@ export const onLegendClick = (event, legendItem, legend) => { const scales = legend?.chart?.config?.options?.scales; if (!scales) return; - const {x: xAxis, ...yAxes} = scales; + const { x: xAxis, ...yAxes } = scales; if (ci.isDatasetVisible(idx)) { ci.hide(idx); @@ -17,38 +17,52 @@ export const onLegendClick = (event, legendItem, legend) => { if (legend?.chart) { const yAxisIdsToShow = (legend?.legendItems ?? []) - .sort((a,b) => (ci?.config?.data?.datasets?.[a?.datasetIndex]?.axisOrder ?? a?.datasetIndex) - (ci?.config?.data?.datasets?.[b?.datasetIndex]?.axisOrder ?? b?.datasetIndex)) - .reduce((cum, legendItem) => { - // done - if (cum.second) return cum; + .sort( + (a, b) => + (ci?.config?.data?.datasets?.[a?.datasetIndex]?.axisOrder ?? + a?.datasetIndex) - + (ci?.config?.data?.datasets?.[b?.datasetIndex]?.axisOrder ?? + b?.datasetIndex), + ) + .reduce( + (cum, legendItem) => { + // done + if (cum.second) return cum; - // skip hidden legend items - if (legendItem?.hidden) return cum; + // skip hidden legend items + if (legendItem?.hidden) return cum; - const yAxisId = ci?.getDatasetMeta(legendItem?.datasetIndex)?.yAxisID ?? null; - if (!yAxisId) return cum; + const yAxisId = + ci?.getDatasetMeta(legendItem?.datasetIndex)?.yAxisID ?? null; + if (!yAxisId) return cum; - if (!cum.first) { - cum.first = yAxisId; - } else if (yAxisId !== cum.first) { - cum.second = yAxisId; - } + if (!cum.first) { + cum.first = yAxisId; + } else if (yAxisId !== cum.first) { + cum.second = yAxisId; + } - return cum; - }, {first: null, second: null}); + return cum; + }, + { first: null, second: null }, + ); - Object.keys(yAxes).forEach(currentAxisKey => { - if (![yAxisIdsToShow.first, yAxisIdsToShow.second].includes(currentAxisKey)) { + Object.keys(yAxes).forEach((currentAxisKey) => { + if ( + ![yAxisIdsToShow.first, yAxisIdsToShow.second].includes(currentAxisKey) + ) { yAxes[currentAxisKey].display = false; return; } yAxes[currentAxisKey].display = true; - if (yAxisIdsToShow.first === currentAxisKey) yAxes[currentAxisKey].position = 'left'; - if (yAxisIdsToShow.second === currentAxisKey) yAxes[currentAxisKey].position = 'right'; + if (yAxisIdsToShow.first === currentAxisKey) + yAxes[currentAxisKey].position = "left"; + if (yAxisIdsToShow.second === currentAxisKey) + yAxes[currentAxisKey].position = "right"; }); - legend.chart.options.scales = {x: xAxis, ...yAxes} + legend.chart.options.scales = { x: xAxis, ...yAxes }; legend.chart.update(); } -} \ No newline at end of file +}; diff --git a/src/components/Player/Charts/utils/regions-plugin.js b/src/components/Player/Charts/utils/regions-plugin.js index 99586a3..ae3b161 100644 --- a/src/components/Player/Charts/utils/regions-plugin.js +++ b/src/components/Player/Charts/utils/regions-plugin.js @@ -1,22 +1,29 @@ export default { - id: 'regions', + id: "regions", beforeDraw(chart, args, options) { if (!options?.regions || !Array.isArray(options.regions)) return; - const {ctx, chartArea: {left, top, right, bottom}, scales: {y}} = chart; + const { + ctx, + chartArea: { left, top, right, bottom }, + scales: { y }, + } = chart; const width = right - left; - let fontSize = parseInt(ctx.font,10); + let fontSize = parseInt(ctx.font, 10); if (isNaN(fontSize)) fontSize = 12; ctx.save(); - options.regions.forEach(region => { + options.regions.forEach((region) => { if (y.min <= region.max && y.max >= region.min) { const minY = Math.max(region.min, y.min); const maxY = Math.min(region.max, y.max); const top = y.getPixelForValue(maxY); - const height = region.min === region.max ? 1 : y.getPixelForValue(minY) - y.getPixelForValue(maxY); + const height = + region.min === region.max + ? 1 + : y.getPixelForValue(minY) - y.getPixelForValue(maxY); ctx.fillStyle = region.color; ctx.fillRect(left, top, width, height); @@ -24,16 +31,20 @@ export default { if (region.label) { const labelWidth = ctx.measureText(region.label)?.width ?? 0; - ctx.textBaseline = 'top'; + ctx.textBaseline = "top"; ctx.fillText( region.label, - region?.position?.horizontal === 'right' ? right - labelWidth - 3 : left + 3, - region?.position?.vertical === 'bottom' ? top + 2 : top - fontSize - 1 + region?.position?.horizontal === "right" + ? right - labelWidth - 3 + : left + 3, + region?.position?.vertical === "bottom" + ? top + 2 + : top - fontSize - 1, ); } } - }) + }); ctx.restore(); - } -} \ No newline at end of file + }, +}; diff --git a/src/components/Player/utils/profile.js b/src/components/Player/utils/profile.js index e8d58f9..cb185bd 100644 --- a/src/components/Player/utils/profile.js +++ b/src/components/Player/utils/profile.js @@ -70,7 +70,7 @@ function updateScoresStats(playerData, playerStats) { bgColor: "var(--ppColour)", }, ] - : [] + : [], ) .filter((s) => s && (!playerStats || s.label !== "Average")); } diff --git a/src/components/Player/utils/service-param-manager.js b/src/components/Player/utils/service-param-manager.js index 006a94b..5b4ee41 100644 --- a/src/components/Player/utils/service-param-manager.js +++ b/src/components/Player/utils/service-param-manager.js @@ -2,27 +2,34 @@ export default () => { let currentService = null; let currentServiceParams = {}; - const getAllServices = () => ['scoresaber', 'beatsavior', 'accsaber']; + const getAllServices = () => ["scoresaber", "beatsavior", "accsaber"]; - const get = () => ({service: currentService, params: currentServiceParams}); + const get = () => ({ service: currentService, params: currentServiceParams }); - const getDefaultParams = service => { + const getDefaultParams = (service) => { switch (service) { - case 'beatsavior': - return {sort: 'recent', order: 'desc', page: 1, filters: {}}; + case "beatsavior": + return { sort: "recent", order: "desc", page: 1, filters: {} }; - case 'accsaber': - return {type: 'overall', order: 'desc', sort: 'ap', page: 1, filters: {}} + case "accsaber": + return { + type: "overall", + order: "desc", + sort: "ap", + page: 1, + filters: {}, + }; - case 'scoresaber': + case "scoresaber": default: - return {sort: 'recent', order: 'desc', page: 1, filters: {}} + return { sort: "recent", order: "desc", page: 1, filters: {} }; } - } + }; const update = (serviceParams = {}, service = currentService) => { const availableServices = getAllServices(); - if (!availableServices.includes(service)) service = availableServices?.[0] ?? 'scoresaber'; + if (!availableServices.includes(service)) + service = availableServices?.[0] ?? "scoresaber"; const defaultServiceParams = getDefaultParams(service); @@ -32,84 +39,103 @@ export default () => { } // preserve old filters - serviceParams = {...serviceParams} + serviceParams = { ...serviceParams }; serviceParams.filters = { ...(currentServiceParams?.filters ?? {}), ...(serviceParams?.filters ?? {}), - } + }; currentService = service; - currentServiceParams = {...defaultServiceParams, ...currentServiceParams, ...serviceParams} + currentServiceParams = { + ...defaultServiceParams, + ...currentServiceParams, + ...serviceParams, + }; return get(); - } + }; - const clearServiceParams = () => currentServiceParams = {} + const clearServiceParams = () => (currentServiceParams = {}); const initFromUrl = (url = null) => { const availableServices = getAllServices(); - const defaultService = availableServices?.[0] ?? 'scoresaber'; - const paramsArr = url ? url.split('/') : [defaultService]; + const defaultService = availableServices?.[0] ?? "scoresaber"; + const paramsArr = url ? url.split("/") : [defaultService]; - const service = paramsArr[0] ?? 'scoresaber'; + const service = paramsArr[0] ?? "scoresaber"; const serviceDefaultParams = getDefaultParams(service); switch (service) { - case 'beatsavior': + case "beatsavior": return update( { sort: paramsArr[1] ?? serviceDefaultParams?.sort, - order: 'desc', + order: "desc", page: paramsArr[2] ?? serviceDefaultParams?.page, }, service, ); - case 'accsaber': + case "accsaber": return update( { type: paramsArr[1] ?? serviceDefaultParams?.type, sort: paramsArr[2] ?? serviceDefaultParams?.sort, - order: (paramsArr[2] ?? serviceDefaultParams?.sort) === 'rank' ? 'asc' : 'desc', + order: + (paramsArr[2] ?? serviceDefaultParams?.sort) === "rank" + ? "asc" + : "desc", page: paramsArr[3] ?? serviceDefaultParams?.page, }, service, ); - case 'scoresaber': + case "scoresaber": default: return update( { sort: paramsArr[1] ?? serviceDefaultParams?.sort, - order: (paramsArr[1] ?? serviceDefaultParams?.sort) === 'rank' ? 'asc' : 'desc', + order: + (paramsArr[1] ?? serviceDefaultParams?.sort) === "rank" + ? "asc" + : "desc", page: paramsArr[2] ?? serviceDefaultParams?.page, }, service, ); } - } + }; const getUrl = (service, params = {}, noPage = false) => { - if (!service) return ''; + if (!service) return ""; const serviceDefaultParams = getDefaultParams(service); switch (service) { - case 'beatsavior': - return `${service}/${params?.sort ?? serviceDefaultParams?.sort}${noPage ? '' : `/${params?.page ?? serviceDefaultParams?.page}`}`; + case "beatsavior": + return `${service}/${params?.sort ?? serviceDefaultParams?.sort}${ + noPage ? "" : `/${params?.page ?? serviceDefaultParams?.page}` + }`; - case 'accsaber': - return `${service}/${params?.type ?? serviceDefaultParams?.type}/${params?.sort ?? serviceDefaultParams?.sort}${noPage ? '' : `/${params?.page ?? serviceDefaultParams?.page}`}`; + case "accsaber": + return `${service}/${params?.type ?? serviceDefaultParams?.type}/${ + params?.sort ?? serviceDefaultParams?.sort + }${noPage ? "" : `/${params?.page ?? serviceDefaultParams?.page}`}`; - case 'scoresaber': - return `${service}/${params?.sort ?? serviceDefaultParams?.sort}${noPage ? '' : `/${params?.page ?? serviceDefaultParams?.page}`}`; + case "scoresaber": + return `${service}/${params?.sort ?? serviceDefaultParams?.sort}${ + noPage ? "" : `/${params?.page ?? serviceDefaultParams?.page}` + }`; } - } + }; - const getCurrentServiceUrl = () => getUrl(currentService, currentServiceParams); - const getCurrentServiceUrlWithoutPage = () => getUrl(currentService, currentServiceParams, true); - const getDefaultServiceUrl = (service = currentService) => getUrl(service, {}); + const getCurrentServiceUrl = () => + getUrl(currentService, currentServiceParams); + const getCurrentServiceUrlWithoutPage = () => + getUrl(currentService, currentServiceParams, true); + const getDefaultServiceUrl = (service = currentService) => + getUrl(service, {}); return { getAvailableServices: getAllServices, @@ -122,5 +148,5 @@ export default () => { getParams: () => currentServiceParams, update, clearServiceParams, - } -} \ No newline at end of file + }; +}; diff --git a/src/db/cache.js b/src/db/cache.js index 8a35e74..00c66e0 100644 --- a/src/db/cache.js +++ b/src/db/cache.js @@ -1,19 +1,29 @@ -import eventBus from '../utils/broadcast-channel-pubsub' +import eventBus from "../utils/broadcast-channel-pubsub"; export default (name, getObjKey) => { let cache = {}; // update data cached on another node - eventBus.on('cache-key-set-' + name, ({key, value}, isLocal) => !isLocal ? set(key, value, false) : null); - eventBus.on('cache-all-set' + name, ({data}, isLocal) => !isLocal ? setAll(data, false) : null); - eventBus.on('cache-merge-' + name, ({data}, isLocal) => !isLocal ? merge(data, false) : null); - eventBus.on('cache-key-forget-' + name, ({key}, isLocal) => !isLocal ? forget(key, false) : null); - eventBus.on('cache-flush-' + name, (_, isLocal) => !isLocal ? flush(false) : null); + eventBus.on("cache-key-set-" + name, ({ key, value }, isLocal) => + !isLocal ? set(key, value, false) : null, + ); + eventBus.on("cache-all-set" + name, ({ data }, isLocal) => + !isLocal ? setAll(data, false) : null, + ); + eventBus.on("cache-merge-" + name, ({ data }, isLocal) => + !isLocal ? merge(data, false) : null, + ); + eventBus.on("cache-key-forget-" + name, ({ key }, isLocal) => + !isLocal ? forget(key, false) : null, + ); + eventBus.on("cache-flush-" + name, (_, isLocal) => + !isLocal ? flush(false) : null, + ); const set = (key, value, emitEvent = true) => { cache[key] = value; - if (emitEvent) eventBus.publish('cache-key-set-' + name, {key, value}); + if (emitEvent) eventBus.publish("cache-key-set-" + name, { key, value }); return value; }; @@ -21,17 +31,17 @@ export default (name, getObjKey) => { const setAll = (data, emitEvent = true) => { cache = data; - if (emitEvent) eventBus.publish('cache-all-set-' + name, {data}); + if (emitEvent) eventBus.publish("cache-all-set-" + name, { data }); return cache; - } + }; const merge = (data, emitEvent = true) => { - cache = {...cache, ...data} + cache = { ...cache, ...data }; - if (emitEvent) eventBus.publish('cache-merge-' + name, {data}); + if (emitEvent) eventBus.publish("cache-merge-" + name, { data }); return cache; - } + }; const get = async (key, fetchFunc) => { if (cache.hasOwnProperty(key)) return cache[key]; @@ -53,42 +63,43 @@ export default (name, getObjKey) => { const key = getObjKey(value); return set(key, value); - } + }; const getAll = () => cache; - const has = key => cache[key] !== undefined; + const has = (key) => cache[key] !== undefined; const getKeys = () => Object.keys(cache); const forget = (key, emitEvent = true) => { delete cache[key]; - if (emitEvent) eventBus.publish('cache-key-forget-' + name, {key}); + if (emitEvent) eventBus.publish("cache-key-forget-" + name, { key }); return cache; - } + }; const forgetByFilter = (filterFunc, emitEvent = true) => { if (!filterFunc) return false; - Object.keys(cache).filter(key => filterFunc(cache[key])) - .forEach(key => { - delete cache[key] + Object.keys(cache) + .filter((key) => filterFunc(cache[key])) + .forEach((key) => { + delete cache[key]; - if (emitEvent) eventBus.publish('cache-key-forget-' + name, {key}); + if (emitEvent) eventBus.publish("cache-key-forget-" + name, { key }); }); return true; - } + }; const flush = (emitEvent = true) => { cache = {}; - if (emitEvent) eventBus.publish('cache-flush-' + name, {}); + if (emitEvent) eventBus.publish("cache-flush-" + name, {}); return cache; - } + }; return { has, @@ -102,5 +113,5 @@ export default (name, getObjKey) => { forget, forgetByFilter, flush, - } -} + }; +}; diff --git a/src/db/db.js b/src/db/db.js index f0ece19..d8cb351 100644 --- a/src/db/db.js +++ b/src/db/db.js @@ -1,195 +1,279 @@ -import {openDB} from 'idb' -import log from '../utils/logger' -import {isDateObject} from '../utils/js' -import eventBus from '../utils/broadcast-channel-pubsub' +import { openDB } from "idb"; +import log from "../utils/logger"; +import { isDateObject } from "../utils/js"; +import eventBus from "../utils/broadcast-channel-pubsub"; const SSR_DB_VERSION = 12; export let db = null; export default async () => { IDBKeyRange.prototype.toString = function () { - return "IDBKeyRange-" + (isDateObject(this.lower) ? this.lower.getTime() : this.lower) + '-' + (isDateObject(this.upper) ? this.upper : this.upper); - } + return ( + "IDBKeyRange-" + + (isDateObject(this.lower) ? this.lower.getTime() : this.lower) + + "-" + + (isDateObject(this.upper) ? this.upper : this.upper) + ); + }; return await openDatabase(); -} +}; async function openDatabase() { try { - let dbNewVersion = 0, dbOldVersion = 0; + let dbNewVersion = 0, + dbOldVersion = 0; - db = await openDB('ssr', SSR_DB_VERSION, { + db = await openDB("ssr", SSR_DB_VERSION, { async upgrade(db, oldVersion, newVersion, transaction) { - log.info(`Converting database from version ${oldVersion} to version ${newVersion}`); + log.info( + `Converting database from version ${oldVersion} to version ${newVersion}`, + ); dbNewVersion = newVersion; dbOldVersion = oldVersion; switch (true) { case newVersion >= 1 && oldVersion <= 0: - db.createObjectStore('players', { - keyPath: 'id', + db.createObjectStore("players", { + keyPath: "id", autoIncrement: false, }); - const playersHistory = db.createObjectStore('players-history', { - keyPath: '_idbId', + const playersHistory = db.createObjectStore("players-history", { + keyPath: "_idbId", autoIncrement: true, }); - playersHistory.createIndex('players-history-playerId', 'playerId', {unique: false}); - playersHistory.createIndex('players-history-timestamp', 'timestamp', {unique: false}); + playersHistory.createIndex("players-history-playerId", "playerId", { + unique: false, + }); + playersHistory.createIndex( + "players-history-timestamp", + "timestamp", + { unique: false }, + ); - const scoresStore = db.createObjectStore('scores', { - keyPath: 'id', + const scoresStore = db.createObjectStore("scores", { + keyPath: "id", autoIncrement: false, }); - scoresStore.createIndex('scores-leaderboardId', 'leaderboardId', {unique: false}); - scoresStore.createIndex('scores-playerId', 'playerId', {unique: false}); - scoresStore.createIndex('scores-timeset', 'timeset', {unique: false}); - scoresStore.createIndex('scores-pp', 'pp', {unique: false}); + scoresStore.createIndex("scores-leaderboardId", "leaderboardId", { + unique: false, + }); + scoresStore.createIndex("scores-playerId", "playerId", { + unique: false, + }); + scoresStore.createIndex("scores-timeset", "timeset", { + unique: false, + }); + scoresStore.createIndex("scores-pp", "pp", { unique: false }); - db.createObjectStore('rankeds', { - keyPath: 'leaderboardId', + db.createObjectStore("rankeds", { + keyPath: "leaderboardId", autoIncrement: false, }); - const songsStore = db.createObjectStore('songs', { - keyPath: 'hash', + const songsStore = db.createObjectStore("songs", { + keyPath: "hash", autoIncrement: false, }); - songsStore.createIndex('songs-key', 'key', {unique: true}); + songsStore.createIndex("songs-key", "key", { unique: true }); - db.createObjectStore('twitch', { - keyPath: 'playerId', + db.createObjectStore("twitch", { + keyPath: "playerId", autoIncrement: false, }); - const rankedsChangesStore = db.createObjectStore('rankeds-changes', { - keyPath: '_idbId', - autoIncrement: true, - }); - rankedsChangesStore.createIndex('rankeds-changes-timestamp', 'timestamp', {unique: false}); - rankedsChangesStore.createIndex('rankeds-changes-leaderboardId', 'leaderboardId', {unique: false}); + const rankedsChangesStore = db.createObjectStore( + "rankeds-changes", + { + keyPath: "_idbId", + autoIncrement: true, + }, + ); + rankedsChangesStore.createIndex( + "rankeds-changes-timestamp", + "timestamp", + { unique: false }, + ); + rankedsChangesStore.createIndex( + "rankeds-changes-leaderboardId", + "leaderboardId", + { unique: false }, + ); // no autoIncrement, no keyPath - key must be provided - db.createObjectStore('key-value'); + db.createObjectStore("key-value"); - db.createObjectStore('cache'); + db.createObjectStore("cache"); - const groups = db.createObjectStore('groups', {keyPath: '_idbId', autoIncrement: true}); - groups.createIndex('groups-name', 'name', {unique: false}); - groups.createIndex('groups-playerId', 'playerId', {unique: false}); + const groups = db.createObjectStore("groups", { + keyPath: "_idbId", + autoIncrement: true, + }); + groups.createIndex("groups-name", "name", { unique: false }); + groups.createIndex("groups-playerId", "playerId", { + unique: false, + }); - const beatSaviorFiles = db.createObjectStore('beat-savior-files', { - keyPath: 'fileId', + const beatSaviorFiles = db.createObjectStore("beat-savior-files", { + keyPath: "fileId", autoIncrement: false, }); - const beatSavior = db.createObjectStore('beat-savior', { - keyPath: 'beatSaviorId', + const beatSavior = db.createObjectStore("beat-savior", { + keyPath: "beatSaviorId", autoIncrement: false, }); - beatSavior.createIndex('beat-savior-playerId', 'playerId', {unique: false}); - beatSavior.createIndex('beat-savior-songId', 'songId', {unique: false}); - beatSavior.createIndex('beat-savior-fileId', 'fileId', {unique: false}); + beatSavior.createIndex("beat-savior-playerId", "playerId", { + unique: false, + }); + beatSavior.createIndex("beat-savior-songId", "songId", { + unique: false, + }); + beatSavior.createIndex("beat-savior-fileId", "fileId", { + unique: false, + }); - // NO break here! + // NO break here! - case newVersion >=2 && oldVersion <= 1: - db.createObjectStore('beat-savior-players', { - keyPath: 'playerId', + case newVersion >= 2 && oldVersion <= 1: + db.createObjectStore("beat-savior-players", { + keyPath: "playerId", autoIncrement: false, }); - // NO break here! + // NO break here! - case newVersion >= 3 && oldVersion <=2: - db.deleteObjectStore('players'); + case newVersion >= 3 && oldVersion <= 2: + db.deleteObjectStore("players"); - db.createObjectStore('players', { - keyPath: 'playerId', + db.createObjectStore("players", { + keyPath: "playerId", autoIncrement: false, }); - const scoresStore4 = transaction.objectStore('scores'); - scoresStore4.deleteIndex('scores-timeset'); - scoresStore4.createIndex('scores-timeSet', 'timeSet', {unique: false}); - - // NO break here - - case newVersion >= 4 && oldVersion <=3: - db.deleteObjectStore('beat-savior-files'); - - const beatSaviorStore = transaction.objectStore('beat-savior'); - beatSaviorStore.deleteIndex('beat-savior-fileId'); - beatSaviorStore.deleteIndex('beat-savior-songId'); + const scoresStore4 = transaction.objectStore("scores"); + scoresStore4.deleteIndex("scores-timeset"); + scoresStore4.createIndex("scores-timeSet", "timeSet", { + unique: false, + }); // NO break here - case newVersion >= 5 && oldVersion <=4: - const songsBeatMapsStore = db.createObjectStore('songs-beatmaps', { - keyPath: 'hash', - autoIncrement: false, - }); - songsBeatMapsStore.createIndex('songs-beatmaps--key', 'key', {unique: true}); + case newVersion >= 4 && oldVersion <= 3: + db.deleteObjectStore("beat-savior-files"); + + const beatSaviorStore = transaction.objectStore("beat-savior"); + beatSaviorStore.deleteIndex("beat-savior-fileId"); + beatSaviorStore.deleteIndex("beat-savior-songId"); // NO break here - case newVersion >= 6 && oldVersion <=5: - const songsBeatMapsStorev6 = transaction.objectStore('songs-beatmaps'); - songsBeatMapsStorev6.deleteIndex('songs-beatmaps--key'); - songsBeatMapsStorev6.createIndex('songs-beatmaps-key', 'key', {unique: true}); + case newVersion >= 5 && oldVersion <= 4: + const songsBeatMapsStore = db.createObjectStore("songs-beatmaps", { + keyPath: "hash", + autoIncrement: false, + }); + songsBeatMapsStore.createIndex("songs-beatmaps--key", "key", { + unique: true, + }); // NO break here - case newVersion >= 7 && oldVersion <=6: - const scoresUpdateQueue = db.createObjectStore('scores-update-queue', { - keyPath: 'id', - autoIncrement: false, + case newVersion >= 6 && oldVersion <= 5: + const songsBeatMapsStorev6 = + transaction.objectStore("songs-beatmaps"); + songsBeatMapsStorev6.deleteIndex("songs-beatmaps--key"); + songsBeatMapsStorev6.createIndex("songs-beatmaps-key", "key", { + unique: true, }); - scoresUpdateQueue.createIndex('scores-update-queue-fetchedAt', 'fetchedAt', {unique: false}); + + // NO break here + + case newVersion >= 7 && oldVersion <= 6: + const scoresUpdateQueue = db.createObjectStore( + "scores-update-queue", + { + keyPath: "id", + autoIncrement: false, + }, + ); + scoresUpdateQueue.createIndex( + "scores-update-queue-fetchedAt", + "fetchedAt", + { unique: false }, + ); case newVersion >= 8 && oldVersion <= 7: - const beatSaviorStorev8 = transaction.objectStore('beat-savior'); - beatSaviorStorev8.createIndex('beat-savior-hash', 'hash', {unique: false}); + const beatSaviorStorev8 = transaction.objectStore("beat-savior"); + beatSaviorStorev8.createIndex("beat-savior-hash", "hash", { + unique: false, + }); // NO break here case newVersion >= 9 && oldVersion <= 8: - const playersHistoryStorev9 = transaction.objectStore('players-history'); - playersHistoryStorev9.deleteIndex('players-history-timestamp'); - playersHistoryStorev9.createIndex('players-history-playerIdSsTimestamp', 'playerIdSsTimestamp', {unique: true}); + const playersHistoryStorev9 = + transaction.objectStore("players-history"); + playersHistoryStorev9.deleteIndex("players-history-timestamp"); + playersHistoryStorev9.createIndex( + "players-history-playerIdSsTimestamp", + "playerIdSsTimestamp", + { unique: true }, + ); // NO break here case newVersion >= 10 && oldVersion <= 9: - const songsBeatMapsStoreV10 = transaction.objectStore('songs-beatmaps'); - songsBeatMapsStoreV10.deleteIndex('songs-beatmaps-key'); - songsBeatMapsStoreV10.createIndex('songs-beatmaps-key', 'key', {unique: false}); + const songsBeatMapsStoreV10 = + transaction.objectStore("songs-beatmaps"); + songsBeatMapsStoreV10.deleteIndex("songs-beatmaps-key"); + songsBeatMapsStoreV10.createIndex("songs-beatmaps-key", "key", { + unique: false, + }); // NO break here case newVersion >= 11 && oldVersion <= 10: - db.createObjectStore('accsaber-categories', { - keyPath: 'name', + db.createObjectStore("accsaber-categories", { + keyPath: "name", autoIncrement: false, }); - const accSaberPlayersStore = db.createObjectStore('accsaber-players', { - keyPath: 'id', - autoIncrement: false, - }); - accSaberPlayersStore.createIndex('accsaber-players-playerId', 'playerId', {unique: false}); - accSaberPlayersStore.createIndex('accsaber-players-category', 'category', {unique: false}); + const accSaberPlayersStore = db.createObjectStore( + "accsaber-players", + { + keyPath: "id", + autoIncrement: false, + }, + ); + accSaberPlayersStore.createIndex( + "accsaber-players-playerId", + "playerId", + { unique: false }, + ); + accSaberPlayersStore.createIndex( + "accsaber-players-category", + "category", + { unique: false }, + ); // NO break here case newVersion >= 12 && oldVersion <= 11: - const accSaberPlayersHistoryStore = db.createObjectStore('accsaber-players-history', { - keyPath: 'playerIdTimestamp', - autoIncrement: false, - }); - accSaberPlayersHistoryStore.createIndex('accsaber-players-history-playerId', 'playerId', {unique: false}); + const accSaberPlayersHistoryStore = db.createObjectStore( + "accsaber-players-history", + { + keyPath: "playerIdTimestamp", + autoIncrement: false, + }, + ); + accSaberPlayersHistoryStore.createIndex( + "accsaber-players-history-playerId", + "playerId", + { unique: false }, + ); // NO break here } @@ -198,28 +282,33 @@ async function openDatabase() { }, blocked() { - console.warn('DB blocked') + console.warn("DB blocked"); }, blocking() { // other tab tries to open newer db version - close connection - console.warn('DB blocking... will be closed') + console.warn("DB blocking... will be closed"); db.close(); - eventBus.publish('dl-manager-pause-cmd'); + eventBus.publish("dl-manager-pause-cmd"); // TODO: should be reopened with new version: event.newVersion // TODO: or rather notify user / auto reload page }, terminated() { - console.warn('DB terminated'); + console.warn("DB terminated"); - eventBus.publish('dl-manager-pause-cmd'); + eventBus.publish("dl-manager-pause-cmd"); }, }); // Closure code should awaits DB operations ONLY or fail // https://github.com/jakearchibald/idb#user-content-transaction-lifetime - db.runInTransaction = async (objectStores, closure, mode = 'readwrite', options = {durability: 'strict'}) => { + db.runInTransaction = async ( + objectStores, + closure, + mode = "readwrite", + options = { durability: "strict" }, + ) => { try { const tx = db.transaction(objectStores, mode, options); @@ -231,13 +320,12 @@ async function openDatabase() { } catch (e) { throw e; } - } + }; return db; - } - catch(e) { - log.error('Can not open DB.'); + } catch (e) { + log.error("Can not open DB."); throw e; } -} \ No newline at end of file +} diff --git a/src/db/fix-data.js b/src/db/fix-data.js index 51b3c41..d15320a 100644 --- a/src/db/fix-data.js +++ b/src/db/fix-data.js @@ -1,189 +1,231 @@ -import keyValueRepository from './repository/key-value'; -import createBeatMapsService from '../services/beatmaps' -import log from '../utils/logger'; -import {db} from './db' -import {isDateObject} from '../utils/js' -import twitchRepository from './repository/twitch' -import {correctOldSsDate} from '../utils/date' +import keyValueRepository from "./repository/key-value"; +import createBeatMapsService from "../services/beatmaps"; +import log from "../utils/logger"; +import { db } from "./db"; +import { isDateObject } from "../utils/js"; +import twitchRepository from "./repository/twitch"; +import { correctOldSsDate } from "../utils/date"; -const FIXES_KEY = 'data-fix'; +const FIXES_KEY = "data-fix"; const getAppliedFixes = async () => keyValueRepository().get(FIXES_KEY, true); -const setAppliedFixes = async fixes => keyValueRepository().set(fixes, FIXES_KEY); -const addAppliedFix = async fixName => { +const setAppliedFixes = async (fixes) => + keyValueRepository().set(fixes, FIXES_KEY); +const addAppliedFix = async (fixName) => { let allAppliedFixes = await getAppliedFixes(); - allAppliedFixes = allAppliedFixes && Array.isArray(allAppliedFixes) ? allAppliedFixes : []; + allAppliedFixes = + allAppliedFixes && Array.isArray(allAppliedFixes) ? allAppliedFixes : []; allAppliedFixes.push(fixName); await setAppliedFixes(allAppliedFixes); -} +}; const allFixes = { - 'rankeds-20210725': { - apply: async fixName => { - log.info('Apply rankeds refresh fix (20210725)') + "rankeds-20210725": { + apply: async (fixName) => { + log.info("Apply rankeds refresh fix (20210725)"); - return db.runInTransaction(['rankeds-changes', 'rankeds', 'key-value'], async tx => { - await tx.objectStore('rankeds-changes').clear(); - await tx.objectStore('rankeds').clear(); + return db.runInTransaction( + ["rankeds-changes", "rankeds", "key-value"], + async (tx) => { + await tx.objectStore("rankeds-changes").clear(); + await tx.objectStore("rankeds").clear(); - const keyValueStore = tx.objectStore('key-value') + const keyValueStore = tx.objectStore("key-value"); - keyValueStore.delete('rankedsLastUpdated'); + keyValueStore.delete("rankedsLastUpdated"); - let allAppliedFixes = await keyValueStore.get(FIXES_KEY); - allAppliedFixes = allAppliedFixes && Array.isArray(allAppliedFixes) ? allAppliedFixes : []; - allAppliedFixes.push(fixName); - await keyValueStore.put(allAppliedFixes, FIXES_KEY); - }); + let allAppliedFixes = await keyValueStore.get(FIXES_KEY); + allAppliedFixes = + allAppliedFixes && Array.isArray(allAppliedFixes) + ? allAppliedFixes + : []; + allAppliedFixes.push(fixName); + await keyValueStore.put(allAppliedFixes, FIXES_KEY); + }, + ); }, }, - 'beatsaver-20210804': { - apply: async fixName => { - log.info('Converting BeatSaver songs to a new format...', 'DBFix') + "beatsaver-20210804": { + apply: async (fixName) => { + log.info("Converting BeatSaver songs to a new format...", "DBFix"); - return db.runInTransaction(['songs', 'songs-beatmaps', 'key-value'], async tx => { - const songsBeatMapsStore = tx.objectStore('songs-beatmaps'); + return db.runInTransaction( + ["songs", "songs-beatmaps", "key-value"], + async (tx) => { + const songsBeatMapsStore = tx.objectStore("songs-beatmaps"); - let cursor = await tx.objectStore('songs').openCursor(); + let cursor = await tx.objectStore("songs").openCursor(); - let songCount = 0; + let songCount = 0; - const beatmapsService = createBeatMapsService(); + const beatmapsService = createBeatMapsService(); - while (cursor) { - const beatSaverSong = cursor.value; + while (cursor) { + const beatSaverSong = cursor.value; - if (beatSaverSong?.metadata?.characteristics) { - const beatMapsSong = beatmapsService.convertOldBeatSaverToBeatMaps(beatSaverSong); - if (beatMapsSong) { - songsBeatMapsStore.put(beatMapsSong) + if (beatSaverSong?.metadata?.characteristics) { + const beatMapsSong = + beatmapsService.convertOldBeatSaverToBeatMaps(beatSaverSong); + if (beatMapsSong) { + songsBeatMapsStore.put(beatMapsSong); - songCount++; + songCount++; + } else { + log.info( + `Unable to convert, deleting a song`, + "DBFix", + beatSaverSong, + ); + } } else { - log.info(`Unable to convert, deleting a song`, 'DBFix', beatSaverSong); + log.info( + `No metadata characteristics, skipping a song`, + "DBFix", + beatSaverSong, + ); } - } else { - log.info(`No metadata characteristics, skipping a song`, 'DBFix', beatSaverSong); + + cursor = await cursor.continue(); } - cursor = await cursor.continue(); - } + const keyValueStore = tx.objectStore("key-value"); + let allAppliedFixes = await keyValueStore.get(FIXES_KEY); + allAppliedFixes = + allAppliedFixes && Array.isArray(allAppliedFixes) + ? allAppliedFixes + : []; + allAppliedFixes.push(fixName); + await keyValueStore.put(allAppliedFixes, FIXES_KEY); - const keyValueStore = tx.objectStore('key-value') - let allAppliedFixes = await keyValueStore.get(FIXES_KEY); - allAppliedFixes = allAppliedFixes && Array.isArray(allAppliedFixes) ? allAppliedFixes : []; - allAppliedFixes.push(fixName); - await keyValueStore.put(allAppliedFixes, FIXES_KEY); - - log.info(`${songCount} BeatSaver song(s) converted`, 'DBFix') - }); - } + log.info(`${songCount} BeatSaver song(s) converted`, "DBFix"); + }, + ); + }, }, - 'twitch-20210808': { - apply: async fixName => { + "twitch-20210808": { + apply: async (fixName) => { const predefinedProfiles = { - '76561198059659922': 'patian25', - '1994101560659098': 'xoxobluff', - '76561198138327464': 'altrowilddog', - '76561198855288628': 'inbourne', - '76561198136177445': 'riviengt', - '76561199004224834': 'nyaanos', - '76561198023909718': 'danielduel', - '76561198212019365': 'fnyt', - '76561197966674102': 'maciekvr', - '76561198025451538': 'drakonno', - '76561197994110158': 'sanorek', - '76561198034203862': 'vr_agent', - '3702342373170767': 'xjedam', - '76561197995161445': 'mediekore', - '76561198087710981': 'shreddyfreddy', - '76561198999385463': 'woltixo', - '76561198035381239': 'motzel', - '76561198178407566' : 'acetari', - '76561198045386379': 'duhhello', - '76561198835772160': 'tornadoef6', - '76561198187936410': 'garsh_', - '76561198362923485': 'tseska_', - '76561198154190170': 'tieeli', - '76561198333869741': 'cerret07', - '76561197995162898': 'electrostats', - '76561198166289091': 'rocker1904', - '2538637699496776': 'astrella_', - '76561198171842815': 'coolpickb', - '76561198145281261': 'harbgy' - } + "76561198059659922": "patian25", + 1994101560659098: "xoxobluff", + "76561198138327464": "altrowilddog", + "76561198855288628": "inbourne", + "76561198136177445": "riviengt", + "76561199004224834": "nyaanos", + "76561198023909718": "danielduel", + "76561198212019365": "fnyt", + "76561197966674102": "maciekvr", + "76561198025451538": "drakonno", + "76561197994110158": "sanorek", + "76561198034203862": "vr_agent", + 3702342373170767: "xjedam", + "76561197995161445": "mediekore", + "76561198087710981": "shreddyfreddy", + "76561198999385463": "woltixo", + "76561198035381239": "motzel", + "76561198178407566": "acetari", + "76561198045386379": "duhhello", + 76561198835772160: "tornadoef6", + "76561198187936410": "garsh_", + "76561198362923485": "tseska_", + "76561198154190170": "tieeli", + "76561198333869741": "cerret07", + "76561197995162898": "electrostats", + "76561198166289091": "rocker1904", + 2538637699496776: "astrella_", + "76561198171842815": "coolpickb", + "76561198145281261": "harbgy", + }; - log.info('Adding predefined Twitch profiles...', 'DBFix') + log.info("Adding predefined Twitch profiles...", "DBFix"); - const updatePlayerTwitchProfile = async (twitchProfile) => twitchRepository().set(twitchProfile); + const updatePlayerTwitchProfile = async (twitchProfile) => + twitchRepository().set(twitchProfile); - await Promise.all(Object.entries(predefinedProfiles).map(async ([playerId, twitchLogin]) => updatePlayerTwitchProfile( - { - lastUpdated: null, - login: twitchLogin, - playerId - } - ))) + await Promise.all( + Object.entries(predefinedProfiles).map( + async ([playerId, twitchLogin]) => + updatePlayerTwitchProfile({ + lastUpdated: null, + login: twitchLogin, + playerId, + }), + ), + ); await addAppliedFix(fixName); - log.info('Twitch profiles added.', 'DBFix') - } + log.info("Twitch profiles added.", "DBFix"); + }, }, - 'player-history-20211022': { - apply: async fixName => { - log.info('Apply player ss history fix (20211022)') + "player-history-20211022": { + apply: async (fixName) => { + log.info("Apply player ss history fix (20211022)"); - return db.runInTransaction(['players-history', 'key-value'], async tx => { - const playersHistoryStore = tx.objectStore('players-history'); + return db.runInTransaction( + ["players-history", "key-value"], + async (tx) => { + const playersHistoryStore = tx.objectStore("players-history"); - let cursor = await playersHistoryStore.openCursor(); + let cursor = await playersHistoryStore.openCursor(); - while (cursor) { - const history = cursor.value; + while (cursor) { + const history = cursor.value; + + if (!history?.playerId || !isDateObject(history?.ssDate)) { + await cursor.delete(); + cursor = await cursor.continue(); + + continue; + } + + const playerId = history.playerId; + const ssDate = correctOldSsDate(history.ssDate); + const playerIdSsTimestamp = `${playerId}_${ssDate.getTime()}`; - if (!history?.playerId || !isDateObject(history?.ssDate)) { await cursor.delete(); - cursor = await cursor.continue(); + playersHistoryStore.put({ + ...history, + ssDate, + playerIdSsTimestamp, + }); - continue; + cursor = await cursor.continue(); } - const playerId = history.playerId; - const ssDate = correctOldSsDate(history.ssDate); - const playerIdSsTimestamp = `${playerId}_${ssDate.getTime()}`; - - await cursor.delete(); - playersHistoryStore.put({...history, ssDate, playerIdSsTimestamp}); - - cursor = await cursor.continue(); - } - - const keyValueStore = tx.objectStore('key-value') - let allAppliedFixes = await keyValueStore.get(FIXES_KEY); - allAppliedFixes = allAppliedFixes && Array.isArray(allAppliedFixes) ? allAppliedFixes : []; - allAppliedFixes.push(fixName); - await keyValueStore.put(allAppliedFixes, FIXES_KEY); - }); + const keyValueStore = tx.objectStore("key-value"); + let allAppliedFixes = await keyValueStore.get(FIXES_KEY); + allAppliedFixes = + allAppliedFixes && Array.isArray(allAppliedFixes) + ? allAppliedFixes + : []; + allAppliedFixes.push(fixName); + await keyValueStore.put(allAppliedFixes, FIXES_KEY); + }, + ); }, }, }; export default async () => { let appliedDbFixes = await getAppliedFixes(); - const appliedFixes = appliedDbFixes && Array.isArray(appliedDbFixes) ? appliedDbFixes : []; - const neededFixes = Object.keys(allFixes).filter(f => !appliedFixes.includes(f) && (!allFixes[f].validTo || allFixes[f].validTo > new Date())); + const appliedFixes = + appliedDbFixes && Array.isArray(appliedDbFixes) ? appliedDbFixes : []; + const neededFixes = Object.keys(allFixes).filter( + (f) => + !appliedFixes.includes(f) && + (!allFixes[f].validTo || allFixes[f].validTo > new Date()), + ); if (!neededFixes.length) return; - document.body.innerHTML = '

Database conversion. Please wait...

'; + document.body.innerHTML = "

Database conversion. Please wait...

"; for (let key of neededFixes) { await allFixes[key].apply(key); } - document.body.innerHTML = ''; -} \ No newline at end of file + document.body.innerHTML = ""; +}; diff --git a/src/db/repositories-init.js b/src/db/repositories-init.js index a1845e0..272bb0c 100644 --- a/src/db/repositories-init.js +++ b/src/db/repositories-init.js @@ -1,19 +1,29 @@ -import cacheRepository from './repository/cache'; -import groupsRepository from './repository/groups'; -import keyValueRepository from './repository/key-value'; -import playersRepository from './repository/players'; -import playersHistoryRepository from './repository/players-history'; -import rankedsRepository from './repository/rankeds'; -import rankedsChangesRepository from './repository/rankeds-changes'; -import scoresRepository from './repository/scores'; -import songsRepository from './repository/songs'; -import twitchRepository from './repository/twitch'; -import log from '../utils/logger'; - +import cacheRepository from "./repository/cache"; +import groupsRepository from "./repository/groups"; +import keyValueRepository from "./repository/key-value"; +import playersRepository from "./repository/players"; +import playersHistoryRepository from "./repository/players-history"; +import rankedsRepository from "./repository/rankeds"; +import rankedsChangesRepository from "./repository/rankeds-changes"; +import scoresRepository from "./repository/scores"; +import songsRepository from "./repository/songs"; +import twitchRepository from "./repository/twitch"; +import log from "../utils/logger"; export default () => { - log.debug('Initialize DB repositories'); + log.debug("Initialize DB repositories"); // initialize all repositories in order to create cache to sync - [cacheRepository, groupsRepository, keyValueRepository, playersRepository, playersHistoryRepository, rankedsRepository, rankedsChangesRepository, scoresRepository, songsRepository, twitchRepository].map(repository => repository()); -} \ No newline at end of file + [ + cacheRepository, + groupsRepository, + keyValueRepository, + playersRepository, + playersHistoryRepository, + rankedsRepository, + rankedsChangesRepository, + scoresRepository, + songsRepository, + twitchRepository, + ].map((repository) => repository()); +}; diff --git a/src/db/repository/accsaber-categories.js b/src/db/repository/accsaber-categories.js index c82a759..6ef3ffb 100644 --- a/src/db/repository/accsaber-categories.js +++ b/src/db/repository/accsaber-categories.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('accsaber-categories', 'name'); \ No newline at end of file +export default () => createRepository("accsaber-categories", "name"); diff --git a/src/db/repository/accsaber-players-history.js b/src/db/repository/accsaber-players-history.js index 388ee7c..9fb0225 100644 --- a/src/db/repository/accsaber-players-history.js +++ b/src/db/repository/accsaber-players-history.js @@ -1,6 +1,7 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('accsaber-players-history', 'playerIdTimestamp', { - 'accsaber-players-history-playerId': 'playerId', - 'accsaber-players-history-playerIdTimestamp': 'playerIdTimestamp' -}); \ No newline at end of file +export default () => + createRepository("accsaber-players-history", "playerIdTimestamp", { + "accsaber-players-history-playerId": "playerId", + "accsaber-players-history-playerIdTimestamp": "playerIdTimestamp", + }); diff --git a/src/db/repository/accsaber-players.js b/src/db/repository/accsaber-players.js index aeddc98..b0b580a 100644 --- a/src/db/repository/accsaber-players.js +++ b/src/db/repository/accsaber-players.js @@ -1,10 +1,7 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository( - 'accsaber-players', - 'id', - { - 'accsaber-players-playerId': 'playerId', - 'accsaber-players-category': 'category', - }, -); \ No newline at end of file +export default () => + createRepository("accsaber-players", "id", { + "accsaber-players-playerId": "playerId", + "accsaber-players-category": "category", + }); diff --git a/src/db/repository/beat-savior-files.js b/src/db/repository/beat-savior-files.js index 5ca6c53..b98707b 100644 --- a/src/db/repository/beat-savior-files.js +++ b/src/db/repository/beat-savior-files.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('beat-savior-files', 'fileId'); \ No newline at end of file +export default () => createRepository("beat-savior-files", "fileId"); diff --git a/src/db/repository/beat-savior-players.js b/src/db/repository/beat-savior-players.js index df41cce..ff520bd 100644 --- a/src/db/repository/beat-savior-players.js +++ b/src/db/repository/beat-savior-players.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('beat-savior-players', 'playerId'); \ No newline at end of file +export default () => createRepository("beat-savior-players", "playerId"); diff --git a/src/db/repository/beat-savior.js b/src/db/repository/beat-savior.js index f765934..d4f14af 100644 --- a/src/db/repository/beat-savior.js +++ b/src/db/repository/beat-savior.js @@ -1,6 +1,7 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('beat-savior', 'beatSaviorId', { - 'beat-savior-playerId': 'playerId', - 'beat-savior-hash': 'hash', -}); \ No newline at end of file +export default () => + createRepository("beat-savior", "beatSaviorId", { + "beat-savior-playerId": "playerId", + "beat-savior-hash": "hash", + }); diff --git a/src/db/repository/cache.js b/src/db/repository/cache.js index 96f8e2c..6cf12ca 100644 --- a/src/db/repository/cache.js +++ b/src/db/repository/cache.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('cache'); \ No newline at end of file +export default () => createRepository("cache"); diff --git a/src/db/repository/generic.js b/src/db/repository/generic.js index efe276a..c3c1067 100644 --- a/src/db/repository/generic.js +++ b/src/db/repository/generic.js @@ -1,11 +1,11 @@ -import cache from '../cache'; -import {db} from '../db'; -import {convertArrayToObjectByKey} from '../../utils/js' -import makePendingPromisePool from '../../utils/pending-promises' -import eventBus from '../../utils/broadcast-channel-pubsub' +import cache from "../cache"; +import { db } from "../db"; +import { convertArrayToObjectByKey } from "../../utils/js"; +import makePendingPromisePool from "../../utils/pending-promises"; +import eventBus from "../../utils/broadcast-channel-pubsub"; -export const ALL_KEY = '__ALL'; -const NONE_KEY = '__NONE'; +export const ALL_KEY = "__ALL"; +const NONE_KEY = "__NONE"; let repositories = {}; @@ -20,46 +20,52 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { const getKeyName = () => inlineKeyName; const hasOutOfLineKey = () => getKeyName() === undefined; const getObjKey = (obj, outOfLineKey = undefined) => { - const key = hasOutOfLineKey() ? outOfLineKey : obj[inlineKeyName] + const key = hasOutOfLineKey() ? outOfLineKey : obj[inlineKeyName]; return key ? key : outOfLineKey; - } + }; let repositoryCache = cache(repositoryName, getObjKey); - const getCacheKeyFor = (query, indexName) => (indexName ? indexName : ALL_KEY) + '-' + (query ? query : NONE_KEY); + const getCacheKeyFor = (query, indexName) => + (indexName ? indexName : ALL_KEY) + "-" + (query ? query : NONE_KEY); - const getFieldForIndexName = indexName => indexesKeyNames[indexName]; - const isFieldForIndexDefined = indexName => !!getFieldForIndexName(indexName); + const getFieldForIndexName = (indexName) => indexesKeyNames[indexName]; + const isFieldForIndexDefined = (indexName) => + !!getFieldForIndexName(indexName); - const setDataAvailabilityStatus = cacheKey => dataAvailableFor[cacheKey] = true; - const setAllDataAvailabilityStatus = () => setDataAvailabilityStatus(getCacheKeyFor()); - const removeDataAvailabilityStatus = cacheKey => { + const setDataAvailabilityStatus = (cacheKey) => + (dataAvailableFor[cacheKey] = true); + const setAllDataAvailabilityStatus = () => + setDataAvailabilityStatus(getCacheKeyFor()); + const removeDataAvailabilityStatus = (cacheKey) => { delete dataAvailableFor[cacheKey]; delete dataAvailableFor[getCacheKeyFor()]; - } - const flushDataAvailabilityStatus = () => dataAvailableFor = {}; - const isIndexDataAvailable = cacheKey => !!dataAvailableFor[cacheKey]; + }; + const flushDataAvailabilityStatus = () => (dataAvailableFor = {}); + const isIndexDataAvailable = (cacheKey) => !!dataAvailableFor[cacheKey]; const isAllDataAvailable = () => isIndexDataAvailable(getCacheKeyFor()); const flushCache = () => { repositoryCache.flush(); flushDataAvailabilityStatus(); - } + }; - const forgetCacheKey = key => repositoryCache.forget(key); + const forgetCacheKey = (key) => repositoryCache.forget(key); - const forgetObject = async obj => { - if (hasOutOfLineKey()) throw 'forgetObject function is not available in repositories with out-of-line keys'; + const forgetObject = async (obj) => { + if (hasOutOfLineKey()) + throw "forgetObject function is not available in repositories with out-of-line keys"; const key = getObjKey(obj); - if (!key) throw `Object does not contain ${inlineKeyName} field which is repository key`; + if (!key) + throw `Object does not contain ${inlineKeyName} field which is repository key`; forgetCacheKey(key); - } + }; const getStoreName = () => storeName; - const getCachedKeys = _ => repositoryCache.getKeys(); + const getCachedKeys = (_) => repositoryCache.getKeys(); const getAllKeys = async () => db.getAllKeys(storeName); @@ -68,16 +74,23 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { const cacheKey = getCacheKeyFor(key); - return repositoryCache.get(key, () => resolvePromiseOrWaitForPending(cacheKey, () => db.get(storeName, key))); + return repositoryCache.get(key, () => + resolvePromiseOrWaitForPending(cacheKey, () => db.get(storeName, key)), + ); }; const getFromIndex = async (indexName, query, refreshCache = false) => { - if (hasOutOfLineKey()) throw `getFromIndex() is not available for stores with out-of-line key`; - if (!isFieldForIndexDefined(indexName)) throw `Index ${indexName} has no field set`; + if (hasOutOfLineKey()) + throw `getFromIndex() is not available for stores with out-of-line key`; + if (!isFieldForIndexDefined(indexName)) + throw `Index ${indexName} has no field set`; - const cacheKey = getCacheKeyFor(query, indexName + '-single'); + const cacheKey = getCacheKeyFor(query, indexName + "-single"); - const getFromDb = () => resolvePromiseOrWaitForPending(cacheKey, () => db.getFromIndex(storeName, indexName, query)); + const getFromDb = () => + resolvePromiseOrWaitForPending(cacheKey, () => + db.getFromIndex(storeName, indexName, query), + ); if (query && query instanceof IDBKeyRange) return getFromDb(); @@ -85,7 +98,8 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { const fullIndexCacheKey = getCacheKeyFor(query, indexName); - const filterItems = item => item !== undefined && (!query || item[field] === query); + const filterItems = (item) => + item !== undefined && (!query || item[field] === query); if (refreshCache) { removeDataAvailabilityStatus(cacheKey); @@ -94,24 +108,34 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { repositoryCache.forgetByFilter(filterItems); } - return repositoryCache.getByFilter(getFromDb, isAllDataAvailable() || isIndexDataAvailable(cacheKey) || isIndexDataAvailable(fullIndexCacheKey) ? filterItems : null); + return repositoryCache.getByFilter( + getFromDb, + isAllDataAvailable() || + isIndexDataAvailable(cacheKey) || + isIndexDataAvailable(fullIndexCacheKey) + ? filterItems + : null, + ); }; - const getAll = async(refreshCache = false) => { + const getAll = async (refreshCache = false) => { const cacheKey = getCacheKeyFor(); - const getFromDb = () => resolvePromiseOrWaitForPending(cacheKey, () => db.getAll(storeName)) + const getFromDb = () => + resolvePromiseOrWaitForPending(cacheKey, () => db.getAll(storeName)); if (hasOutOfLineKey()) return getFromDb(); if (refreshCache) flushCache(); - const filterUndefined = item => item !== undefined; + const filterUndefined = (item) => item !== undefined; if (!isAllDataAvailable()) { const data = convertArrayToObjectByKey(await getFromDb(), inlineKeyName); - const ret = Object.values(repositoryCache.setAll(data)).filter(filterUndefined); + const ret = Object.values(repositoryCache.setAll(data)).filter( + filterUndefined, + ); setAllDataAvailabilityStatus(); @@ -119,92 +143,111 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { } return Object.values(repositoryCache.getAll()).filter(filterUndefined); - } + }; - const getAllFromIndex = async(indexName, query = undefined, refreshCache = false) => { - if (hasOutOfLineKey()) throw `getAllFromIndex() is not available for stores with out-of-line key`; - if (!isFieldForIndexDefined(indexName)) throw `Index ${indexName} has no field set`; + const getAllFromIndex = async ( + indexName, + query = undefined, + refreshCache = false, + ) => { + if (hasOutOfLineKey()) + throw `getAllFromIndex() is not available for stores with out-of-line key`; + if (!isFieldForIndexDefined(indexName)) + throw `Index ${indexName} has no field set`; const cacheKey = getCacheKeyFor(query, indexName); - const getFromDb = async () => resolvePromiseOrWaitForPending(cacheKey, () => db.getAllFromIndex(storeName, indexName, query)); + const getFromDb = async () => + resolvePromiseOrWaitForPending(cacheKey, () => + db.getAllFromIndex(storeName, indexName, query), + ); if (query && query instanceof IDBKeyRange) return getFromDb(); const field = getFieldForIndexName(indexName); - const filterItems = item => item !== undefined && (!query || item[field] === query); + const filterItems = (item) => + item !== undefined && (!query || item[field] === query); if (refreshCache) { removeDataAvailabilityStatus(cacheKey); repositoryCache.forgetByFilter(filterItems); } - const getFromDbAndUpdateCache = async () => resolvePromiseOrWaitForPending(`${cacheKey}-updateDb`, async () => { - const data = await getFromDb(); + const getFromDbAndUpdateCache = async () => + resolvePromiseOrWaitForPending(`${cacheKey}-updateDb`, async () => { + const data = await getFromDb(); - repositoryCache.merge(convertArrayToObjectByKey(data, inlineKeyName)); + repositoryCache.merge(convertArrayToObjectByKey(data, inlineKeyName)); - setDataAvailabilityStatus(cacheKey); + setDataAvailabilityStatus(cacheKey); - return data; - }) + return data; + }); - if (!isAllDataAvailable() && !isIndexDataAvailable(cacheKey)) return await getFromDbAndUpdateCache(); + if (!isAllDataAvailable() && !isIndexDataAvailable(cacheKey)) + return await getFromDbAndUpdateCache(); return Object.values(repositoryCache.getAll()).filter(filterItems); - } + }; const set = async (value, key = undefined, tx = null) => { const txStores = tx ? [...tx.objectStoreNames] : null; let putKey; if (tx && txStores.includes(storeName)) { - putKey = await tx.objectStore(storeName).put(value, inlineKeyName ? undefined : key); + putKey = await tx + .objectStore(storeName) + .put(value, inlineKeyName ? undefined : key); } else { - putKey = await db.put(storeName, value, inlineKeyName ? undefined : key) + putKey = await db.put(storeName, value, inlineKeyName ? undefined : key); } if (!hasOutOfLineKey() && !getObjKey(value)) value[inlineKeyName] = putKey; return repositoryCache.set(getObjKey(value, key), value); - } + }; - const del = async key => { + const del = async (key) => { await db.delete(storeName, key); return repositoryCache.forget(key); - } + }; - const deleteObject = async obj => { - if (hasOutOfLineKey()) throw 'deleteObject function is not available in repositories with out-of-line keys'; + const deleteObject = async (obj) => { + if (hasOutOfLineKey()) + throw "deleteObject function is not available in repositories with out-of-line keys"; const key = getObjKey(obj); - if (!key) throw `Object does not contain ${inlineKeyName} field which is repository key`; + if (!key) + throw `Object does not contain ${inlineKeyName} field which is repository key`; return del(key); - } + }; - const openCursor = async (mode = 'readonly') => db.transaction(storeName, mode).store.openCursor(); + const openCursor = async (mode = "readonly") => + db.transaction(storeName, mode).store.openCursor(); const setCache = (value, key) => { if (hasOutOfLineKey()) { - if (!key) throw `setCache() needs a key for stores (${storeName}) with out-of-line keys`; + if (!key) + throw `setCache() needs a key for stores (${storeName}) with out-of-line keys`; } else { key = getObjKey(value, key); } repositoryCache.set(key, value); - } - const addToCache = data => { - if (hasOutOfLineKey()) throw `addToCache() is not available for stores (${storeName}) with out-of-line key`; + }; + const addToCache = (data) => { + if (hasOutOfLineKey()) + throw `addToCache() is not available for stores (${storeName}) with out-of-line key`; repositoryCache.merge(convertArrayToObjectByKey(data, inlineKeyName)); - } + }; const getCache = () => repositoryCache; - return repositories[repositoryName] = { + return (repositories[repositoryName] = { getStoreName, hasOutOfLineKey, getAllKeys, @@ -224,5 +267,5 @@ export default (storeName, inlineKeyName = undefined, indexesKeyNames = {}) => { setCache, addToCache, getCache, - }; + }); }; diff --git a/src/db/repository/groups.js b/src/db/repository/groups.js index c01c7ea..9b0ca93 100644 --- a/src/db/repository/groups.js +++ b/src/db/repository/groups.js @@ -1,5 +1,11 @@ -import createRepository from './generic'; +import createRepository from "./generic"; let repository; -export default () => repository ? repository : repository = createRepository('groups', '_idbId', {'groups-name': 'name', 'groups-playerId': 'playerId'}); \ No newline at end of file +export default () => + repository + ? repository + : (repository = createRepository("groups", "_idbId", { + "groups-name": "name", + "groups-playerId": "playerId", + })); diff --git a/src/db/repository/key-value.js b/src/db/repository/key-value.js index b129d4b..91861cf 100644 --- a/src/db/repository/key-value.js +++ b/src/db/repository/key-value.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('key-value'); \ No newline at end of file +export default () => createRepository("key-value"); diff --git a/src/db/repository/players-history.js b/src/db/repository/players-history.js index 6d1a152..8b5fc3a 100644 --- a/src/db/repository/players-history.js +++ b/src/db/repository/players-history.js @@ -1,6 +1,7 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('players-history', '_idbId', { - 'players-history-playerId': 'playerId', - 'players-history-playerIdSsTimestamp': 'playerIdSsTimestamp' -}); \ No newline at end of file +export default () => + createRepository("players-history", "_idbId", { + "players-history-playerId": "playerId", + "players-history-playerIdSsTimestamp": "playerIdSsTimestamp", + }); diff --git a/src/db/repository/players.js b/src/db/repository/players.js index da418f7..94175e7 100644 --- a/src/db/repository/players.js +++ b/src/db/repository/players.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('players', 'playerId'); \ No newline at end of file +export default () => createRepository("players", "playerId"); diff --git a/src/db/repository/rankeds-changes.js b/src/db/repository/rankeds-changes.js index cae9b96..5d755c5 100644 --- a/src/db/repository/rankeds-changes.js +++ b/src/db/repository/rankeds-changes.js @@ -1,3 +1,7 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('rankeds-changes', '_idbId', {'rankeds-changes-timestamp': 'timestamp', 'rankeds-changes-leaderboardId': 'leaderboardId'}); \ No newline at end of file +export default () => + createRepository("rankeds-changes", "_idbId", { + "rankeds-changes-timestamp": "timestamp", + "rankeds-changes-leaderboardId": "leaderboardId", + }); diff --git a/src/db/repository/rankeds.js b/src/db/repository/rankeds.js index b5cbba7..92806f7 100644 --- a/src/db/repository/rankeds.js +++ b/src/db/repository/rankeds.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('rankeds', 'leaderboardId'); \ No newline at end of file +export default () => createRepository("rankeds", "leaderboardId"); diff --git a/src/db/repository/scores-update-queue.js b/src/db/repository/scores-update-queue.js index a33794c..a7ec833 100644 --- a/src/db/repository/scores-update-queue.js +++ b/src/db/repository/scores-update-queue.js @@ -1,9 +1,6 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository( - 'scores-update-queue', - 'id', - { - 'scores-update-queue-fetchedAt': 'fetchedAt', - }, - ) \ No newline at end of file +export default () => + createRepository("scores-update-queue", "id", { + "scores-update-queue-fetchedAt": "fetchedAt", + }); diff --git a/src/db/repository/scores.js b/src/db/repository/scores.js index 1a1c83d..68f4a9c 100644 --- a/src/db/repository/scores.js +++ b/src/db/repository/scores.js @@ -1,12 +1,9 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository( - 'scores', - 'id', - { - 'scores-timeset': 'timeset', - 'scores-leaderboardId': 'leaderboardId', - 'scores-playerId': 'playerId', - 'scores-pp': 'pp', - }, - ) \ No newline at end of file +export default () => + createRepository("scores", "id", { + "scores-timeset": "timeset", + "scores-leaderboardId": "leaderboardId", + "scores-playerId": "playerId", + "scores-pp": "pp", + }); diff --git a/src/db/repository/songs-beatmaps.js b/src/db/repository/songs-beatmaps.js index 75fad2b..17cc4cc 100644 --- a/src/db/repository/songs-beatmaps.js +++ b/src/db/repository/songs-beatmaps.js @@ -1,3 +1,4 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('songs-beatmaps', 'hash', {'songs-beatmaps-key': 'key'}); \ No newline at end of file +export default () => + createRepository("songs-beatmaps", "hash", { "songs-beatmaps-key": "key" }); diff --git a/src/db/repository/songs.js b/src/db/repository/songs.js index 0e8b9f0..47b5656 100644 --- a/src/db/repository/songs.js +++ b/src/db/repository/songs.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('songs', 'hash', {'songs-key': 'key'}); \ No newline at end of file +export default () => createRepository("songs", "hash", { "songs-key": "key" }); diff --git a/src/db/repository/twitch.js b/src/db/repository/twitch.js index 9d98845..9b63dcb 100644 --- a/src/db/repository/twitch.js +++ b/src/db/repository/twitch.js @@ -1,3 +1,3 @@ -import createRepository from './generic'; +import createRepository from "./generic"; -export default () => createRepository('twitch', 'playerId'); \ No newline at end of file +export default () => createRepository("twitch", "playerId"); diff --git a/src/main.js b/src/main.js index 110932e..7e1d6e7 100644 --- a/src/main.js +++ b/src/main.js @@ -1,35 +1,35 @@ -import App from './App.svelte'; -import log from './utils/logger' -import initDb from './db/db' -import initializeRepositories from './db/repositories-init'; -import setupDataFixes from './db/fix-data' -import createConfigStore from './stores/config' -import createPlayerService from './services/scoresaber/player' -import createBeatSaviorService from './services/beatsavior' -import createRankedsStore from './stores/scoresaber/rankeds' -import initDownloadManager from './network/download-manager' -import initCommandProcessor from './network/command-processor' -import {enablePatches, setAutoFreeze} from 'immer' -import {initCompareEnhancer} from './stores/http/enhancers/scores/compare' -import ErrorComponent from './components/Common/Error.svelte' -import initializeWorkers from './utils/worker-wrappers' +import App from "./App.svelte"; +import log from "./utils/logger"; +import initDb from "./db/db"; +import initializeRepositories from "./db/repositories-init"; +import setupDataFixes from "./db/fix-data"; +import createConfigStore from "./stores/config"; +import createPlayerService from "./services/scoresaber/player"; +import createBeatSaviorService from "./services/beatsavior"; +import createRankedsStore from "./stores/scoresaber/rankeds"; +import initDownloadManager from "./network/download-manager"; +import initCommandProcessor from "./network/command-processor"; +import { enablePatches, setAutoFreeze } from "immer"; +import { initCompareEnhancer } from "./stores/http/enhancers/scores/compare"; +import ErrorComponent from "./components/Common/Error.svelte"; +import initializeWorkers from "./utils/worker-wrappers"; let app = null; -(async() => { +(async () => { try { // TODO: remove level setting // log.setLevel(log.TRACE); // log.logOnly(['AccSaberService']); - log.info('Starting up...', 'Main') + log.info("Starting up...", "Main"); await initDb(); await initializeRepositories(); await setupDataFixes(); // WORKAROUND for immer.js esm (see https://github.com/immerjs/immer/issues/557) - window.process = {env: {NODE_ENV: "production"}}; + window.process = { env: { NODE_ENV: "production" } }; // setup immer.js enablePatches(); @@ -47,24 +47,29 @@ let app = null; initCommandProcessor(await initDownloadManager()); - log.info('Site initialized', 'Main') + log.info("Site initialized", "Main"); app = new App({ target: document.body, props: {}, }); - } catch(error) { + } catch (error) { console.error(error); - if (error instanceof DOMException && error.toString() === 'InvalidStateError: A mutation operation was attempted on a database that did not allow mutations.') - error = new Error('Firefox in private mode does not support the database. Please run the site in normal mode.') + if ( + error instanceof DOMException && + error.toString() === + "InvalidStateError: A mutation operation was attempted on a database that did not allow mutations." + ) + error = new Error( + "Firefox in private mode does not support the database. Please run the site in normal mode.", + ); app = new ErrorComponent({ target: document.body, - props: {error, withTrace: true}, + props: { error, withTrace: true }, }); } })(); - -export default app; \ No newline at end of file +export default app; diff --git a/src/network/cache.js b/src/network/cache.js index f82a863..5b98d44 100644 --- a/src/network/cache.js +++ b/src/network/cache.js @@ -1,5 +1,5 @@ // import eventBus from '../utils/broadcast-channel-pubsub' -import {addToDate, MINUTE} from '../utils/date' +import { addToDate, MINUTE } from "../utils/date"; const DEFAULT_CACHE_SIZE = 100; @@ -7,20 +7,25 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { let cache = {}; let cacheSize = size; - const isWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope + const isWorker = + typeof WorkerGlobalScope !== "undefined" && + self instanceof WorkerGlobalScope; const defaultExpiryIn = expiryIn; - const packValue = value => { - if (!value || typeof value !== 'object') return value; + const packValue = (value) => { + if (!value || typeof value !== "object") return value; - const newValue = {...value}; + const newValue = { ...value }; if (value.headers && value.headers instanceof Headers) { - newValue.headers = [...value.headers.entries()].reduce((cum, [key, value]) => { - cum[key] = value; - return cum; - }, {}) + newValue.headers = [...value.headers.entries()].reduce( + (cum, [key, value]) => { + cum[key] = value; + return cum; + }, + {}, + ); } if (value.body && value.body instanceof Document) { @@ -28,25 +33,29 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { } return newValue; - } + }; - const unpackValue = value => { - if (!value || typeof value !== 'object') return value; + const unpackValue = (value) => { + if (!value || typeof value !== "object") return value; - const newValue = {...value}; + const newValue = { ...value }; if (value.headers) { const headers = new Headers(); - Object.keys(value.headers).map(k => headers.append(k, value.headers[k])); + Object.keys(value.headers).map((k) => + headers.append(k, value.headers[k]), + ); newValue.headers = headers; } if (value.body) { - newValue.body = !isWorker ? new DOMParser().parseFromString(value.body, 'text/html') : value.body; + newValue.body = !isWorker + ? new DOMParser().parseFromString(value.body, "text/html") + : value.body; } return newValue; - } + }; // update data cached on another node // const setUnsubscribe = eventBus.on('net-cache-key-set', ({key, value, expiryIn}, isLocal) => !isLocal ? set(key, unpackValue(value), expiryIn, false) : null); @@ -54,14 +63,25 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { // const flushUnsubscribe = eventBus.on('net-cache-flush', (_, isLocal) => !isLocal ? flush(false) : null); const has = (key, maxAge = null, withExpired = false) => - cache.hasOwnProperty(key) && cache[key] && - (withExpired || !cache[key].expiryAt || cache[key].expiryAt >= new Date()) && - (!Number.isFinite(maxAge) || !cache[key].cachedAt || addToDate(maxAge, cache[key].cachedAt) >= new Date()); + cache.hasOwnProperty(key) && + cache[key] && + (withExpired || + !cache[key].expiryAt || + cache[key].expiryAt >= new Date()) && + (!Number.isFinite(maxAge) || + !cache[key].cachedAt || + addToDate(maxAge, cache[key].cachedAt) >= new Date()); const set = (key, value, expiryIn = null, emitEvent = true) => { expiryIn = expiryIn ? expiryIn : defaultExpiryIn; - cache[key] = {key, cachedAt: new Date(), expiryIn, expiryAt: addToDate(expiryIn, new Date()), value}; + cache[key] = { + key, + cachedAt: new Date(), + expiryIn, + expiryAt: addToDate(expiryIn, new Date()), + value, + }; // if (emitEvent) eventBus.publish('net-cache-key-set', {key, value: packValue(value), expiryIn}); @@ -70,7 +90,12 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { return value; }; - const get = (key, maxAge = null, withExpired = false, valueOnly = true) => has(key, maxAge, withExpired) ? (valueOnly ? cache[key].value : cache[key]) : undefined; + const get = (key, maxAge = null, withExpired = false, valueOnly = true) => + has(key, maxAge, withExpired) + ? valueOnly + ? cache[key].value + : cache[key] + : undefined; const getAll = () => cache; @@ -82,7 +107,7 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { // if (emitEvent) eventBus.publish('net-cache-key-forget', {key}); return cache; - } + }; const flush = (emitEvent = true) => { cache = {}; @@ -90,23 +115,26 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { // if (emitEvent) eventBus.publish('net-cache-flush', {}); return cache; - } + }; const garbageCollect = (size = cacheSize) => { const values = Object.values(cache); if (values.length < size) return; cache = values - .sort((a,b) => b.expiryAt - a.expiryAt) + .sort((a, b) => b.expiryAt - a.expiryAt) .slice(0, size) - .reduce((cum, item) => {cum[item.key] = item; return cum;}, {}); - } + .reduce((cum, item) => { + cum[item.key] = item; + return cum; + }, {}); + }; const destroy = () => { // setUnsubscribe(); // forgetUnsubscribe(); // flushUnsubscribe(); - } + }; return { has, @@ -117,5 +145,5 @@ export default (size = DEFAULT_CACHE_SIZE, expiryIn = MINUTE) => { forget, flush, destroy, - } -} + }; +}; diff --git a/src/network/clients/accsaber/api-categories.js b/src/network/clients/accsaber/api-categories.js index 2f786cd..bff4fd5 100644 --- a/src/network/clients/accsaber/api-categories.js +++ b/src/network/clients/accsaber/api-categories.js @@ -1,19 +1,22 @@ -import queue from '../../queues/queues' -import createClient from '../generic' +import queue from "../../queues/queues"; +import createClient from "../generic"; -const process = response => { +const process = (response) => { if (!response || !Array.isArray(response)) return []; - return response.map(c => ({ + return response.map((c) => ({ name: c.categoryName, displayName: c.categoryDisplayName, countsTowardsOverall: c.countsTowardsOverall, - description: c.description + description: c.description, })); -} +}; -const get = async ({priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.ACCSABER.categories(priority, queueOptions); +const get = async ({ + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.ACCSABER.categories(priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/accsaber/api-leaderboard.js b/src/network/clients/accsaber/api-leaderboard.js index e70c884..45c8896 100644 --- a/src/network/clients/accsaber/api-leaderboard.js +++ b/src/network/clients/accsaber/api-leaderboard.js @@ -1,10 +1,16 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import {dateFromString, formatDateRelative} from '../../../utils/date' -import {LEADERBOARD_SCORES_PER_PAGE} from '../../../utils/accsaber/consts' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import { dateFromString, formatDateRelative } from "../../../utils/date"; +import { LEADERBOARD_SCORES_PER_PAGE } from "../../../utils/accsaber/consts"; -const process = response => { - if (!response || !Array.isArray(response.responses) || response.responses.length !== 2 || !Array.isArray(response.responses[0])) return []; +const process = (response) => { + if ( + !response || + !Array.isArray(response.responses) || + response.responses.length !== 2 || + !Array.isArray(response.responses[0]) + ) + return []; const page = response?.fetchOptions.page ?? 1; const totalItems = response.responses[0].length; @@ -25,16 +31,32 @@ const process = response => { difficulty, } = mapInfo; - const song = {hash, name, subName, authorName, levelAuthorName, beatsaverKey}; - const diffInfo = {type: 'Standard', diff: difficulty?.toLowerCase()?.replace('plus', 'Plus')} - const leaderboard = {leaderboardId, song, diffInfo, complexity, categoryDisplayName}; + const song = { + hash, + name, + subName, + authorName, + levelAuthorName, + beatsaverKey, + }; + const diffInfo = { + type: "Standard", + diff: difficulty?.toLowerCase()?.replace("plus", "Plus"), + }; + const leaderboard = { + leaderboardId, + song, + diffInfo, + complexity, + categoryDisplayName, + }; return { page, pageQty, totalItems, leaderboard, - scores: response.responses[0].map(s => { + scores: response.responses[0].map((s) => { let { accuracy: acc, ap, @@ -48,14 +70,16 @@ const process = response => { if (acc && Number.isFinite(acc)) acc *= 100; - timeSet = dateFromString(timeSet) + timeSet = dateFromString(timeSet); const timeSetString = formatDateRelative(timeSet); return { player: { name, playerId, - playerInfo: {avatar: `https://cdn.accsaber.com/avatars/${playerId}.jpg`}, + playerInfo: { + avatar: `https://cdn.accsaber.com/avatars/${playerId}.jpg`, + }, }, score: { acc, @@ -67,20 +91,31 @@ const process = response => { timeSetString, }, other: rest, - } + }; }), }; -} +}; -const get = async ({leaderboardId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => { +const get = async ({ + leaderboardId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => { const responses = await Promise.all([ queue.ACCSABER.leaderboard(leaderboardId, page, priority, queueOptions), - queue.ACCSABER.leaderboardInfo(leaderboardId, priority, queueOptions) + queue.ACCSABER.leaderboardInfo(leaderboardId, priority, queueOptions), ]); - return {...responses[0], body: {responses: responses.map(r => r.body), fetchOptions: {leaderboardId, page}}} -} + return { + ...responses[0], + body: { + responses: responses.map((r) => r.body), + fetchOptions: { leaderboardId, page }, + }, + }; +}; const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/accsaber/api-player-rank-history.js b/src/network/clients/accsaber/api-player-rank-history.js index b3627de..15e507f 100644 --- a/src/network/clients/accsaber/api-player-rank-history.js +++ b/src/network/clients/accsaber/api-player-rank-history.js @@ -1,29 +1,44 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import {fromAccSaberDateString} from '../../../utils/date' -import {isDateObject} from '../../../utils/js' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import { fromAccSaberDateString } from "../../../utils/date"; +import { isDateObject } from "../../../utils/js"; -const process = response => { +const process = (response) => { const playerId = response?.fetchOptions?.playerId ?? null; - if (!response?.response || !Object.keys(response.response)?.length || !playerId) return []; - + if ( + !response?.response || + !Object.keys(response.response)?.length || + !playerId + ) + return []; return { playerId, history: Object.entries(response.response) - .map(([date, rank]) => ({date: fromAccSaberDateString(date), rank})) - .filter(obj => isDateObject(obj?.date)) - .sort((a,b) => a.date.getTime() - b.date.getTime()) - , - } -} + .map(([date, rank]) => ({ date: fromAccSaberDateString(date), rank })) + .filter((obj) => isDateObject(obj?.date)) + .sort((a, b) => a.date.getTime() - b.date.getTime()), + }; +}; -const get = async ({playerId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => { - const response = await queue.ACCSABER.playerRankHistory(playerId, priority, queueOptions); +const get = async ({ + playerId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => { + const response = await queue.ACCSABER.playerRankHistory( + playerId, + priority, + queueOptions, + ); - return {...response, body: {response: response.body, fetchOptions: {playerId}}} -} + return { + ...response, + body: { response: response.body, fetchOptions: { playerId } }, + }; +}; const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/accsaber/api-ranking.js b/src/network/clients/accsaber/api-ranking.js index 1522db9..1978bd0 100644 --- a/src/network/clients/accsaber/api-ranking.js +++ b/src/network/clients/accsaber/api-ranking.js @@ -1,24 +1,37 @@ -import queue from '../../queues/queues' -import createClient from '../generic' +import queue from "../../queues/queues"; +import createClient from "../generic"; -const process = response => { - const category = response?.fetchOptions?.category ?? 'overall'; +const process = (response) => { + const category = response?.fetchOptions?.category ?? "overall"; if (!response?.response || !Array.isArray(response.response)) return []; - return response.response.map(p => ({ + return response.response.map((p) => ({ ...p, id: `${p.playerId}-${category}`, category, lastUpdated: new Date(), })); -} +}; -const get = async ({category = 'overall', page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => { - const response = await queue.ACCSABER.ranking(category, page, priority, queueOptions); +const get = async ({ + category = "overall", + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => { + const response = await queue.ACCSABER.ranking( + category, + page, + priority, + queueOptions, + ); - return {...response, body: {response: response.body, fetchOptions: {category}}} -} + return { + ...response, + body: { response: response.body, fetchOptions: { category } }, + }; +}; const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/accsaber/api-scores.js b/src/network/clients/accsaber/api-scores.js index 6fc55e0..d4982b0 100644 --- a/src/network/clients/accsaber/api-scores.js +++ b/src/network/clients/accsaber/api-scores.js @@ -1,12 +1,13 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import {dateFromString} from '../../../utils/date' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import { dateFromString } from "../../../utils/date"; -const process = response => { +const process = (response) => { const playerId = response?.fetchOptions?.playerId ?? null; - if (!response?.response || !Array.isArray(response.response) || !playerId) return []; + if (!response?.response || !Array.isArray(response.response) || !playerId) + return []; - return response.response.map(s => { + return response.response.map((s) => { let { songHash: hash, songName: name, @@ -28,11 +29,27 @@ const process = response => { leaderboardId = parseInt(leaderboardId, 10); if (isNaN(leaderboardId)) leaderboardId = null; - const song = {hash, name, subName: '', authorName, levelAuthorName, beatsaverKey}; - const diffInfo = {type: 'Standard', diff: difficulty?.toLowerCase()?.replace('plus', 'Plus')} - const leaderboard = {leaderboardId, song, diffInfo, complexity, categoryDisplayName}; + const song = { + hash, + name, + subName: "", + authorName, + levelAuthorName, + beatsaverKey, + }; + const diffInfo = { + type: "Standard", + diff: difficulty?.toLowerCase()?.replace("plus", "Plus"), + }; + const leaderboard = { + leaderboardId, + song, + diffInfo, + complexity, + categoryDisplayName, + }; - const timeSet = dateFromString(s.timeSet) + const timeSet = dateFromString(s.timeSet); return { id: `${playerId}-${s.leaderboardId}`, playerId, @@ -41,19 +58,42 @@ const process = response => { ap, acc, leaderboard, - score: {...originalScore, ap, unmodifiedScore: score, score, mods: null, timeSet, acc, percentage: acc, weightedAp}, + score: { + ...originalScore, + ap, + unmodifiedScore: score, + score, + mods: null, + timeSet, + acc, + percentage: acc, + weightedAp, + }, fetchedAt: new Date(), lastUpdated: new Date(), - } + }; }); -} +}; -const get = async ({playerId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => { - const response = await queue.ACCSABER.scores(playerId, page, priority, queueOptions); +const get = async ({ + playerId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => { + const response = await queue.ACCSABER.scores( + playerId, + page, + priority, + queueOptions, + ); - return {...response, body: {response: response.body, fetchOptions: {playerId, page}}} -} + return { + ...response, + body: { response: response.body, fetchOptions: { playerId, page } }, + }; +}; const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/beatmaps/api-hash.js b/src/network/clients/beatmaps/api-hash.js index e83b831..770ab79 100644 --- a/src/network/clients/beatmaps/api-hash.js +++ b/src/network/clients/beatmaps/api-hash.js @@ -1,9 +1,13 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import process from './utils/process' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import process from "./utils/process"; -const get = async ({hash, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.BEATMAPS.byHash(hash, priority, queueOptions); +const get = async ({ + hash, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.BEATMAPS.byHash(hash, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/beatmaps/api-key.js b/src/network/clients/beatmaps/api-key.js index fca4e52..02de149 100644 --- a/src/network/clients/beatmaps/api-key.js +++ b/src/network/clients/beatmaps/api-key.js @@ -1,9 +1,13 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import process from './utils/process' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import process from "./utils/process"; -const get = async ({key, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.BEATMAPS.byKey(key, priority, queueOptions); +const get = async ({ + key, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.BEATMAPS.byKey(key, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/beatmaps/utils/process.js b/src/network/clients/beatmaps/utils/process.js index e514457..5147a09 100644 --- a/src/network/clients/beatmaps/utils/process.js +++ b/src/network/clients/beatmaps/utils/process.js @@ -1,15 +1,15 @@ -import {opt} from '../../../../utils/js' +import { opt } from "../../../../utils/js"; -export default response => { - const versions = opt(response, 'versions'); +export default (response) => { + const versions = opt(response, "versions"); if (!versions || !Array.isArray(versions) || !versions.length) return null; const lastIdx = versions.length - 1; const hash = opt(versions, `${lastIdx}.hash`); - const key = opt(response, 'id'); + const key = opt(response, "id"); if (!hash || !key || !hash.toLowerCase) return null; - return {...response, hash: hash.toLowerCase(), key} -} \ No newline at end of file + return { ...response, hash: hash.toLowerCase(), key }; +}; diff --git a/src/network/clients/beatsavior/api.js b/src/network/clients/beatsavior/api.js index 07928f7..b20b4d8 100644 --- a/src/network/clients/beatsavior/api.js +++ b/src/network/clients/beatsavior/api.js @@ -1,6 +1,6 @@ -import queue from '../../queues/queues' -import {dateFromString} from '../../../utils/date' -import createClient from '../generic' +import queue from "../../queues/queues"; +import { dateFromString } from "../../../utils/date"; +import createClient from "../generic"; const SONG_DATA_TYPES = { None: 0, @@ -8,14 +8,14 @@ const SONG_DATA_TYPES = { Fail: 2, Practice: 3, Replay: 4, - Campaign: 5 -} + Campaign: 5, +}; -const process = response => { +const process = (response) => { if (!response || !Array.isArray(response)) return null; return response - .map(s => { + .map((s) => { let { _id: beatSaviorId, playerID: playerId, @@ -29,28 +29,65 @@ const process = response => { timeSet, trackers, trackers: { - accuracyTracker: {accLeft, accRight, leftAverageCut, rightAverageCut, leftTimeDependence, rightTimeDependence, leftPreswing, leftPostswing, rightPreswing, rightPostswing}, - winTracker: {won, nbOfPause: pauses, rank}, - hitTracker: {bombHit, miss, missedNotes, badCuts, nbOfWallHit: wallHit, maxCombo}, - scoreTracker: {score}, + accuracyTracker: { + accLeft, + accRight, + leftAverageCut, + rightAverageCut, + leftTimeDependence, + rightTimeDependence, + leftPreswing, + leftPostswing, + rightPreswing, + rightPostswing, + }, + winTracker: { won, nbOfPause: pauses, rank }, + hitTracker: { + bombHit, + miss, + missedNotes, + badCuts, + nbOfWallHit: wallHit, + maxCombo, + }, + scoreTracker: { score }, }, } = s; - if (![SONG_DATA_TYPES.Pass, SONG_DATA_TYPES.Fail, SONG_DATA_TYPES.Campaign].includes(type)) return null; + if ( + ![ + SONG_DATA_TYPES.Pass, + SONG_DATA_TYPES.Fail, + SONG_DATA_TYPES.Campaign, + ].includes(type) + ) + return null; const leaderboardId = null; hash = hash ? hash.toLowerCase() : null; - if (!playerId || !playerId.length || !hash || !hash.length || !diff || !diff.length || !score) return null; + if ( + !playerId || + !playerId.length || + !hash || + !hash.length || + !diff || + !diff.length || + !score + ) + return null; - const song = {hash, name, subName: '', authorName, levelAuthorName}; + const song = { hash, name, subName: "", authorName, levelAuthorName }; const leaderboard = { leaderboardId, difficulty, - diffInfo: {diff: diff === 'expertplus' ? 'expertPlus' : diff, type: 'Standard'}, + diffInfo: { + diff: diff === "expertplus" ? "expertPlus" : diff, + type: "Standard", + }, song, - } + }; const stats = { won, @@ -62,9 +99,17 @@ const process = response => { bombHit, wallHit, maxCombo, - accLeft, accRight, leftAverageCut, rightAverageCut, leftTimeDependence, rightTimeDependence, - leftPreswing, leftPostswing, rightPreswing, rightPostswing, - } + accLeft, + accRight, + leftAverageCut, + rightAverageCut, + leftTimeDependence, + rightTimeDependence, + leftPreswing, + leftPostswing, + rightPreswing, + rightPostswing, + }; return { beatSaviorId, @@ -72,24 +117,27 @@ const process = response => { leaderboardId, scoreId: null, hash, - diff: diff === 'expertplus' ? 'expertPlus' : diff, + diff: diff === "expertplus" ? "expertPlus" : diff, score, type, leaderboard, timeSet: dateFromString(timeSet), stats, trackers, - } - + }; }) - .filter(s => s); + .filter((s) => s); }; -const get = async ({playerId, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.BEATSAVIOR.player(playerId, priority, queueOptions); +const get = async ({ + playerId, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.BEATSAVIOR.player(playerId, priority, queueOptions); const client = createClient(get, process); export default { ...client, - SONG_DATA_TYPES -}; \ No newline at end of file + SONG_DATA_TYPES, +}; diff --git a/src/network/clients/generic.js b/src/network/clients/generic.js index f6f7d97..2a99025 100644 --- a/src/network/clients/generic.js +++ b/src/network/clients/generic.js @@ -1,19 +1,35 @@ -import queue, {getResponseBody, isResponseCached, updateResponseBody} from '../queues/queues' +import queue, { + getResponseBody, + isResponseCached, + updateResponseBody, +} from "../queues/queues"; export default (get, process) => { - const clientGet = async ({priority = queue.PRIORITY.FG_LOW, fullResponse = false, ...getOptions} = {}) => { - const response = await get({...getOptions, priority}); + const clientGet = async ({ + priority = queue.PRIORITY.FG_LOW, + fullResponse = false, + ...getOptions + } = {}) => { + const response = await get({ ...getOptions, priority }); return fullResponse ? response : getResponseBody(response); - } + }; - const clientGetProcessed = async ({priority = queue.PRIORITY.FG_LOW, fullResponse = false, ...getOptions} = {}) => { - const response = await clientGet({...getOptions, priority, fullResponse}); + const clientGetProcessed = async ({ + priority = queue.PRIORITY.FG_LOW, + fullResponse = false, + ...getOptions + } = {}) => { + const response = await clientGet({ ...getOptions, priority, fullResponse }); - const processedResponse = process(fullResponse ? getResponseBody(response) : response); + const processedResponse = process( + fullResponse ? getResponseBody(response) : response, + ); - return fullResponse ? updateResponseBody(response, processedResponse) : processedResponse; - } + return fullResponse + ? updateResponseBody(response, processedResponse) + : processedResponse; + }; return { get: clientGet, @@ -21,5 +37,5 @@ export default (get, process) => { getProcessed: clientGetProcessed, getDataFromResponse: getResponseBody, isResponseCached, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/clients/scoresaber/leaderboard/page-leaderboard.js b/src/network/clients/scoresaber/leaderboard/page-leaderboard.js index 2b5a520..a9afbb6 100644 --- a/src/network/clients/scoresaber/leaderboard/page-leaderboard.js +++ b/src/network/clients/scoresaber/leaderboard/page-leaderboard.js @@ -1,34 +1,63 @@ -import queue from '../../../queues/queues' -import {opt} from '../../../../utils/js' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import { opt } from "../../../../utils/js"; +import createClient from "../../generic"; -const process = response => { - if (!opt(response, 'scores') || !Array.isArray(response.scores)) return null; +const process = (response) => { + if (!opt(response, "scores") || !Array.isArray(response.scores)) return null; - const scores = response.scores.map(s => { - let {unmodififiedScore: unmodifiedScore, mods, ...score} = s.score; + const scores = response.scores.map((s) => { + let { unmodififiedScore: unmodifiedScore, mods, ...score } = s.score; - if (mods && typeof mods === 'string') mods = mods.split(',').map(m => m.trim().toUpperCase()).filter(m => m.length); + if (mods && typeof mods === "string") + mods = mods + .split(",") + .map((m) => m.trim().toUpperCase()) + .filter((m) => m.length); else if (!mods) mods = null; - const acc = unmodifiedScore && opt(score, 'maxScore') ? unmodifiedScore / score.maxScore * 100 : opt(score, 'acc', null); - const percentage = opt(score, 'score') && opt(score, 'maxScore') ? score.score / score.maxScore * 100 : opt(score, 'percentage', null); + const acc = + unmodifiedScore && opt(score, "maxScore") + ? (unmodifiedScore / score.maxScore) * 100 + : opt(score, "acc", null); + const percentage = + opt(score, "score") && opt(score, "maxScore") + ? (score.score / score.maxScore) * 100 + : opt(score, "percentage", null); - const ppWeighted = opt(score, 'pp') && opt(score, 'weight') ? score.pp * score.weight : null; + const ppWeighted = + opt(score, "pp") && opt(score, "weight") ? score.pp * score.weight : null; return { ...s, - score: {...score, unmodifiedScore: unmodifiedScore || null, mods, acc, percentage, ppWeighted}, + score: { + ...score, + unmodifiedScore: unmodifiedScore || null, + mods, + acc, + percentage, + ppWeighted, + }, }; }); return { ...response, - scores - } -} + scores, + }; +}; -const get = async ({leaderboardId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_PAGE.leaderboard(leaderboardId, page, priority, queueOptions); +const get = async ({ + leaderboardId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => + queue.SCORESABER_PAGE.leaderboard( + leaderboardId, + page, + priority, + queueOptions, + ); const client = createClient(get, process); diff --git a/src/network/clients/scoresaber/player/api.js b/src/network/clients/scoresaber/player/api.js index 40ddfed..82ba530 100644 --- a/src/network/clients/scoresaber/player/api.js +++ b/src/network/clients/scoresaber/player/api.js @@ -1,34 +1,56 @@ -import queue from '../../../queues/queues' -import createClient from '../../generic' -import {opt} from '../../../../utils/js' +import queue from "../../../queues/queues"; +import createClient from "../../generic"; +import { opt } from "../../../../utils/js"; -const process = response => { - if (!opt(response, 'playerInfo')) return null; +const process = (response) => { + if (!opt(response, "playerInfo")) return null; - const {playerInfo: info, scoreStats} = response; - const {playerId, playerName: name, country, countryRank, avatar, permissions, ...playerInfo} = info; + const { playerInfo: info, scoreStats } = response; + const { + playerId, + playerName: name, + country, + countryRank, + avatar, + permissions, + ...playerInfo + } = info; if (avatar) { - if (!avatar.startsWith('http')) - playerInfo.avatar = `${queue.SCORESABER_API.SS_API_HOST}${!avatar.startsWith('/') ? '/' : ''}${avatar}`; - else - playerInfo.avatar = avatar; + if (!avatar.startsWith("http")) + playerInfo.avatar = `${queue.SCORESABER_API.SS_API_HOST}${ + !avatar.startsWith("/") ? "/" : "" + }${avatar}`; + else playerInfo.avatar = avatar; } playerInfo.banned = !!playerInfo.banned; playerInfo.inactive = !!playerInfo.inactive; - playerInfo.rankHistory = playerInfo.history && playerInfo.history.length - ? playerInfo.history.split(',').map(r => parseInt(r, 10)).filter(r => !isNaN(r)) - : []; + playerInfo.rankHistory = + playerInfo.history && playerInfo.history.length + ? playerInfo.history + .split(",") + .map((r) => parseInt(r, 10)) + .filter((r) => !isNaN(r)) + : []; delete playerInfo.history; playerInfo.externalProfileUrl = null; - playerInfo.countries = [{country, rank: countryRank}]; + playerInfo.countries = [{ country, rank: countryRank }]; - return {playerId, name, playerInfo, scoreStats: scoreStats ? scoreStats : null}; + return { + playerId, + name, + playerInfo, + scoreStats: scoreStats ? scoreStats : null, + }; }; -const get = async ({playerId, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.player(playerId, priority, queueOptions); +const get = async ({ + playerId, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.SCORESABER_API.player(playerId, priority, queueOptions); const client = createClient(get, process); diff --git a/src/network/clients/scoresaber/player/page.js b/src/network/clients/scoresaber/player/page.js index 06b9620..eb6bc89 100644 --- a/src/network/clients/scoresaber/player/page.js +++ b/src/network/clients/scoresaber/player/page.js @@ -1,21 +1,27 @@ -import queue from '../../../queues/queues' -import api from './api' -import {opt} from '../../../../utils/js' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import api from "./api"; +import { opt } from "../../../../utils/js"; +import createClient from "../../generic"; -const process = response => { - const apiProcessedResponse = api.process(response && response.player ? response.player : null); +const process = (response) => { + const apiProcessedResponse = api.process( + response && response.player ? response.player : null, + ); - if (!opt(apiProcessedResponse, 'player.playerInfo')) return null; + if (!opt(apiProcessedResponse, "player.playerInfo")) return null; - const recentPlay = opt(response, 'player.recentPlay'); - const recentPlayLastUpdated = opt(response, 'player.recentPlayLastUpdated'); + const recentPlay = opt(response, "player.recentPlay"); + const recentPlayLastUpdated = opt(response, "player.recentPlayLastUpdated"); if (recentPlay && recentPlayLastUpdated) { apiProcessedResponse.playerInfo.recentPlay = recentPlay; - apiProcessedResponse.playerInfo.recentPlayLastUpdated = recentPlayLastUpdated; + apiProcessedResponse.playerInfo.recentPlayLastUpdated = + recentPlayLastUpdated; } - const externalProfileUrl = opt(response, 'player.playerInfo.externalProfileUrl'); + const externalProfileUrl = opt( + response, + "player.playerInfo.externalProfileUrl", + ); if (externalProfileUrl) { apiProcessedResponse.playerInfo.externalProfileUrl = externalProfileUrl; } @@ -23,8 +29,12 @@ const process = response => { return apiProcessedResponse; }; -const get = async ({playerId, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_PAGE.player(playerId, priority, queueOptions); +const get = async ({ + playerId, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.SCORESABER_PAGE.player(playerId, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/players/api-player-find.js b/src/network/clients/scoresaber/players/api-player-find.js index a74c3f4..7512ff5 100644 --- a/src/network/clients/scoresaber/players/api-player-find.js +++ b/src/network/clients/scoresaber/players/api-player-find.js @@ -1,9 +1,13 @@ -import queue from '../../../queues/queues' -import process from './utils/process' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import process from "./utils/process"; +import createClient from "../../generic"; -const get = async ({query, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.findPlayer(query, priority, queueOptions); +const get = async ({ + query, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.SCORESABER_API.findPlayer(query, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/players/api-ranking-global-pages.js b/src/network/clients/scoresaber/players/api-ranking-global-pages.js index 0c829c2..33e8af4 100644 --- a/src/network/clients/scoresaber/players/api-ranking-global-pages.js +++ b/src/network/clients/scoresaber/players/api-ranking-global-pages.js @@ -1,11 +1,14 @@ -import queue from '../../../queues/queues' -import {opt} from '../../../../utils/js' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import { opt } from "../../../../utils/js"; +import createClient from "../../generic"; -const process = response => opt(response, 'pages', null) +const process = (response) => opt(response, "pages", null); -const get = async ({priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.rankingGlobalPages(priority, queueOptions); +const get = async ({ + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.SCORESABER_API.rankingGlobalPages(priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/players/api-ranking-global.js b/src/network/clients/scoresaber/players/api-ranking-global.js index f2f083f..1ee1215 100644 --- a/src/network/clients/scoresaber/players/api-ranking-global.js +++ b/src/network/clients/scoresaber/players/api-ranking-global.js @@ -1,9 +1,13 @@ -import queue from '../../../queues/queues' -import process from './utils/process' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import process from "./utils/process"; +import createClient from "../../generic"; -const get = async ({page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.rankingGlobal(page, priority, queueOptions); +const get = async ({ + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.SCORESABER_API.rankingGlobal(page, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/players/page-ranking-country.js b/src/network/clients/scoresaber/players/page-ranking-country.js index fb1f747..793912c 100644 --- a/src/network/clients/scoresaber/players/page-ranking-country.js +++ b/src/network/clients/scoresaber/players/page-ranking-country.js @@ -1,18 +1,24 @@ -import queue from '../../../queues/queues' -import api from './api-ranking-global' -import {opt} from '../../../../utils/js' -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import api from "./api-ranking-global"; +import { opt } from "../../../../utils/js"; +import createClient from "../../generic"; -const process = response => { +const process = (response) => { const apiProcessedResponse = api.process(response); - if (!opt(response, 'players')) return null; + if (!opt(response, "players")) return null; return apiProcessedResponse; -} +}; -const get = async ({country, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_PAGE.countryRanking(country, page, priority, queueOptions); +const get = async ({ + country, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => + queue.SCORESABER_PAGE.countryRanking(country, page, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/players/utils/process.js b/src/network/clients/scoresaber/players/utils/process.js index 94929ee..c1e046c 100644 --- a/src/network/clients/scoresaber/players/utils/process.js +++ b/src/network/clients/scoresaber/players/utils/process.js @@ -1,17 +1,28 @@ -import {opt} from '../../../../../utils/js' -import queue from '../../../../queues/queues' +import { opt } from "../../../../../utils/js"; +import queue from "../../../../queues/queues"; -export default response => { - if (!opt(response, 'players')) return null; +export default (response) => { + if (!opt(response, "players")) return null; if (!Array.isArray(response.players)) return null; - return response.players.map(player => { - let {avatar, country, difference, history, playerId, playerName: name, pp, rank} = player; + return response.players.map((player) => { + let { + avatar, + country, + difference, + history, + playerId, + playerName: name, + pp, + rank, + } = player; if (avatar) { - if (!avatar.startsWith('http')) - avatar = `${queue.SCORESABER_API.SS_API_HOST}${!avatar.startsWith('/') ? '/' : ''}${avatar}`; + if (!avatar.startsWith("http")) + avatar = `${queue.SCORESABER_API.SS_API_HOST}${ + !avatar.startsWith("/") ? "/" : "" + }${avatar}`; } return { @@ -19,16 +30,20 @@ export default response => { name, playerInfo: { avatar, - countries: [{country, rank: null}], + countries: [{ country, rank: null }], pp, rank, - rankHistory: history && history.length - ? history.split(',').map(r => parseInt(r, 10)).filter(r => !isNaN(r)) - : [], + rankHistory: + history && history.length + ? history + .split(",") + .map((r) => parseInt(r, 10)) + .filter((r) => !isNaN(r)) + : [], }, others: { difference, }, - } + }; }); -}; \ No newline at end of file +}; diff --git a/src/network/clients/scoresaber/rankeds/page.js b/src/network/clients/scoresaber/rankeds/page.js index 11de639..5a68df2 100644 --- a/src/network/clients/scoresaber/rankeds/page.js +++ b/src/network/clients/scoresaber/rankeds/page.js @@ -1,10 +1,14 @@ -import createClient from '../../generic' -import queues from '../../../queues/queues' +import createClient from "../../generic"; +import queues from "../../../queues/queues"; -const process = response => response; +const process = (response) => response; -const get = async ({page = 1, priority = queues.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queues.SCORESABER_PAGE.rankeds(page, priority, queueOptions) +const get = async ({ + page = 1, + priority = queues.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queues.SCORESABER_PAGE.rankeds(page, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/scores/api-recent.js b/src/network/clients/scoresaber/scores/api-recent.js index dacffad..8673d2c 100644 --- a/src/network/clients/scoresaber/scores/api-recent.js +++ b/src/network/clients/scoresaber/scores/api-recent.js @@ -1,9 +1,15 @@ -import queue from '../../../queues/queues' -import process from './utils/process'; -import createClient from '../../generic' +import queue from "../../../queues/queues"; +import process from "./utils/process"; +import createClient from "../../generic"; -const get = async ({playerId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.recentScores(playerId, page, priority, queueOptions); +const get = async ({ + playerId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => + queue.SCORESABER_API.recentScores(playerId, page, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/scores/api-top.js b/src/network/clients/scoresaber/scores/api-top.js index a93ac20..f8fd21b 100644 --- a/src/network/clients/scoresaber/scores/api-top.js +++ b/src/network/clients/scoresaber/scores/api-top.js @@ -1,9 +1,15 @@ -import queue from '../../../queues/queues' -import createClient from '../../generic' -import process from './utils/process' +import queue from "../../../queues/queues"; +import createClient from "../../generic"; +import process from "./utils/process"; -const get = async ({playerId, page = 1, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.SCORESABER_API.topScores(playerId, page, priority, queueOptions); +const get = async ({ + playerId, + page = 1, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => + queue.SCORESABER_API.topScores(playerId, page, priority, queueOptions); const client = createClient(get, process); -export default client; \ No newline at end of file +export default client; diff --git a/src/network/clients/scoresaber/scores/utils/process.js b/src/network/clients/scoresaber/scores/utils/process.js index d2dc63d..ac8ff86 100644 --- a/src/network/clients/scoresaber/scores/utils/process.js +++ b/src/network/clients/scoresaber/scores/utils/process.js @@ -1,11 +1,16 @@ -import {dateFromString} from '../../../../../utils/date' -import {extractDiffAndType} from '../../../../../utils/scoresaber/format' -import {opt} from '../../../../../utils/js' +import { dateFromString } from "../../../../../utils/date"; +import { extractDiffAndType } from "../../../../../utils/scoresaber/format"; +import { opt } from "../../../../../utils/js"; -export default response => { - if (!opt(response, 'scores') || !Array.isArray(response.scores) || !opt(response, 'scores.0.scoreId')) return []; +export default (response) => { + if ( + !opt(response, "scores") || + !Array.isArray(response.scores) || + !opt(response, "scores.0.scoreId") + ) + return []; - return response.scores.map(s => { + return response.scores.map((s) => { const { songHash: hash, songName: name, @@ -18,25 +23,44 @@ export default response => { ...originalScore } = s; - const song = {hash, name, subName, authorName, levelAuthorName}; + const song = { hash, name, subName, authorName, levelAuthorName }; const diffInfo = extractDiffAndType(difficultyRaw); - const leaderboard = {leaderboardId, song, diffInfo, difficulty}; + const leaderboard = { leaderboardId, song, diffInfo, difficulty }; - let {unmodififiedScore: unmodifiedScore, mods, ...score} = originalScore; + let { unmodififiedScore: unmodifiedScore, mods, ...score } = originalScore; - if (mods && typeof mods === 'string') mods = mods.split(',').map(m => m.trim().toUpperCase()).filter(m => m.length); + if (mods && typeof mods === "string") + mods = mods + .split(",") + .map((m) => m.trim().toUpperCase()) + .filter((m) => m.length); else if (!mods) mods = null; - const acc = unmodifiedScore && opt(score, 'maxScore') ? unmodifiedScore / score.maxScore * 100 : null; - const percentage = opt(score, 'score') && opt(score, 'maxScore') ? score.score / score.maxScore * 100 : null; + const acc = + unmodifiedScore && opt(score, "maxScore") + ? (unmodifiedScore / score.maxScore) * 100 + : null; + const percentage = + opt(score, "score") && opt(score, "maxScore") + ? (score.score / score.maxScore) * 100 + : null; - const ppWeighted = opt(score, 'pp') && opt(score, 'weight') ? score.pp * score.weight : null; + const ppWeighted = + opt(score, "pp") && opt(score, "weight") ? score.pp * score.weight : null; return { leaderboard, - score: {...score, unmodifiedScore, mods, timeSet: dateFromString(score.timeSet), acc, percentage, ppWeighted}, + score: { + ...score, + unmodifiedScore, + mods, + timeSet: dateFromString(score.timeSet), + acc, + percentage, + ppWeighted, + }, fetchedAt: new Date(), lastUpdated: new Date(), }; }); -} \ No newline at end of file +}; diff --git a/src/network/clients/twitch/api-profile.js b/src/network/clients/twitch/api-profile.js index 4ebe15f..70e95af 100644 --- a/src/network/clients/twitch/api-profile.js +++ b/src/network/clients/twitch/api-profile.js @@ -1,17 +1,22 @@ -import queue from '../../queues/queues' -import createClient from '../generic' -import {opt} from '../../../utils/js' +import queue from "../../queues/queues"; +import createClient from "../generic"; +import { opt } from "../../../utils/js"; -const process = response => { - if (!opt(response, 'data.0')) return null; +const process = (response) => { + if (!opt(response, "data.0")) return null; - return {...response.data[0], profileLastUpdated: new Date()}; + return { ...response.data[0], profileLastUpdated: new Date() }; }; -const get = async ({accessToken, login, priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.TWITCH.profile(accessToken, login, priority, queueOptions); +const get = async ({ + accessToken, + login, + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.TWITCH.profile(accessToken, login, priority, queueOptions); const client = createClient(get, process); export default { - ...client -} + ...client, +}; diff --git a/src/network/clients/twitch/api-videos.js b/src/network/clients/twitch/api-videos.js index a818ffd..3c4e074 100644 --- a/src/network/clients/twitch/api-videos.js +++ b/src/network/clients/twitch/api-videos.js @@ -1,16 +1,22 @@ -import queue from '../../queues/queues' -import createClient from '../generic' +import queue from "../../queues/queues"; +import createClient from "../generic"; -const process = response => { +const process = (response) => { if (!response || !response.data || !Array.isArray(response.data)) return null; return response.data; }; -const get = async ({accessToken, userId, type = 'archive', priority = queue.PRIORITY.FG_HIGH, ...queueOptions} = {}) => queue.TWITCH.videos(accessToken, userId, type, queueOptions); +const get = async ({ + accessToken, + userId, + type = "archive", + priority = queue.PRIORITY.FG_HIGH, + ...queueOptions +} = {}) => queue.TWITCH.videos(accessToken, userId, type, queueOptions); const client = createClient(get, process); export default { ...client, -} +}; diff --git a/src/network/command-processor.js b/src/network/command-processor.js index 1900eca..bb3fe4d 100644 --- a/src/network/command-processor.js +++ b/src/network/command-processor.js @@ -1,45 +1,48 @@ -import eventBus from '../utils/broadcast-channel-pubsub' -import createPlayerService from '../services/scoresaber/player' -import log from '../utils/logger' +import eventBus from "../utils/broadcast-channel-pubsub"; +import createPlayerService from "../services/scoresaber/player"; +import log from "../utils/logger"; let initialized = false; export default (dlManager) => { if (initialized) { - log.debug(`Command processor already initialized.`, 'CmdProcessor'); + log.debug(`Command processor already initialized.`, "CmdProcessor"); return; } const playerService = createPlayerService(); - eventBus.on('data-imported', () => { - if (window) window.location.reload() + eventBus.on("data-imported", () => { + if (window) window.location.reload(); }); - eventBus.on('player-add-cmd', async ({playerId}) => { + eventBus.on("player-add-cmd", async ({ playerId }) => { await dlManager.enqueuePlayer(playerId); }); - eventBus.on('player-remove-cmd', async ({playerId, purgeScores = false}) => { - if (!playerId) return; + eventBus.on( + "player-remove-cmd", + async ({ playerId, purgeScores = false }) => { + if (!playerId) return; - await playerService.remove(playerId, purgeScores); - }); + await playerService.remove(playerId, purgeScores); + }, + ); - eventBus.on('dl-manager-pause-cmd', () => { - log.debug('Pause Dl Manager', 'CmdProcessor'); + eventBus.on("dl-manager-pause-cmd", () => { + log.debug("Pause Dl Manager", "CmdProcessor"); dlManager.pause(); }); - eventBus.on('dl-manager-unpause-cmd', () => { - log.debug('Unpause Dl Manager', 'CmdProcessor'); + eventBus.on("dl-manager-unpause-cmd", () => { + log.debug("Unpause Dl Manager", "CmdProcessor"); dlManager.start(); }); initialized = true; - log.info(`Command processor initialized`, 'CmdProcessor'); -} \ No newline at end of file + log.info(`Command processor initialized`, "CmdProcessor"); +}; diff --git a/src/network/download-manager.js b/src/network/download-manager.js index 4a37638..3ce8c26 100644 --- a/src/network/download-manager.js +++ b/src/network/download-manager.js @@ -1,15 +1,15 @@ -import eventBus from '../utils/broadcast-channel-pubsub' -import log from '../utils/logger' -import createQueue, {PRIORITY} from '../utils/queue' -import {configStore} from '../stores/config' -import createRankedsStore from '../stores/scoresaber/rankeds' -import createPlayerService from '../services/scoresaber/player' -import createScoresService from '../services/scoresaber/scores' -import createBeatSaviorService from '../services/beatsavior' -import createAccSaberService from '../services/accsaber' -import {PRIORITY as HTTP_QUEUE_PRIORITY} from './queues/http-queue' -import {HOUR, MINUTE} from '../utils/date' -import {opt} from '../utils/js' +import eventBus from "../utils/broadcast-channel-pubsub"; +import log from "../utils/logger"; +import createQueue, { PRIORITY } from "../utils/queue"; +import { configStore } from "../stores/config"; +import createRankedsStore from "../stores/scoresaber/rankeds"; +import createPlayerService from "../services/scoresaber/player"; +import createScoresService from "../services/scoresaber/scores"; +import createBeatSaviorService from "../services/beatsavior"; +import createAccSaberService from "../services/accsaber"; +import { PRIORITY as HTTP_QUEUE_PRIORITY } from "./queues/http-queue"; +import { HOUR, MINUTE } from "../utils/date"; +import { opt } from "../utils/js"; const INTERVAL_TICK = MINUTE; @@ -22,110 +22,198 @@ let beatSaviorService = null; let accSaberService = null; const TYPES = { - BEATSAVIOR: {name: 'BEATSAVIOR', priority: PRIORITY.LOW}, - RANKEDS: {name: 'RANKEDS', priority: PRIORITY.LOW}, - ACCSABER: {name: 'ACCSABER', priority: PRIORITY.NORMAL}, - PLAYER_SCORES: {name: 'PLAYER-SCORES', priority: PRIORITY.NORMAL}, - PLAYER_SCORES_UPDATE_QUEUE: {name: 'PLAYER_SCORES_UPDATE_QUEUE', priority: PRIORITY.LOWEST}, - ACTIVE_PLAYERS: {name: 'ACTIVE-PLAYERS', priority: PRIORITY.HIGH}, - MAIN_PLAYER: {name: 'MAIN-PLAYER', priority: PRIORITY.HIGHEST}, -} + BEATSAVIOR: { name: "BEATSAVIOR", priority: PRIORITY.LOW }, + RANKEDS: { name: "RANKEDS", priority: PRIORITY.LOW }, + ACCSABER: { name: "ACCSABER", priority: PRIORITY.NORMAL }, + PLAYER_SCORES: { name: "PLAYER-SCORES", priority: PRIORITY.NORMAL }, + PLAYER_SCORES_UPDATE_QUEUE: { + name: "PLAYER_SCORES_UPDATE_QUEUE", + priority: PRIORITY.LOWEST, + }, + ACTIVE_PLAYERS: { name: "ACTIVE-PLAYERS", priority: PRIORITY.HIGH }, + MAIN_PLAYER: { name: "MAIN-PLAYER", priority: PRIORITY.HIGHEST }, +}; -const enqueue = async (queue, type, force = false, data = null, then = null) => { +const enqueue = async ( + queue, + type, + force = false, + data = null, + then = null, +) => { if (!type || !type.name || !Number.isFinite(type.priority)) { - log.warn(`Unknown type enqueued.`, 'DlManager', type); + log.warn(`Unknown type enqueued.`, "DlManager", type); return; } - log.debug(`Try to enqueue type ${type.name}. Forced: ${force}, data: ${JSON.stringify(data)}`, 'DlManager'); + log.debug( + `Try to enqueue type ${type.name}. Forced: ${force}, data: ${JSON.stringify( + data, + )}`, + "DlManager", + ); const priority = force ? PRIORITY.HIGHEST : type.priority; - const networkPriority = priority === PRIORITY.HIGHEST ? HTTP_QUEUE_PRIORITY.BG_HIGH : HTTP_QUEUE_PRIORITY.BG_NORMAL; + const networkPriority = + priority === PRIORITY.HIGHEST + ? HTTP_QUEUE_PRIORITY.BG_HIGH + : HTTP_QUEUE_PRIORITY.BG_NORMAL; const processThen = async (promise, then = null) => { - promise.then(result => { - if(then) log.debug('Processing then command...', 'DlManager'); + promise.then((result) => { + if (then) log.debug("Processing then command...", "DlManager"); - return then ? {result, thenResult: then()} : result; - }) - } + return then ? { result, thenResult: then() } : result; + }); + }; switch (type) { case TYPES.MAIN_PLAYER: if (mainPlayerId) { - log.debug(`Enqueue main player`, 'DlManager'); + log.debug(`Enqueue main player`, "DlManager"); await Promise.all([ - enqueue(queue, {...TYPES.ACTIVE_PLAYERS, priority: PRIORITY.HIGHEST}, force, {playerId: mainPlayerId}), - enqueue(queue, {...TYPES.PLAYER_SCORES, priority: PRIORITY.HIGHEST}, force, {playerId: mainPlayerId}), + enqueue( + queue, + { ...TYPES.ACTIVE_PLAYERS, priority: PRIORITY.HIGHEST }, + force, + { playerId: mainPlayerId }, + ), + enqueue( + queue, + { ...TYPES.PLAYER_SCORES, priority: PRIORITY.HIGHEST }, + force, + { playerId: mainPlayerId }, + ), ]); } break; case TYPES.RANKEDS: - log.debug(`Enqueue rankeds`, 'DlManager'); + log.debug(`Enqueue rankeds`, "DlManager"); if (!rankedsStore) rankedsStore = await createRankedsStore(); - processThen(queue.add(async () => rankedsStore.refresh(force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued rankeds processed.', 'DlManager')); + processThen( + queue.add( + async () => rankedsStore.refresh(force, networkPriority), + priority, + ), + then, + ).then((_) => log.debug("Enqueued rankeds processed.", "DlManager")); break; case TYPES.ACTIVE_PLAYERS: - log.debug(`Enqueue active players`, 'DlManager'); + log.debug(`Enqueue active players`, "DlManager"); if (data && data.playerId) { if (data.add) - processThen(queue.add(async () => playerService.add(data.playerId, networkPriority), priority), then) - .then(_ => log.debug('Enqueued active players processed.', 'DlManager')); + processThen( + queue.add( + async () => playerService.add(data.playerId, networkPriority), + priority, + ), + then, + ).then((_) => + log.debug("Enqueued active players processed.", "DlManager"), + ); else - processThen(queue.add(async () => playerService.refresh(data.playerId, force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued active players processed.', 'DlManager')); + processThen( + queue.add( + async () => + playerService.refresh(data.playerId, force, networkPriority), + priority, + ), + then, + ).then((_) => + log.debug("Enqueued active players processed.", "DlManager"), + ); } else - processThen(queue.add(async () => playerService.refreshAll(force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued active players processed.', 'DlManager')); + processThen( + queue.add( + async () => playerService.refreshAll(force, networkPriority), + priority, + ), + then, + ).then((_) => + log.debug("Enqueued active players processed.", "DlManager"), + ); break; case TYPES.PLAYER_SCORES: - log.debug(`Enqueue players scores`, 'DlManager'); + log.debug(`Enqueue players scores`, "DlManager"); if (data && data.playerId) - processThen(queue.add(async () => scoresService.refresh(data.playerId, force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued players scores processed.', 'DlManager')); + processThen( + queue.add( + async () => + scoresService.refresh(data.playerId, force, networkPriority), + priority, + ), + then, + ).then((_) => + log.debug("Enqueued players scores processed.", "DlManager"), + ); else - processThen(queue.add(async () => scoresService.refreshAll(force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued players scores processed.', 'DlManager')); + processThen( + queue.add( + async () => scoresService.refreshAll(force, networkPriority), + priority, + ), + then, + ).then((_) => + log.debug("Enqueued players scores processed.", "DlManager"), + ); break; case TYPES.BEATSAVIOR: - log.debug(`Enqueue Beat Savior`, 'DlManager'); + log.debug(`Enqueue Beat Savior`, "DlManager"); - processThen(queue.add(async () => beatSaviorService.refreshAll(force, networkPriority), priority), then) - .then(_ => log.debug('Enqueued Beat Savior processed.', 'DlManager')); + processThen( + queue.add( + async () => beatSaviorService.refreshAll(force, networkPriority), + priority, + ), + then, + ).then((_) => log.debug("Enqueued Beat Savior processed.", "DlManager")); break; case TYPES.PLAYER_SCORES_UPDATE_QUEUE: - log.debug(`Enqueue player scores rank && pp updates`, 'DlManager'); + log.debug(`Enqueue player scores rank && pp updates`, "DlManager"); - processThen(queue.add(async () => scoresService.updateRankAndPpFromTheQueue(), priority), then) - .then(_ => log.debug('Enqueued player scores rank & pp updates processed.', 'DlManager')); + processThen( + queue.add( + async () => scoresService.updateRankAndPpFromTheQueue(), + priority, + ), + then, + ).then((_) => + log.debug( + "Enqueued player scores rank & pp updates processed.", + "DlManager", + ), + ); break; case TYPES.ACCSABER: - log.debug(`Enqueue AccSaber updates`, 'DlManager'); + log.debug(`Enqueue AccSaber updates`, "DlManager"); - processThen(queue.add(async () => accSaberService.refreshAll(), priority), then) - .then(_ => log.debug('Enqueued AccSaber updates processed.', 'DlManager')); + processThen( + queue.add(async () => accSaberService.refreshAll(), priority), + then, + ).then((_) => + log.debug("Enqueued AccSaber updates processed.", "DlManager"), + ); break; } -} +}; -const enqueueAllJobs = async queue => { - log.debug(`Try to enqueue & process queue.`, 'DlManager'); +const enqueueAllJobs = async (queue) => { + log.debug(`Try to enqueue & process queue.`, "DlManager"); await Promise.all([ enqueue(queue, TYPES.MAIN_PLAYER), @@ -137,18 +225,18 @@ const enqueueAllJobs = async queue => { // it should be at the end of the queue enqueue(queue, TYPES.PLAYER_SCORES_UPDATE_QUEUE), - ]) -} + ]); +}; let intervalId; -const startSyncing = async queue => { +const startSyncing = async (queue) => { await enqueueAllJobs(queue); intervalId = setInterval(() => enqueueAllJobs(queue), INTERVAL_TICK); -} +}; export default async () => { if (initialized) { - log.debug(`Download manager already initialized.`, 'DlManager'); + log.debug(`Download manager already initialized.`, "DlManager"); return; } @@ -161,49 +249,54 @@ export default async () => { mainPlayerId = configStore.getMainPlayerId(); - configStore.subscribe(config => { - const newMainPlayerId = opt(config, 'users.main') + configStore.subscribe((config) => { + const newMainPlayerId = opt(config, "users.main"); if (mainPlayerId !== newMainPlayerId) { mainPlayerId = newMainPlayerId; - log.debug(`Main player changed to ${mainPlayerId}`, 'DlManager') + log.debug(`Main player changed to ${mainPlayerId}`, "DlManager"); } - }) + }); playerService = createPlayerService(); scoresService = createScoresService(); beatSaviorService = createBeatSaviorService(); accSaberService = createAccSaberService(); - eventBus.leaderStore.subscribe(async isLeader => { + eventBus.leaderStore.subscribe(async (isLeader) => { if (isLeader) { queue.clear(); queue.start(); const nodeId = eventBus.getNodeId(); - log.info(`Node ${nodeId} is a leader, queue processing enabled`, 'DlManager') + log.info( + `Node ${nodeId} is a leader, queue processing enabled`, + "DlManager", + ); - await startSyncing(queue) + await startSyncing(queue); } - }) + }); - const enqueuePlayer = async playerId => { + const enqueuePlayer = async (playerId) => { await enqueue( - queue, TYPES.ACTIVE_PLAYERS, true, - {playerId, add: true}, - async () => enqueue(queue, TYPES.PLAYER_SCORES, true, {playerId}), + queue, + TYPES.ACTIVE_PLAYERS, + true, + { playerId, add: true }, + async () => enqueue(queue, TYPES.PLAYER_SCORES, true, { playerId }), ); - } + }; const pause = () => { - log.debug('Pause Dl Manager', 'DlManager'); + log.debug("Pause Dl Manager", "DlManager"); queue.clear(); queue.pause(); }; const start = () => { - log.debug('Unpause Dl Manager', 'DlManager'); + log.debug("Unpause Dl Manager", "DlManager"); queue.clear(); queue.start(); @@ -213,11 +306,11 @@ export default async () => { initialized = true; - log.info(`Download manager initialized`, 'DlManager'); + log.info(`Download manager initialized`, "DlManager"); return { start, pause, - enqueuePlayer - } -} \ No newline at end of file + enqueuePlayer, + }; +}; diff --git a/src/network/errors.js b/src/network/errors.js index 645aa58..66aea9b 100644 --- a/src/network/errors.js +++ b/src/network/errors.js @@ -1,6 +1,6 @@ -import {SsrError} from '../others/errors' -import {delay} from '../utils/promise' -import {parseRateLimitHeaders} from './utils' +import { SsrError } from "../others/errors"; +import { delay } from "../utils/promise"; +import { parseRateLimitHeaders } from "./utils"; export class SsrNetworkError extends SsrError { constructor(message) { @@ -20,7 +20,7 @@ export class SsrNetworkError extends SsrError { export class SsrNetworkTimeoutError extends SsrNetworkError { constructor(timeout, message) { - super(message && message.length ? message : `Timeout Error (${timeout}ms)`) + super(message && message.length ? message : `Timeout Error (${timeout}ms)`); this.name = "SsrNetworkTimeoutError"; this.timeout = timeout; @@ -29,12 +29,17 @@ export class SsrNetworkTimeoutError extends SsrNetworkError { export class SsrHttpResponseError extends SsrNetworkError { constructor(response, ...args) { - super(`HTTP Error Response: ${response && response.status ? response.status : 'None'} ${response && response.statusText ? response.statusText : ''}`, ...args); + super( + `HTTP Error Response: ${ + response && response.status ? response.status : "None" + } ${response && response.statusText ? response.statusText : ""}`, + ...args, + ); - this.name = 'SsrHttpResponseError'; + this.name = "SsrHttpResponseError"; this.response = response; - const {remaining, limit, resetAt} = parseRateLimitHeaders(response); + const { remaining, limit, resetAt } = parseRateLimitHeaders(response); this.remaining = remaining; this.limit = limit; @@ -50,7 +55,7 @@ export class SsrHttpClientError extends SsrHttpResponseError { constructor(...args) { super(...args); - this.name = 'SsrHttpClientError'; + this.name = "SsrHttpClientError"; } shouldRetry() { @@ -66,7 +71,7 @@ export class SsrHttpRateLimitError extends SsrHttpClientError { constructor(response, ...args) { super(response, ...args); - this.name = 'SsrHttpRateLimitError'; + this.name = "SsrHttpRateLimitError"; } shouldRetry() { @@ -119,6 +124,6 @@ export class SsrHttpServerError extends SsrHttpResponseError { constructor(...args) { super(...args); - this.name = 'SsrHttpServerError'; + this.name = "SsrHttpServerError"; } -} \ No newline at end of file +} diff --git a/src/network/fetch.js b/src/network/fetch.js index e214f3f..a034a28 100644 --- a/src/network/fetch.js +++ b/src/network/fetch.js @@ -97,12 +97,12 @@ export async function fetchUrl(url, options = {}, cors = true) { export async function fetchJson( url, - { cacheTtl = null, maxAge = null, ...restOptions } = {} + { cacheTtl = null, maxAge = null, ...restOptions } = {}, ) { const options = getOptionsWithCacheKey( url, { cacheTtl, maxAge, ...restOptions }, - "json" + "json", ); const { @@ -129,7 +129,7 @@ export async function fetchJson( body, }, fetchCacheKey, - fetchCacheTtl + fetchCacheTtl, ); }) .catch((err) => { @@ -141,12 +141,12 @@ export async function fetchJson( export async function fetchHtml( url, - { cacheTtl = null, maxAge = null, ...restOptions } = {} + { cacheTtl = null, maxAge = null, ...restOptions } = {}, ) { const options = getOptionsWithCacheKey( url, { cacheTtl, maxAge, ...restOptions }, - "json" + "json", ); const { @@ -172,7 +172,7 @@ export async function fetchHtml( body: new DOMParser().parseFromString(body, "text/html"), }, fetchCacheKey, - fetchCacheTtl + fetchCacheTtl, ); }); } diff --git a/src/network/queues/accsaber/api-queue.js b/src/network/queues/accsaber/api-queue.js index cfe0fbe..e7ee0f9 100644 --- a/src/network/queues/accsaber/api-queue.js +++ b/src/network/queues/accsaber/api-queue.js @@ -1,25 +1,75 @@ -import {default as createQueue, PRIORITY} from '../http-queue'; -import {substituteVars} from "../../../utils/format"; +import { default as createQueue, PRIORITY } from "../http-queue"; +import { substituteVars } from "../../../utils/format"; -const ACCSABER_API_URL = 'https://api.accsaber.com'; -const CATEGORIES_URL = ACCSABER_API_URL + '/categories'; -const RANKING_URL = ACCSABER_API_URL + '/categories/${category}/standings'; -const PLAYER_SCORES_URL = ACCSABER_API_URL + '/players/${playerId}/scores'; -const PLAYER_RANK_HISTORY = ACCSABER_API_URL + '/players/${playerId}/recent-rank-history' -const LEADERBOARD_URL = ACCSABER_API_URL + '/map-leaderboards/${leaderboardId}'; -const LEADERBOARD_INFO_URL = ACCSABER_API_URL + '/ranked-maps/${leaderboardId}'; +const ACCSABER_API_URL = "https://api.accsaber.com"; +const CATEGORIES_URL = ACCSABER_API_URL + "/categories"; +const RANKING_URL = ACCSABER_API_URL + "/categories/${category}/standings"; +const PLAYER_SCORES_URL = ACCSABER_API_URL + "/players/${playerId}/scores"; +const PLAYER_RANK_HISTORY = + ACCSABER_API_URL + "/players/${playerId}/recent-rank-history"; +const LEADERBOARD_URL = ACCSABER_API_URL + "/map-leaderboards/${leaderboardId}"; +const LEADERBOARD_INFO_URL = ACCSABER_API_URL + "/ranked-maps/${leaderboardId}"; export default (options = {}) => { const queue = createQueue(options); - const {fetchJson, fetchHtml, ...queueToReturn} = queue; + const { fetchJson, fetchHtml, ...queueToReturn } = queue; - const categories = async (priority = PRIORITY.FG_LOW, options = {}) => fetchJson(CATEGORIES_URL, options, priority) - const ranking = async (category = 'overall', page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(RANKING_URL, {category, page}), options, priority) - const scores = async (playerId, page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(PLAYER_SCORES_URL, {playerId, page}), options, priority) - const playerRankHistory = async (playerId, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(PLAYER_RANK_HISTORY, {playerId}), options, priority) - const leaderboard = async (leaderboardId, page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(LEADERBOARD_URL, {leaderboardId, page}), options, priority) - const leaderboardInfo = async (leaderboardId, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(LEADERBOARD_INFO_URL, {leaderboardId}), options, priority) + const categories = async (priority = PRIORITY.FG_LOW, options = {}) => + fetchJson(CATEGORIES_URL, options, priority); + const ranking = async ( + category = "overall", + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(RANKING_URL, { category, page }), + options, + priority, + ); + const scores = async ( + playerId, + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(PLAYER_SCORES_URL, { playerId, page }), + options, + priority, + ); + const playerRankHistory = async ( + playerId, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(PLAYER_RANK_HISTORY, { playerId }), + options, + priority, + ); + const leaderboard = async ( + leaderboardId, + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(LEADERBOARD_URL, { leaderboardId, page }), + options, + priority, + ); + const leaderboardInfo = async ( + leaderboardId, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(LEADERBOARD_INFO_URL, { leaderboardId }), + options, + priority, + ); return { categories, @@ -29,5 +79,5 @@ export default (options = {}) => { leaderboard, leaderboardInfo, ...queueToReturn, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/queues/beatmaps/api-queue.js b/src/network/queues/beatmaps/api-queue.js index 98a5630..5ab9f66 100644 --- a/src/network/queues/beatmaps/api-queue.js +++ b/src/network/queues/beatmaps/api-queue.js @@ -1,21 +1,23 @@ -import {default as createQueue, PRIORITY} from '../http-queue'; -import {substituteVars} from "../../../utils/format"; +import { default as createQueue, PRIORITY } from "../http-queue"; +import { substituteVars } from "../../../utils/format"; -const BEATMAPS_API_URL = 'https://api.beatsaver.com/'; -const SONG_BY_HASH_URL = BEATMAPS_API_URL + '/maps/hash/${hash}'; -const SONG_BY_KEY_URL = BEATMAPS_API_URL + '/maps/id/${key}' +const BEATMAPS_API_URL = "https://api.beatsaver.com/"; +const SONG_BY_HASH_URL = BEATMAPS_API_URL + "/maps/hash/${hash}"; +const SONG_BY_KEY_URL = BEATMAPS_API_URL + "/maps/id/${key}"; export default (options = {}) => { const queue = createQueue(options); - const {fetchJson, fetchHtml, ...queueToReturn} = queue; + const { fetchJson, fetchHtml, ...queueToReturn } = queue; - const byHash = async (hash, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(SONG_BY_HASH_URL, {hash}), options, priority) - const byKey = async (key, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(SONG_BY_KEY_URL, {key}), options, priority) + const byHash = async (hash, priority = PRIORITY.FG_LOW, options = {}) => + fetchJson(substituteVars(SONG_BY_HASH_URL, { hash }), options, priority); + const byKey = async (key, priority = PRIORITY.FG_LOW, options = {}) => + fetchJson(substituteVars(SONG_BY_KEY_URL, { key }), options, priority); return { byHash, byKey, ...queueToReturn, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/queues/http-queue.js b/src/network/queues/http-queue.js index b8d7ab5..0f9214b 100644 --- a/src/network/queues/http-queue.js +++ b/src/network/queues/http-queue.js @@ -1,9 +1,17 @@ -import {default as createQueue, PRIORITY as QUEUE_PRIORITY} from '../../utils/queue'; -import {SsrError, SsrTimeoutError} from '../../others/errors' -import {SsrHttpRateLimitError, SsrHttpResponseError, SsrNetworkError, SsrNetworkTimeoutError} from '../errors' -import {fetchHtml, fetchJson} from '../fetch'; -import makePendingPromisePool from '../../utils/pending-promises' -import {AbortError} from '../../utils/promise' +import { + default as createQueue, + PRIORITY as QUEUE_PRIORITY, +} from "../../utils/queue"; +import { SsrError, SsrTimeoutError } from "../../others/errors"; +import { + SsrHttpRateLimitError, + SsrHttpResponseError, + SsrNetworkError, + SsrNetworkTimeoutError, +} from "../errors"; +import { fetchHtml, fetchJson } from "../fetch"; +import makePendingPromisePool from "../../utils/pending-promises"; +import { AbortError } from "../../utils/promise"; const DEFAULT_RETRIES = 2; @@ -13,65 +21,91 @@ export const PRIORITY = { BG_HIGH: QUEUE_PRIORITY.NORMAL, BG_NORMAL: QUEUE_PRIORITY.LOW, BG_LOW: QUEUE_PRIORITY.LOWEST, -} +}; const resolvePromiseOrWaitForPending = makePendingPromisePool(); export default (options = {}) => { - const {retries, rateLimitTick, ...queueOptions} = {retries: DEFAULT_RETRIES, rateLimitTick: 500, ...options}; + const { retries, rateLimitTick, ...queueOptions } = { + retries: DEFAULT_RETRIES, + rateLimitTick: 500, + ...options, + }; const queue = createQueue(queueOptions); - const {add, emitter, ...queueToReturn} = queue; + const { add, emitter, ...queueToReturn } = queue; let lastRateLimitError = null; let rateLimitTimerId = null; - let currentRateLimit = {waiting: 0, remaining: null, limit: null, resetAt: null}; + let currentRateLimit = { + waiting: 0, + remaining: null, + limit: null, + resetAt: null, + }; const rateLimitTicker = () => { - const expiresInMs = lastRateLimitError && lastRateLimitError.resetAt ? lastRateLimitError.resetAt - new Date() + 1000 : 0; + const expiresInMs = + lastRateLimitError && lastRateLimitError.resetAt + ? lastRateLimitError.resetAt - new Date() + 1000 + : 0; if (expiresInMs <= 0) { - emitter.emit('waiting', {waiting: 0, remaining: null, limit: null, resetAt: null}); + emitter.emit("waiting", { + waiting: 0, + remaining: null, + limit: null, + resetAt: null, + }); if (rateLimitTimerId) clearTimeout(rateLimitTimerId); return; } - const {remaining, limit, resetAt} = lastRateLimitError; - emitter.emit('waiting', {waiting: expiresInMs, remaining, limit, resetAt}); + const { remaining, limit, resetAt } = lastRateLimitError; + emitter.emit("waiting", { + waiting: expiresInMs, + remaining, + limit, + resetAt, + }); if (rateLimitTimerId) clearTimeout(rateLimitTimerId); rateLimitTimerId = setTimeout(rateLimitTicker, rateLimitTick); - } + }; - const retriedFetch = async (fetchFunc, url, options, priority = PRIORITY.FG_LOW) => { + const retriedFetch = async ( + fetchFunc, + url, + options, + priority = PRIORITY.FG_LOW, + ) => { for (let i = 0; i <= retries; i++) { try { return await add(async () => { - if (lastRateLimitError) { - await lastRateLimitError.waitBeforeRetry(); + if (lastRateLimitError) { + await lastRateLimitError.waitBeforeRetry(); - lastRateLimitError = null; - } + lastRateLimitError = null; + } - return fetchFunc(url, options) - .then(response => { - currentRateLimit = {...response.rateLimit, waiting: 0}; + return fetchFunc(url, options) + .then((response) => { + currentRateLimit = { ...response.rateLimit, waiting: 0 }; - return response; - }) - .catch(err => { - if (err instanceof SsrTimeoutError) throw new SsrNetworkTimeoutError(err.timeout); + return response; + }) + .catch((err) => { + if (err instanceof SsrTimeoutError) + throw new SsrNetworkTimeoutError(err.timeout); - throw err; - }) - }, - priority, - ) + throw err; + }); + }, priority); } catch (err) { if (err instanceof SsrHttpResponseError) { - const {remaining, limit, resetAt} = err; - currentRateLimit = {waiting: 0, remaining, limit, resetAt}; + const { remaining, limit, resetAt } = err; + currentRateLimit = { waiting: 0, remaining, limit, resetAt }; } if (err instanceof SsrNetworkError) { @@ -79,7 +113,13 @@ export default (options = {}) => { if (!shouldRetry || i === retries) throw err; if (err instanceof SsrHttpRateLimitError) { - if (err.remaining <= 0 && err.resetAt && (!lastRateLimitError || !lastRateLimitError.resetAt || lastRateLimitError.resetAt < err.resetAt)) { + if ( + err.remaining <= 0 && + err.resetAt && + (!lastRateLimitError || + !lastRateLimitError.resetAt || + lastRateLimitError.resetAt < err.resetAt) + ) { lastRateLimitError = err; rateLimitTicker(); @@ -95,11 +135,17 @@ export default (options = {}) => { } } - throw new SsrError('Unknown error'); - } + throw new SsrError("Unknown error"); + }; - const queuedFetchJson = async (url, options, priority = PRIORITY.FG_LOW) => resolvePromiseOrWaitForPending(url, () => retriedFetch(fetchJson, url, options, priority)); - const queuedFetchHtml = async (url, options, priority = PRIORITY.FG_LOW) => resolvePromiseOrWaitForPending(url, () => retriedFetch(fetchHtml, url, options, priority)); + const queuedFetchJson = async (url, options, priority = PRIORITY.FG_LOW) => + resolvePromiseOrWaitForPending(url, () => + retriedFetch(fetchJson, url, options, priority), + ); + const queuedFetchHtml = async (url, options, priority = PRIORITY.FG_LOW) => + resolvePromiseOrWaitForPending(url, () => + retriedFetch(fetchHtml, url, options, priority), + ); const getRateLimit = () => currentRateLimit; @@ -108,5 +154,5 @@ export default (options = {}) => { fetchHtml: queuedFetchHtml, getRateLimit, ...queueToReturn, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/queues/queues.js b/src/network/queues/queues.js index 37506fb..7ffa958 100644 --- a/src/network/queues/queues.js +++ b/src/network/queues/queues.js @@ -1,55 +1,99 @@ -import {writable} from 'svelte/store' -import {PRIORITY} from './http-queue' -import createScoreSaberApiQueue from './scoresaber/api-queue' -import createScoreSaberPageQueue from './scoresaber/page-queue' -import createBeatMapsApiQueue from './beatmaps/api-queue' -import createBeatSaviorApiQueue from './beatsavior/api-queue' -import createTwitchApiQueue from './twitch/api-queue' -import createAccSaberApiQueue from './accsaber/api-queue' +import { writable } from "svelte/store"; +import { PRIORITY } from "./http-queue"; +import createScoreSaberApiQueue from "./scoresaber/api-queue"; +import createScoreSaberPageQueue from "./scoresaber/page-queue"; +import createBeatMapsApiQueue from "./beatmaps/api-queue"; +import createBeatSaviorApiQueue from "./beatsavior/api-queue"; +import createTwitchApiQueue from "./twitch/api-queue"; +import createAccSaberApiQueue from "./accsaber/api-queue"; -export const getResponseBody = response => response ? response.body : null; -export const isResponseCached = response => !!(response && response.cached) -export const updateResponseBody = (response, body) => response ? {...response, body} : null; +export const getResponseBody = (response) => (response ? response.body : null); +export const isResponseCached = (response) => !!(response && response.cached); +export const updateResponseBody = (response, body) => + response ? { ...response, body } : null; -const initQueue = queue => { +const initQueue = (queue) => { let queueState = { size: 0, pending: 0, - rateLimit: {waiting: 0, remaining: null, limit: null, resetAt: null}, - progress: {num: 0, count: 0, progress: 1}, + rateLimit: { waiting: 0, remaining: null, limit: null, resetAt: null }, + progress: { num: 0, count: 0, progress: 1 }, }; - const {subscribe, set} = writable(queueState); + const { subscribe, set } = writable(queueState); - queue.on('change', ({size, pending}) => { - const {rateLimit: {waiting}} = queueState; - const {remaining, limit, resetAt} = queue.getRateLimit(); - queueState = {...queueState, size, pending, rateLimit: {waiting, remaining, limit, resetAt}}; + queue.on("change", ({ size, pending }) => { + const { + rateLimit: { waiting }, + } = queueState; + const { remaining, limit, resetAt } = queue.getRateLimit(); + queueState = { + ...queueState, + size, + pending, + rateLimit: { waiting, remaining, limit, resetAt }, + }; set(queueState); }); - queue.on('progress', ({progress, num, count}) => { - const {rateLimit: {waiting}} = queueState; - const {remaining, limit, resetAt} = queue.getRateLimit(); - queueState = {...queueState, progress: {num, count, progress}, rateLimit: {waiting, remaining, limit, resetAt}} + queue.on("progress", ({ progress, num, count }) => { + const { + rateLimit: { waiting }, + } = queueState; + const { remaining, limit, resetAt } = queue.getRateLimit(); + queueState = { + ...queueState, + progress: { num, count, progress }, + rateLimit: { waiting, remaining, limit, resetAt }, + }; set(queueState); }); - queue.on('waiting', ({waiting, remaining, limit, resetAt}) => { - queueState = {...queueState, rateLimit: {waiting, remaining, limit, resetAt}} + queue.on("waiting", ({ waiting, remaining, limit, resetAt }) => { + queueState = { + ...queueState, + rateLimit: { waiting, remaining, limit, resetAt }, + }; set(queueState); - }) + }); return { subscribe, ...queue, - } -} + }; +}; export default { - SCORESABER_API: initQueue(createScoreSaberApiQueue({concurrency: 3, timeout: 95000})), - SCORESABER_PAGE: initQueue(createScoreSaberPageQueue({concurrency: 3, timeout: 30000})), - BEATMAPS: initQueue(createBeatMapsApiQueue({concurrency: 1, timeout: 10000, intervalCap: 10, interval: 1000})), - BEATSAVIOR: initQueue(createBeatSaviorApiQueue({concurrency: 1, timeout: 10000, intervalCap: 60, interval: 60000})), - TWITCH: initQueue(createTwitchApiQueue({concurrency: 8, timeout: 8000, intervalCap: 800, interval: 60000})), - ACCSABER: initQueue(createAccSaberApiQueue({concurrency: 2, timeout: 10000})), + SCORESABER_API: initQueue( + createScoreSaberApiQueue({ concurrency: 3, timeout: 95000 }), + ), + SCORESABER_PAGE: initQueue( + createScoreSaberPageQueue({ concurrency: 3, timeout: 30000 }), + ), + BEATMAPS: initQueue( + createBeatMapsApiQueue({ + concurrency: 1, + timeout: 10000, + intervalCap: 10, + interval: 1000, + }), + ), + BEATSAVIOR: initQueue( + createBeatSaviorApiQueue({ + concurrency: 1, + timeout: 10000, + intervalCap: 60, + interval: 60000, + }), + ), + TWITCH: initQueue( + createTwitchApiQueue({ + concurrency: 8, + timeout: 8000, + intervalCap: 800, + interval: 60000, + }), + ), + ACCSABER: initQueue( + createAccSaberApiQueue({ concurrency: 2, timeout: 10000 }), + ), PRIORITY, -} \ No newline at end of file +}; diff --git a/src/network/queues/scoresaber/api-queue.js b/src/network/queues/scoresaber/api-queue.js index 97ef174..b400532 100644 --- a/src/network/queues/scoresaber/api-queue.js +++ b/src/network/queues/scoresaber/api-queue.js @@ -1,35 +1,79 @@ -import {default as createQueue, PRIORITY} from '../http-queue'; -import {substituteVars} from '../../../utils/format' -import {PLAYER_SCORES_PER_PAGE, PLAYERS_PER_PAGE} from '../../../utils/scoresaber/consts' +import { default as createQueue, PRIORITY } from "../http-queue"; +import { substituteVars } from "../../../utils/format"; +import { + PLAYER_SCORES_PER_PAGE, + PLAYERS_PER_PAGE, +} from "../../../utils/scoresaber/consts"; -export const SS_API_HOST = 'https://new.scoresaber.com'; +export const SS_API_HOST = "https://new.scoresaber.com"; export const SS_API_URL = `${SS_API_HOST}/api`; -export const SS_API_PLAYER_INFO_URL = SS_API_URL + '/player/${playerId}/full'; -export const SS_API_RECENT_SCORES_URL = SS_API_URL + '/player/${playerId}/scores/recent/${page}'; -export const SS_API_TOP_SCORES_URL = SS_API_URL + '/player/${playerId}/scores/top/${page}'; -export const SS_API_FIND_PLAYER_URL = SS_API_URL + '/players/by-name/${query}' -export const SS_API_RANKING_GLOBAL_URL = SS_API_URL + '/players/${page}' -export const SS_API_RANKING_GLOBAL_PAGES_URL = SS_API_URL + '/players/pages' +export const SS_API_PLAYER_INFO_URL = SS_API_URL + "/player/${playerId}/full"; +export const SS_API_RECENT_SCORES_URL = + SS_API_URL + "/player/${playerId}/scores/recent/${page}"; +export const SS_API_TOP_SCORES_URL = + SS_API_URL + "/player/${playerId}/scores/top/${page}"; +export const SS_API_FIND_PLAYER_URL = SS_API_URL + "/players/by-name/${query}"; +export const SS_API_RANKING_GLOBAL_URL = SS_API_URL + "/players/${page}"; +export const SS_API_RANKING_GLOBAL_PAGES_URL = SS_API_URL + "/players/pages"; export default (options = {}) => { const queue = createQueue(options); - const {fetchJson, fetchHtml, ...queueToReturn} = queue; + const { fetchJson, fetchHtml, ...queueToReturn } = queue; - const fetchScores = async (baseUrl, playerId, page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(baseUrl, {playerId, page}), options, priority); + const fetchScores = async ( + baseUrl, + playerId, + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson(substituteVars(baseUrl, { playerId, page }), options, priority); - const player = async (playerId, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(SS_API_PLAYER_INFO_URL, {playerId}), options, priority); + const player = async (playerId, priority = PRIORITY.FG_LOW, options = {}) => + fetchJson( + substituteVars(SS_API_PLAYER_INFO_URL, { playerId }), + options, + priority, + ); - const recentScores = async (playerId, page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchScores(SS_API_RECENT_SCORES_URL, playerId, page, priority, options); + const recentScores = async ( + playerId, + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => fetchScores(SS_API_RECENT_SCORES_URL, playerId, page, priority, options); - const topScores = async (playerId, page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchScores(SS_API_TOP_SCORES_URL, playerId, page, priority, options); + const topScores = async ( + playerId, + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => fetchScores(SS_API_TOP_SCORES_URL, playerId, page, priority, options); - const findPlayer = async (query, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(SS_API_FIND_PLAYER_URL, {query: encodeURIComponent(query)}), options, priority); + const findPlayer = async (query, priority = PRIORITY.FG_LOW, options = {}) => + fetchJson( + substituteVars(SS_API_FIND_PLAYER_URL, { + query: encodeURIComponent(query), + }), + options, + priority, + ); - const rankingGlobal = async (page = 1, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(substituteVars(SS_API_RANKING_GLOBAL_URL, {page}), options, priority); + const rankingGlobal = async ( + page = 1, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + substituteVars(SS_API_RANKING_GLOBAL_URL, { page }), + options, + priority, + ); - const rankingGlobalPages = async (priority = PRIORITY.FG_LOW, options = {}) => fetchJson(SS_API_RANKING_GLOBAL_PAGES_URL, options, priority); + const rankingGlobalPages = async (priority = PRIORITY.FG_LOW, options = {}) => + fetchJson(SS_API_RANKING_GLOBAL_PAGES_URL, options, priority); return { player, @@ -42,5 +86,5 @@ export default (options = {}) => { PLAYER_SCORES_PER_PAGE, PLAYERS_PER_PAGE, ...queueToReturn, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/queues/scoresaber/page-queue.js b/src/network/queues/scoresaber/page-queue.js index ed097e5..b7104ea 100644 --- a/src/network/queues/scoresaber/page-queue.js +++ b/src/network/queues/scoresaber/page-queue.js @@ -24,7 +24,7 @@ export const parseSsInt = (text) => { export const parseSsFloat = (text) => text ? parseFloat( - getFirstRegexpMatch(/([0-9,.]+)\s*$/, text.replace(/[^\d.]/g, "")) + getFirstRegexpMatch(/([0-9,.]+)\s*$/, text.replace(/[^\d.]/g, "")), ) : null; @@ -78,32 +78,32 @@ export default (options = {}) => { const rankeds = async ( page = 1, priority = PRIORITY.BG_NORMAL, - options = {} + options = {}, ) => fetchJson(substituteVars(RANKEDS_URL, { page }), options, priority).then( (r) => { r.body = processRankeds(r.body); return r; - } + }, ); const processPlayerProfile = (playerId, doc) => { cfDecryptEmail(doc); let avatar = getImgUrl( - opt(doc.querySelector(".column.avatar img"), "src", null) + opt(doc.querySelector(".column.avatar img"), "src", null), ); let playerName = opt( doc.querySelector(".content .column:not(.avatar) .title a"), - "innerText" + "innerText", ); playerName = playerName ? playerName.trim() : null; let country = getFirstRegexpMatch( /^.*?\/flags\/([^.]+)\..*$/, - opt(doc.querySelector(".content .column .title img"), "src") + opt(doc.querySelector(".content .column .title img"), "src"), ); country = country ? country.toUpperCase() : null; @@ -111,8 +111,8 @@ export default (options = {}) => { opt( doc.querySelector(".pagination .pagination-list li a.is-current"), "innerText", - null - ) + null, + ), ); pageNum = !isNaN(pageNum) ? pageNum : null; @@ -120,8 +120,8 @@ export default (options = {}) => { opt( doc.querySelector(".pagination .pagination-list li:last-of-type"), "innerText", - null - ) + null, + ), ); pageQty = !isNaN(pageQty) ? pageQty : null; @@ -130,31 +130,31 @@ export default (options = {}) => { /^\s*(?:[^:]+)\s*:?\s*<\/strong>\s*(.*)$/, opt( doc.querySelector( - ".columns .column:not(.is-narrow) ul li:nth-of-type(3)" + ".columns .column:not(.is-narrow) ul li:nth-of-type(3)", ), - "innerHTML" - ) - ) + "innerHTML", + ), + ), ); totalItems = !isNaN(totalItems) ? totalItems : 0; let playerRank = parseSsInt( opt( doc.querySelector( - ".content .column ul li:first-of-type a:first-of-type" + ".content .column ul li:first-of-type a:first-of-type", ), - "innerText" - ) + "innerText", + ), ); playerRank = !isNaN(playerRank) ? playerRank : null; let countryRank = parseSsInt( opt( doc.querySelector( - '.content .column ul li:first-of-type a[href^="/global?country="]' + '.content .column ul li:first-of-type a[href^="/global?country="]', ), - "innerText" - ) + "innerText", + ), ); countryRank = !isNaN(countryRank) ? countryRank : null; @@ -170,7 +170,7 @@ export default (options = {}) => { [...doc.querySelectorAll(".content .column ul li")] .map((li) => { const matches = li.innerHTML.match( - /^\s*([^:]+)\s*:?\s*<\/strong>\s*(.*)$/ + /^\s*([^:]+)\s*:?\s*<\/strong>\s*(.*)$/, ); if (!matches) return null; @@ -219,7 +219,7 @@ export default (options = {}) => { const item = mapping.find((m) => m.key === matches[1]); return item ? { ...item, value } : { label: matches[1], value }; }) - .filter((s) => s) + .filter((s) => s), ) .reduce( (cum, item) => { @@ -255,7 +255,7 @@ export default (options = {}) => { return cum; }, - { inactiveAccount: false, bannedAccount: false } + { inactiveAccount: false, bannedAccount: false }, ); const scores = [...doc.querySelectorAll("table.ranking tbody tr")].map( @@ -274,7 +274,7 @@ export default (options = {}) => { if (song) { const leaderboardId = parseInt( getFirstRegexpMatch(/leaderboard\/(\d+)/, song.href), - 10 + 10, ); ret.leaderboardId = leaderboardId ? leaderboardId : null; } else { @@ -293,7 +293,7 @@ export default (options = {}) => { .replace(/&/g, "&") .replace( /\[email protected]<\/span>/g, - "" + "", ) .match(/^(.*?)\s*]+>(.*?)<\/span>/) : null; @@ -328,7 +328,7 @@ export default (options = {}) => { ret.timeSet = songDate ? dateFromString(songDate.title) : null; const pp = parseSsFloat( - opt(tr.querySelector("th.score .scoreTop.ppValue"), "innerText") + opt(tr.querySelector("th.score .scoreTop.ppValue"), "innerText"), ); ret.pp = !isNaN(pp) ? pp : null; @@ -337,9 +337,9 @@ export default (options = {}) => { /^\(([0-9.]+)pp\)$/, opt( tr.querySelector("th.score .scoreTop.ppWeightedValue"), - "innerText" - ) - ) + "innerText", + ), + ), ); ret.ppWeighted = !isNaN(ppWeighted) ? ppWeighted : null; @@ -380,7 +380,7 @@ export default (options = {}) => { } return ret; - } + }, ); const recentPlay = scores && scores.length && scores[0].timeSet ? scores[0].timeSet : null; @@ -394,18 +394,18 @@ export default (options = {}) => { externalProfileUrl: opt( doc.querySelector(".content .column:not(.avatar) .title a"), "href", - null + null, ), history: getFirstRegexpMatch( /data:\s*\[([0-9,]+)\]/, - doc.body.innerHTML + doc.body.innerHTML, ), country, badges: [...doc.querySelectorAll(".column.avatar center img")].map( (img) => ({ image: getImgUrl(img.src), description: img.title, - }) + }), ), rank: stats.rank ? stats.rank : null, countryRank: stats.countryRank ? stats.countryRank : null, @@ -435,7 +435,7 @@ export default (options = {}) => { fetchHtml( substituteVars(PLAYER_PROFILE_URL, { playerId }), options, - priority + priority, ).then((r) => { r.body = processPlayerProfile(playerId, r.body); @@ -451,17 +451,17 @@ export default (options = {}) => { const id = getFirstRegexpMatch(/\/(\d+)$/, a.href); const avatar = getImgUrl( - opt(tr.querySelector("td.picture img"), "src", null) + opt(tr.querySelector("td.picture img"), "src", null), ); let country = getFirstRegexpMatch( /^.*?\/flags\/([^.]+)\..*$/, - opt(tr.querySelector("td.player img"), "src", null) + opt(tr.querySelector("td.player img"), "src", null), ); country = country ? country.toUpperCase() : null; let difference = parseSsInt( - opt(tr.querySelector("td.diff"), "innerText", null) + opt(tr.querySelector("td.diff"), "innerText", null), ); difference = !isNaN(difference) ? difference : null; @@ -469,15 +469,15 @@ export default (options = {}) => { playerName = playerName || playerName === "" ? playerName.trim() : null; let pp = parseSsFloat( - opt(tr.querySelector("td.pp .scoreTop.ppValue"), "innerText") + opt(tr.querySelector("td.pp .scoreTop.ppValue"), "innerText"), ); pp = !isNaN(pp) ? pp : null; let rank = parseSsInt( getFirstRegexpMatch( /^\s*#(\d+)\s*$/, - opt(tr.querySelector("td.rank"), "innerText", null) - ) + opt(tr.querySelector("td.rank"), "innerText", null), + ), ); rank = !isNaN(rank) ? rank : null; @@ -491,7 +491,7 @@ export default (options = {}) => { pp, rank, }; - } + }, ); return { players: data }; @@ -501,12 +501,12 @@ export default (options = {}) => { country, page = 1, priority = PRIORITY.FG_LOW, - options = {} + options = {}, ) => fetchHtml( substituteVars(COUNTRY_RANKING_URL, { country, page }), options, - priority + priority, ).then((r) => { r.body = processCountryRanking(country, r.body); @@ -529,11 +529,11 @@ export default (options = {}) => { }; ret.player.playerInfo.avatar = getImgUrl( - opt(tr.querySelector(".picture img"), "src", null) + opt(tr.querySelector(".picture img"), "src", null), ); ret.score.rank = parseSsInt( - opt(tr.querySelector("td.rank"), "innerText") + opt(tr.querySelector("td.rank"), "innerText"), ); if (isNaN(ret.score.rank)) ret.score.rank = null; @@ -541,7 +541,7 @@ export default (options = {}) => { if (player) { let country = getFirstRegexpMatch( /^.*?\/flags\/([^.]+)\..*$/, - opt(player.querySelector("img"), "src", "") + opt(player.querySelector("img"), "src", ""), ); country = country ? country.toUpperCase() : null; if (country) { @@ -551,14 +551,14 @@ export default (options = {}) => { ret.player.name = opt( player.querySelector("span.songTop.pp"), - "innerText" + "innerText", ); ret.player.name = ret.player.name ? ret.player.name.trim().replace("'", "'") : null; ret.player.playerId = getFirstRegexpMatch( /\/u\/(\d+)((\?|&|#).*)?$/, - opt(player, "href", "") + opt(player, "href", ""), ); ret.player.playerId = ret.player.playerId ? ret.player.playerId.trim() @@ -574,7 +574,7 @@ export default (options = {}) => { ret.score.timeSetString = opt( tr.querySelector("td.timeset"), "innerText", - null + null, ); if (ret.score.timeSetString) ret.score.timeSetString = ret.score.timeSetString.trim(); @@ -602,7 +602,7 @@ export default (options = {}) => { const diffs = [...doc.querySelectorAll(".tabs ul li a")].map((a) => { let leaderboardId = parseInt( getFirstRegexpMatch(/leaderboard\/(\d+)$/, a.href), - 10 + 10, ); if (isNaN(leaderboardId)) leaderboardId = null; @@ -615,7 +615,7 @@ export default (options = {}) => { const currentDiffHuman = opt( doc.querySelector(".tabs li.is-active a span"), "innerText", - null + null, ); let diff = null; @@ -628,20 +628,20 @@ export default (options = {}) => { const songName = opt( doc.querySelector( - ".column.is-one-third-desktop .box:first-of-type .title a" + ".column.is-one-third-desktop .box:first-of-type .title a", ), "innerText", - null + null, ); const imageUrl = getImgUrl( opt( doc.querySelector( - ".column.is-one-third-desktop .box:first-of-type .columns .column.is-one-quarter img" + ".column.is-one-third-desktop .box:first-of-type .columns .column.is-one-quarter img", ), "src", - null - ) + null, + ), ); const songInfo = [ @@ -656,13 +656,13 @@ export default (options = {}) => { ] .map((sid) => { let songInfoBox = doc.querySelector( - ".column.is-one-third-desktop .box:first-of-type" + ".column.is-one-third-desktop .box:first-of-type", ); return { ...sid, value: songInfoBox ? songInfoBox.innerHTML.match( - new RegExp(sid.label + ":\\s*(.*?)", "i") + new RegExp(sid.label + ":\\s*(.*?)", "i"), ) : null, }; @@ -708,7 +708,7 @@ export default (options = {}) => { return cum; }, - { imageUrl, stats: {} } + { imageUrl, stats: {} }, ); const { stats, ...song } = songInfo; @@ -718,9 +718,9 @@ export default (options = {}) => { opt( doc.querySelector(".pagination .pagination-list li:last-of-type"), "innerText", - null + null, ), - 10 + 10, ); if (isNaN(pageQty)) pageQty = null; @@ -736,7 +736,7 @@ export default (options = {}) => { let diffChartText = getFirstRegexpMatch( /'difficulty',\s*([0-9.,\s]+)\s*\]/, - doc.body.innerHTML + doc.body.innerHTML, ); let diffChart = (diffChartText ? diffChartText : "") .split(",") @@ -758,12 +758,12 @@ export default (options = {}) => { leaderboardId, page = 1, priority = PRIORITY.FG_LOW, - options = {} + options = {}, ) => fetchHtml( substituteVars(LEADERBOARD_URL, { leaderboardId, page }), options, - priority + priority, ).then((r) => { r.body = processLeaderboard(leaderboardId, page, r.body); diff --git a/src/network/queues/twitch/api-queue.js b/src/network/queues/twitch/api-queue.js index 7aa69df..bd495f7 100644 --- a/src/network/queues/twitch/api-queue.js +++ b/src/network/queues/twitch/api-queue.js @@ -1,44 +1,104 @@ -import {default as createQueue, PRIORITY} from '../http-queue'; -import ssrConfig from '../../../ssr-config' -import {substituteVars} from "../../../utils/format"; +import { default as createQueue, PRIORITY } from "../http-queue"; +import ssrConfig from "../../../ssr-config"; +import { substituteVars } from "../../../utils/format"; -const CLIENT_ID = 'u0swxz56n4iumc634at1osoqdk31qt'; +const CLIENT_ID = "u0swxz56n4iumc634at1osoqdk31qt"; -const TWITCH_AUTH_URL = 'https://id.twitch.tv/oauth2' -const AUTHORIZATION_URL = `${TWITCH_AUTH_URL}/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(ssrConfig.domain + '/twitch')}&response_type=token` + '&scope=${scopes}&state=${state}'; -const VALIDATE_URL = `${TWITCH_AUTH_URL}/validate` +const TWITCH_AUTH_URL = "https://id.twitch.tv/oauth2"; +const AUTHORIZATION_URL = + `${TWITCH_AUTH_URL}/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent( + ssrConfig.domain + "/twitch", + )}&response_type=token` + "&scope=${scopes}&state=${state}"; +const VALIDATE_URL = `${TWITCH_AUTH_URL}/validate`; -const TWITCH_API_URL = 'https://api.twitch.tv/helix'; -const PROFILE_URL = TWITCH_API_URL + '/users?login=${login}'; -const VIDEOS_URL = TWITCH_API_URL + '/videos?user_id=${userId}&type=${type}&first=100'; -const STREAMS_URL = TWITCH_API_URL + '/streams?user_id=${userId}'; +const TWITCH_API_URL = "https://api.twitch.tv/helix"; +const PROFILE_URL = TWITCH_API_URL + "/users?login=${login}"; +const VIDEOS_URL = + TWITCH_API_URL + "/videos?user_id=${userId}&type=${type}&first=100"; +const STREAMS_URL = TWITCH_API_URL + "/streams?user_id=${userId}"; export default (options = {}) => { const queue = createQueue(options); - const {fetchJson, fetchHtml, ...queueToReturn} = queue; + const { fetchJson, fetchHtml, ...queueToReturn } = queue; - const fetchApi = (url, accessToken, priority = PRIORITY.FG_LOW, options = {}) => fetchJson( + const fetchApi = ( url, - { - ...options, - headers: { - 'Client-ID': CLIENT_ID, - 'Authorization': `Bearer ${accessToken}` - } - }, - priority, - ) + accessToken, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + url, + { + ...options, + headers: { + "Client-ID": CLIENT_ID, + Authorization: `Bearer ${accessToken}`, + }, + }, + priority, + ); - const getAuthUrl = (state = '', scopes = '') => substituteVars(AUTHORIZATION_URL, {state: encodeURIComponent(state), scopes: encodeURIComponent(scopes)}); + const getAuthUrl = (state = "", scopes = "") => + substituteVars(AUTHORIZATION_URL, { + state: encodeURIComponent(state), + scopes: encodeURIComponent(scopes), + }); - const validateToken = async (accessToken, priority = PRIORITY.FG_LOW, options = {}) => fetchJson(VALIDATE_URL, {...options, headers: {'Authorization': `OAuth ${accessToken}`}}, priority) + const validateToken = async ( + accessToken, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchJson( + VALIDATE_URL, + { ...options, headers: { Authorization: `OAuth ${accessToken}` } }, + priority, + ); - const profile = async (accessToken, login, priority = PRIORITY.FG_LOW, options = {}) => fetchApi(substituteVars(PROFILE_URL, {login: encodeURIComponent(login)}), accessToken, priority, options) + const profile = async ( + accessToken, + login, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchApi( + substituteVars(PROFILE_URL, { login: encodeURIComponent(login) }), + accessToken, + priority, + options, + ); - const videos = async (accessToken, userId, type = 'archive', priority = PRIORITY.FG_LOW, options = {}) => fetchApi(substituteVars(VIDEOS_URL, {userId: encodeURIComponent(userId), type: encodeURIComponent(type)}), accessToken, priority, options) + const videos = async ( + accessToken, + userId, + type = "archive", + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchApi( + substituteVars(VIDEOS_URL, { + userId: encodeURIComponent(userId), + type: encodeURIComponent(type), + }), + accessToken, + priority, + options, + ); - const streams = async (accessToken, userId, priority = PRIORITY.FG_LOW, options = {}) => fetchApi(substituteVars(STREAMS_URL, {userId: encodeURIComponent(userId)}), accessToken, priority, options) + const streams = async ( + accessToken, + userId, + priority = PRIORITY.FG_LOW, + options = {}, + ) => + fetchApi( + substituteVars(STREAMS_URL, { userId: encodeURIComponent(userId) }), + accessToken, + priority, + options, + ); return { getAuthUrl, @@ -47,5 +107,5 @@ export default (options = {}) => { videos, streams, ...queueToReturn, - } -} \ No newline at end of file + }; +}; diff --git a/src/network/utils.js b/src/network/utils.js index d4618b2..7ad0a2f 100644 --- a/src/network/utils.js +++ b/src/network/utils.js @@ -1,13 +1,13 @@ -export const parseRateLimitHeaders = response => { +export const parseRateLimitHeaders = (response) => { if (!response || !response.headers) return null; - const remaining = parseInt(response.headers.get('x-ratelimit-remaining'), 10); - const limit = parseInt(response.headers.get('x-ratelimit-limit'), 10); - const resetAt = parseInt(response.headers.get('x-ratelimit-reset'), 10); + const remaining = parseInt(response.headers.get("x-ratelimit-remaining"), 10); + const limit = parseInt(response.headers.get("x-ratelimit-limit"), 10); + const resetAt = parseInt(response.headers.get("x-ratelimit-reset"), 10); return { remaining: !isNaN(remaining) ? remaining : null, limit: !isNaN(limit) ? limit : null, resetAt: !isNaN(resetAt) ? new Date(resetAt * 1000) : null, - } -} \ No newline at end of file + }; +}; diff --git a/src/others/errors.js b/src/others/errors.js index b8dbed5..2b13351 100644 --- a/src/others/errors.js +++ b/src/others/errors.js @@ -12,7 +12,7 @@ export class SsrError extends Error { export class SsrTimeoutError extends SsrError { constructor(timeout, message) { - super(message && message.length ? message : `Timeout Error (${timeout}ms)`) + super(message && message.length ? message : `Timeout Error (${timeout}ms)`); this.name = "SsrTimeoutError"; this.timeout = timeout; @@ -21,9 +21,9 @@ export class SsrTimeoutError extends SsrError { export class SsrDataFormatError extends SsrError { constructor(message, previous = null) { - super(message && message.length ? message : `Data format error`) + super(message && message.length ? message : `Data format error`); this.name = "SsrDataFormatError"; this.previous = previous; } -} \ No newline at end of file +} diff --git a/src/services/accsaber.js b/src/services/accsaber.js index e0c5c85..2096ede 100644 --- a/src/services/accsaber.js +++ b/src/services/accsaber.js @@ -1,35 +1,36 @@ -import {db} from '../db/db' -import queues from '../network/queues/queues'; -import accSaberCategoriesApiClient from '../network/clients/accsaber/api-categories'; -import accSaberRankingApiClient from '../network/clients/accsaber/api-ranking'; -import accSaberScoresApiClient from '../network/clients/accsaber/api-scores'; -import accSaberPlayerRankHistoryApiClient from '../network/clients/accsaber/api-player-rank-history'; -import accSaberCategoriesRepository from '../db/repository/accsaber-categories' -import accSaberPlayersRepository from '../db/repository/accsaber-players' -import accSaberPlayersHistoryRepository from '../db/repository/accsaber-players-history'; -import keyValueRepository from '../db/repository/key-value' -import createPlayerService from '../services/scoresaber/player'; -import {capitalize, convertArrayToObjectByKey} from '../utils/js' -import log from '../utils/logger' +import { db } from "../db/db"; +import queues from "../network/queues/queues"; +import accSaberCategoriesApiClient from "../network/clients/accsaber/api-categories"; +import accSaberRankingApiClient from "../network/clients/accsaber/api-ranking"; +import accSaberScoresApiClient from "../network/clients/accsaber/api-scores"; +import accSaberPlayerRankHistoryApiClient from "../network/clients/accsaber/api-player-rank-history"; +import accSaberCategoriesRepository from "../db/repository/accsaber-categories"; +import accSaberPlayersRepository from "../db/repository/accsaber-players"; +import accSaberPlayersHistoryRepository from "../db/repository/accsaber-players-history"; +import keyValueRepository from "../db/repository/key-value"; +import createPlayerService from "../services/scoresaber/player"; +import { capitalize, convertArrayToObjectByKey } from "../utils/js"; +import log from "../utils/logger"; import { addToDate, toAccSaberMidnight, formatDate, HOUR, MINUTE, - dateFromString, truncateDate, -} from '../utils/date' -import {PRIORITY} from '../network/queues/http-queue' -import makePendingPromisePool from '../utils/pending-promises' -import {getServicePlayerGain, serviceFilterFunc} from './utils' -import {PLAYER_SCORES_PER_PAGE} from '../utils/accsaber/consts' -import {roundToPrecision} from '../utils/format' + dateFromString, + truncateDate, +} from "../utils/date"; +import { PRIORITY } from "../network/queues/http-queue"; +import makePendingPromisePool from "../utils/pending-promises"; +import { getServicePlayerGain, serviceFilterFunc } from "./utils"; +import { PLAYER_SCORES_PER_PAGE } from "../utils/accsaber/consts"; +import { roundToPrecision } from "../utils/format"; const REFRESH_INTERVAL = HOUR; const SCORES_NETWORK_TTL = MINUTE * 5; const HISTOGRAM_AP_PRECISION = 5; -const CATEGORIES_ORDER = ['overall', 'true', 'standard', 'tech']; +const CATEGORIES_ORDER = ["overall", "true", "standard", "tech"]; let service = null; export default () => { @@ -40,61 +41,120 @@ export default () => { const resolvePromiseOrWaitForPending = makePendingPromisePool(); const getCategories = async () => { - const categories = await resolvePromiseOrWaitForPending(`accSaberCategories`, () => accSaberCategoriesRepository().getAll()); + const categories = await resolvePromiseOrWaitForPending( + `accSaberCategories`, + () => accSaberCategoriesRepository().getAll(), + ); - const getIdx = category => { - const idx = CATEGORIES_ORDER.findIndex(v => v === category?.name); + const getIdx = (category) => { + const idx = CATEGORIES_ORDER.findIndex((v) => v === category?.name); return idx >= 0 ? idx : 100000; - } - return categories.sort((a,b) => getIdx(a) - getIdx(b)); - } + }; + return categories.sort((a, b) => getIdx(a) - getIdx(b)); + }; - const getPlayer = async playerId => resolvePromiseOrWaitForPending(`accSaberPlayer/${playerId}`, () => accSaberPlayersRepository().getAllFromIndex('accsaber-players-playerId', playerId)); - const getRanking = async (category = 'overall') => accSaberPlayersRepository().getAllFromIndex('accsaber-players-category', category); - const getPlayerHistory = async playerId => resolvePromiseOrWaitForPending(`accSaberPlayerHistory/${playerId}`, () => accSaberPlayersHistoryRepository().getAllFromIndex('accsaber-players-history-playerId', playerId)) + const getPlayer = async (playerId) => + resolvePromiseOrWaitForPending(`accSaberPlayer/${playerId}`, () => + accSaberPlayersRepository().getAllFromIndex( + "accsaber-players-playerId", + playerId, + ), + ); + const getRanking = async (category = "overall") => + accSaberPlayersRepository().getAllFromIndex( + "accsaber-players-category", + category, + ); + const getPlayerHistory = async (playerId) => + resolvePromiseOrWaitForPending(`accSaberPlayerHistory/${playerId}`, () => + accSaberPlayersHistoryRepository().getAllFromIndex( + "accsaber-players-history-playerId", + playerId, + ), + ); - const isDataForPlayerAvailable = async playerId => (await Promise.all([getPlayer(playerId), getCategories()])).every(d => d?.length) + const isDataForPlayerAvailable = async (playerId) => + (await Promise.all([getPlayer(playerId), getCategories()])).every( + (d) => d?.length, + ); - const getPlayerGain = (playerHistory, daysAgo = 1, maxDaysAgo = 7) => getServicePlayerGain(playerHistory, toAccSaberMidnight, 'accSaberDate', daysAgo, maxDaysAgo); + const getPlayerGain = (playerHistory, daysAgo = 1, maxDaysAgo = 7) => + getServicePlayerGain( + playerHistory, + toAccSaberMidnight, + "accSaberDate", + daysAgo, + maxDaysAgo, + ); - const getLastUpdatedKey = type => `accSaber${capitalize(type)}LastUpdated`; - const getLastUpdated = async (type = 'all') => keyValueRepository().get(getLastUpdatedKey(type)); - const setLastUpdated = async (type = 'all', date) => keyValueRepository().set(date, getLastUpdatedKey(type)); + const getLastUpdatedKey = (type) => `accSaber${capitalize(type)}LastUpdated`; + const getLastUpdated = async (type = "all") => + keyValueRepository().get(getLastUpdatedKey(type)); + const setLastUpdated = async (type = "all", date) => + keyValueRepository().set(date, getLastUpdatedKey(type)); - const shouldRefresh = async (type = 'all', forceUpdate = false) => { + const shouldRefresh = async (type = "all", forceUpdate = false) => { if (!forceUpdate) { const lastUpdated = await getLastUpdated(type); if (lastUpdated && lastUpdated > new Date() - REFRESH_INTERVAL) { - log.debug(`Refresh interval for ${type} not yet expired, skipping. Next refresh on ${formatDate(addToDate(REFRESH_INTERVAL, lastUpdated))}`, 'AccSaberService') + log.debug( + `Refresh interval for ${type} not yet expired, skipping. Next refresh on ${formatDate( + addToDate(REFRESH_INTERVAL, lastUpdated), + )}`, + "AccSaberService", + ); return false; } } return true; - } + }; - const fetchScoresPage = async (playerId, page = 1, priority = PRIORITY.FG_LOW, {...options} = {}) => { + const fetchScoresPage = async ( + playerId, + page = 1, + priority = PRIORITY.FG_LOW, + { ...options } = {}, + ) => { if (!options) options = {}; - if (!options.hasOwnProperty('cacheTtl')) options.cacheTtl = SCORES_NETWORK_TTL; + if (!options.hasOwnProperty("cacheTtl")) + options.cacheTtl = SCORES_NETWORK_TTL; - const categoriesByDisplayName = convertArrayToObjectByKey(await getCategories(), 'displayName'); + const categoriesByDisplayName = convertArrayToObjectByKey( + await getCategories(), + "displayName", + ); - return (await resolvePromiseOrWaitForPending(`fetchPlayerScores/${playerId}/${page}`, () => accSaberScoresApiClient.getProcessed({...options, playerId, page, priority}))) - .map(s => ({ - ...s, - leaderboard: { - ...s?.leaderboard, - category: categoriesByDisplayName[s?.leaderboard?.categoryDisplayName]?.name ?? null, - } - })) - } + return ( + await resolvePromiseOrWaitForPending( + `fetchPlayerScores/${playerId}/${page}`, + () => + accSaberScoresApiClient.getProcessed({ + ...options, + playerId, + page, + priority, + }), + ) + ).map((s) => ({ + ...s, + leaderboard: { + ...s?.leaderboard, + category: + categoriesByDisplayName[s?.leaderboard?.categoryDisplayName]?.name ?? + null, + }, + })); + }; - const getScoresHistogramDefinition = (serviceParams = {type: 'overall', sort: 'ap', order: 'desc'}) => { - const scoreType = serviceParams?.type ?? 'overall'; - const sort = serviceParams?.sort ?? 'ap'; - const order = serviceParams?.order ?? 'desc'; + const getScoresHistogramDefinition = ( + serviceParams = { type: "overall", sort: "ap", order: "desc" }, + ) => { + const scoreType = serviceParams?.type ?? "overall"; + const sort = serviceParams?.sort ?? "ap"; + const order = serviceParams?.order ?? "desc"; const commonFilterFunc = serviceFilterFunc(serviceParams); @@ -104,68 +164,75 @@ export default () => { let maxBucketSize = null; let bucketSizeStep = null; let bucketSizeValues = null; - let type = 'linear'; - let valFunc = s => s; - let filterFunc = s => commonFilterFunc(s) && (scoreType === 'overall' || s?.leaderboard?.category === scoreType); - let histogramFilterFunc = s => s; - let roundedValFunc = (s, type = type, precision = bucketSize) => type === 'linear' - ? roundToPrecision(valFunc(s), precision) - : truncateDate(valFunc(s), precision); - let prefix = ''; - let prefixLong = ''; - let suffix = ''; - let suffixLong = ''; + let type = "linear"; + let valFunc = (s) => s; + let filterFunc = (s) => + commonFilterFunc(s) && + (scoreType === "overall" || s?.leaderboard?.category === scoreType); + let histogramFilterFunc = (s) => s; + let roundedValFunc = (s, type = type, precision = bucketSize) => + type === "linear" + ? roundToPrecision(valFunc(s), precision) + : truncateDate(valFunc(s), precision); + let prefix = ""; + let prefixLong = ""; + let suffix = ""; + let suffixLong = ""; - switch(sort) { - case 'ap': - valFunc = s => s?.ap; - type = 'linear'; + switch (sort) { + case "ap": + valFunc = (s) => s?.ap; + type = "linear"; bucketSize = HISTOGRAM_AP_PRECISION; minBucketSize = 1; maxBucketSize = 100; bucketSizeStep = 1; round = 0; - suffix = ' AP'; - suffixLong = ' AP'; + suffix = " AP"; + suffixLong = " AP"; break; - case 'recent': - valFunc = s => s?.timeSet; - type = 'time'; - bucketSize = 'day' + case "recent": + valFunc = (s) => s?.timeSet; + type = "time"; + bucketSize = "day"; break; - case 'acc': - valFunc = s => s?.acc; - type = 'linear'; + case "acc": + valFunc = (s) => s?.acc; + type = "linear"; bucketSize = 0.05; minBucketSize = 0.05; maxBucketSize = 1; bucketSizeStep = 0.05; round = 2; - suffix = '%'; - suffixLong = '%'; + suffix = "%"; + suffixLong = "%"; break; - case 'rank': - valFunc = s => s?.score?.rank; - type = 'linear'; + case "rank": + valFunc = (s) => s?.score?.rank; + type = "linear"; bucketSize = 5; minBucketSize = 1; maxBucketSize = 100; bucketSizeStep = 1; round = 0; - prefix = ''; - prefixLong = '#'; + prefix = ""; + prefixLong = "#"; break; } return { getValue: valFunc, - getRoundedValue: (bucketSize = bucketSize) => s => roundedValFunc(s, type, bucketSize), + getRoundedValue: + (bucketSize = bucketSize) => + (s) => + roundedValFunc(s, type, bucketSize), filter: filterFunc, histogramFilter: histogramFilterFunc, - sort: (a, b) => order === 'asc' ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), + sort: (a, b) => + order === "asc" ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), type, bucketSize, minBucketSize, @@ -177,164 +244,224 @@ export default () => { prefixLong, suffix, suffixLong, - order - } - } + order, + }; + }; - const getPlayerScores = async playerId => { + const getPlayerScores = async (playerId) => { try { return fetchScoresPage(playerId, 1); - } - catch (err) { + } catch (err) { return []; } - } + }; - const getPlayerScoresPage = async (playerId, serviceParams = {sort: 'recent', order: 'desc', page: 1}) => { + const getPlayerScoresPage = async ( + playerId, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + ) => { let page = serviceParams?.page ?? 1; if (page < 1) page = 1; let playerScores; try { playerScores = await fetchScoresPage(playerId, page); - } - catch (err) { - return {total: 0, scores: []}; + } catch (err) { + return { total: 0, scores: [] }; } - if (!playerScores?.length) return {total: 0, scores: []}; + if (!playerScores?.length) return { total: 0, scores: [] }; - const {sort: sortFunc, filter: filterFunc} = getScoresHistogramDefinition(serviceParams); + const { sort: sortFunc, filter: filterFunc } = + getScoresHistogramDefinition(serviceParams); - playerScores = playerScores.filter(filterFunc).sort(sortFunc) + playerScores = playerScores.filter(filterFunc).sort(sortFunc); const startIdx = (page - 1) * PLAYER_SCORES_PER_PAGE; - if (playerScores.length < startIdx + 1) return {total: 0, scores: []}; + if (playerScores.length < startIdx + 1) return { total: 0, scores: [] }; return { total: playerScores.length, itemsPerPage: PLAYER_SCORES_PER_PAGE, - scores: playerScores - .slice(startIdx, startIdx + PLAYER_SCORES_PER_PAGE) - } - } + scores: playerScores.slice(startIdx, startIdx + PLAYER_SCORES_PER_PAGE), + }; + }; - const fetchPlayerRankHistory = async (playerId, priority = PRIORITY.FG_LOW, {...options} = {}) => { + const fetchPlayerRankHistory = async ( + playerId, + priority = PRIORITY.FG_LOW, + { ...options } = {}, + ) => { if (!options) options = {}; - if (!options.hasOwnProperty('cacheTtl')) options.cacheTtl = SCORES_NETWORK_TTL; + if (!options.hasOwnProperty("cacheTtl")) + options.cacheTtl = SCORES_NETWORK_TTL; - return accSaberPlayerRankHistoryApiClient.getProcessed({...options, playerId, priority}); - } + return accSaberPlayerRankHistoryApiClient.getProcessed({ + ...options, + playerId, + priority, + }); + }; - const refreshCategories = async (forceUpdate = false, priority = queues.PRIORITY.BG_NORMAL, throwErrors = false) => { - log.debug(`Starting AccSaber categories refreshing${forceUpdate ? ' (forced)' : ''}...`, 'AccSaberService') + const refreshCategories = async ( + forceUpdate = false, + priority = queues.PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.debug( + `Starting AccSaber categories refreshing${ + forceUpdate ? " (forced)" : "" + }...`, + "AccSaberService", + ); try { - log.trace(`Fetching categories from DB...`, 'AccSaberService'); + log.trace(`Fetching categories from DB...`, "AccSaberService"); const dbCategories = await getCategories(); - log.trace(`DB categories fetched`, 'AccSaberService', dbCategories); + log.trace(`DB categories fetched`, "AccSaberService", dbCategories); - if (!await shouldRefresh('categories', forceUpdate)) return {changed: [], all: dbCategories}; + if (!(await shouldRefresh("categories", forceUpdate))) + return { changed: [], all: dbCategories }; - log.trace(`Fetching current categories from AccSaber...`, 'AccSaberService'); + log.trace( + `Fetching current categories from AccSaber...`, + "AccSaberService", + ); - let categories = await accSaberCategoriesApiClient.getProcessed({priority}); + let categories = await accSaberCategoriesApiClient.getProcessed({ + priority, + }); if (!categories || !categories.length) { - log.warn(`AccSaber returned empty categories list`, 'AccSaberService') + log.warn(`AccSaber returned empty categories list`, "AccSaberService"); return null; } - categories = categories.concat([{ - name: 'overall', - displayName: 'Overall', - countsTowardsOverall: null, - description: 'Overall' - }]); + categories = categories.concat([ + { + name: "overall", + displayName: "Overall", + countsTowardsOverall: null, + description: "Overall", + }, + ]); - log.trace(`Categories fetched`, 'AccSaberService', categories); + log.trace(`Categories fetched`, "AccSaberService", categories); - const dbCategoriesNames = dbCategories.map(c => c.name); - const newCategories = categories.filter(c => !dbCategories || !dbCategoriesNames.includes(c.name)); + const dbCategoriesNames = dbCategories.map((c) => c.name); + const newCategories = categories.filter( + (c) => !dbCategories || !dbCategoriesNames.includes(c.name), + ); if (newCategories && newCategories.length) - log.debug(`${newCategories.length} new categories found`, 'AccSaberService'); + log.debug( + `${newCategories.length} new categories found`, + "AccSaberService", + ); - await db.runInTransaction(['accsaber-categories', 'key-value'], async tx => { - const newCategoriesNames = categories.map(c => c.name); + await db.runInTransaction( + ["accsaber-categories", "key-value"], + async (tx) => { + const newCategoriesNames = categories.map((c) => c.name); - const accSaberCategoriesStore = tx.objectStore('accsaber-categories'); + const accSaberCategoriesStore = tx.objectStore("accsaber-categories"); - let cursor = await accSaberCategoriesStore.openCursor(); + let cursor = await accSaberCategoriesStore.openCursor(); - log.trace(`Remove old categories from DB`, 'AccSaberService'); + log.trace(`Remove old categories from DB`, "AccSaberService"); - while (cursor) { - const category = cursor.value; - if (!newCategoriesNames.includes(category.name)) await cursor.delete(); + while (cursor) { + const category = cursor.value; + if (!newCategoriesNames.includes(category.name)) + await cursor.delete(); - cursor = await cursor.continue(); - } + cursor = await cursor.continue(); + } - log.trace(`Old categories removed from DB`, 'AccSaberService'); + log.trace(`Old categories removed from DB`, "AccSaberService"); - log.trace(`Updating categories in DB...`, 'AccSaberService'); + log.trace(`Updating categories in DB...`, "AccSaberService"); - await Promise.all(categories.map(async c => accSaberCategoriesStore.put(c))); + await Promise.all( + categories.map(async (c) => accSaberCategoriesStore.put(c)), + ); - log.trace(`Categories updated`, 'AccSaberService'); + log.trace(`Categories updated`, "AccSaberService"); - log.trace(`Updating categories last update date in DB...`, 'AccSaberService'); + log.trace( + `Updating categories last update date in DB...`, + "AccSaberService", + ); - await tx.objectStore('key-value').put(new Date(), getLastUpdatedKey('categories')); + await tx + .objectStore("key-value") + .put(new Date(), getLastUpdatedKey("categories")); - log.debug(`Categories last update date updated`, 'AccSaberService'); - }); + log.debug(`Categories last update date updated`, "AccSaberService"); + }, + ); accSaberCategoriesRepository().addToCache(categories); - keyValueRepository().setCache(getLastUpdatedKey('categories'), new Date()); + keyValueRepository().setCache( + getLastUpdatedKey("categories"), + new Date(), + ); - log.debug(`Categories refreshing completed`, 'AccSaberService'); + log.debug(`Categories refreshing completed`, "AccSaberService"); - return {changed: newCategories, all: categories}; - } - catch(e) { + return { changed: newCategories, all: categories }; + } catch (e) { if (throwErrors) throw e; - log.debug(`Categories refreshing error`, 'AccSaberService', e) + log.debug(`Categories refreshing error`, "AccSaberService", e); return null; } - } + }; - const updatePlayerHistory = async player => { + const updatePlayerHistory = async (player) => { if (!player?.playerId) return; try { - log.debug(`Updating player ${player.playerId} history`, 'AccSaberService'); + log.debug( + `Updating player ${player.playerId} history`, + "AccSaberService", + ); const accSaberDate = toAccSaberMidnight(new Date()); const playerIdTimestamp = `${player.playerId}_${accSaberDate.getTime()}`; - const existingData = await accSaberPlayersHistoryRepository().get(playerIdTimestamp); + const existingData = + await accSaberPlayersHistoryRepository().get(playerIdTimestamp); const lastUpdated = dateFromString(existingData?.lastUpdated); if (lastUpdated && lastUpdated > new Date() - REFRESH_INTERVAL) { - log.debug(`Refresh interval for player ${player.playerId} history not yet expired, skipping. Next refresh on ${formatDate(addToDate(REFRESH_INTERVAL, lastUpdated))}`, 'AccSaberService') + log.debug( + `Refresh interval for player ${ + player.playerId + } history not yet expired, skipping. Next refresh on ${formatDate( + addToDate(REFRESH_INTERVAL, lastUpdated), + )}`, + "AccSaberService", + ); return; } - const categories = (await getCategories())?.map(c => c.name) ?? null; + const categories = (await getCategories())?.map((c) => c.name) ?? null; if (!categories) { - log.trace(`No categories found, skip updating player ${player.playerId} history.`); + log.trace( + `No categories found, skip updating player ${player.playerId} history.`, + ); return; } let accStats = {}; for (const category of categories) { - const playerAccInfo = (await getRanking(category) ?? []).find(p => p.playerId === player.playerId); + const playerAccInfo = ((await getRanking(category)) ?? []).find( + (p) => p.playerId === player.playerId, + ); if (!playerAccInfo) continue; const { @@ -358,109 +485,175 @@ export default () => { accSaberDate, lastUpdated: new Date(), playerIdTimestamp, - categories: accStats - } + categories: accStats, + }; await accSaberPlayersHistoryRepository().set(stats); } else { - log.trace(`No Acc Saber data for player ${player.playerId}, skipping history updating.`, 'AccSaberService'); + log.trace( + `No Acc Saber data for player ${player.playerId}, skipping history updating.`, + "AccSaberService", + ); return; } - log.debug(`Player ${player.playerId} history updated`, 'AccSaberService'); + log.debug(`Player ${player.playerId} history updated`, "AccSaberService"); + } catch (e) { + log.debug( + `Player ${player.playerId} history updating error.`, + "AccSaberService", + e, + ); } - catch(e) { - log.debug(`Player ${player.playerId} history updating error.`, 'AccSaberService', e); - } - } + }; - const refreshRanking = async (category = 'overall', forceUpdate = false, priority = queues.PRIORITY.BG_NORMAL, throwErrors = false) => { - log.debug(`Starting AccSaber ${category} ranking refreshing${forceUpdate ? ' (forced)' : ''}...`, 'AccSaberService') + const refreshRanking = async ( + category = "overall", + forceUpdate = false, + priority = queues.PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.debug( + `Starting AccSaber ${category} ranking refreshing${ + forceUpdate ? " (forced)" : "" + }...`, + "AccSaberService", + ); try { - log.trace(`Fetching ${category} ranking from DB...`, 'AccSaberService'); + log.trace(`Fetching ${category} ranking from DB...`, "AccSaberService"); const dbRanking = await getRanking(category); - log.trace(`DB ${category} ranking fetched`, 'AccSaberService', dbRanking); + log.trace(`DB ${category} ranking fetched`, "AccSaberService", dbRanking); - const rankingType = `${category}Ranking` + const rankingType = `${category}Ranking`; - if (!await shouldRefresh(rankingType, forceUpdate)) return dbRanking.sort((a, b) => a.rank - b.rank); + if (!(await shouldRefresh(rankingType, forceUpdate))) + return dbRanking.sort((a, b) => a.rank - b.rank); - log.trace(`Fetching current ${category} ranking from AccSaber...`, 'AccSaberService'); + log.trace( + `Fetching current ${category} ranking from AccSaber...`, + "AccSaberService", + ); - const ranking = await accSaberRankingApiClient.getProcessed({category, priority}); + const ranking = await accSaberRankingApiClient.getProcessed({ + category, + priority, + }); if (!ranking || !ranking.length) { - log.warn(`AccSaber returned empty ${category} ranking`, 'AccSaberService') + log.warn( + `AccSaber returned empty ${category} ranking`, + "AccSaberService", + ); return null; } - log.trace(`${capitalize(category)} ranking fetched`, 'AccSaberService', ranking); + log.trace( + `${capitalize(category)} ranking fetched`, + "AccSaberService", + ranking, + ); - log.trace(`Updating ${category} ranking...`, 'AccSaberService'); + log.trace(`Updating ${category} ranking...`, "AccSaberService"); - await db.runInTransaction(['accsaber-players', 'key-value'], async tx => { - const newPlayerIds = ranking.map(c => c.playerId); + await db.runInTransaction( + ["accsaber-players", "key-value"], + async (tx) => { + const newPlayerIds = ranking.map((c) => c.playerId); - const accSaberPlayersStore = tx.objectStore('accsaber-players'); + const accSaberPlayersStore = tx.objectStore("accsaber-players"); - let cursor = await accSaberPlayersStore.openCursor(); + let cursor = await accSaberPlayersStore.openCursor(); - log.trace(`Remove old players from DB for category ${category}`, 'AccSaberService'); + log.trace( + `Remove old players from DB for category ${category}`, + "AccSaberService", + ); - while (cursor) { - const player = cursor.value; - if (player.category === category && !newPlayerIds.includes(player.playerId)) await cursor.delete(); + while (cursor) { + const player = cursor.value; + if ( + player.category === category && + !newPlayerIds.includes(player.playerId) + ) + await cursor.delete(); - cursor = await cursor.continue(); - } + cursor = await cursor.continue(); + } - log.trace(`Old players removed from DB`, 'AccSaberService'); + log.trace(`Old players removed from DB`, "AccSaberService"); - log.trace(`Updating players in DB...`, 'AccSaberService'); + log.trace(`Updating players in DB...`, "AccSaberService"); - await Promise.all(ranking.map(async p => accSaberPlayersStore.put(p))); + await Promise.all( + ranking.map(async (p) => accSaberPlayersStore.put(p)), + ); - log.trace(`Players updated`, 'AccSaberService'); + log.trace(`Players updated`, "AccSaberService"); - log.trace(`Updating players last update date in DB...`, 'AccSaberService'); + log.trace( + `Updating players last update date in DB...`, + "AccSaberService", + ); - await tx.objectStore('key-value').put(new Date(), getLastUpdatedKey(rankingType)); + await tx + .objectStore("key-value") + .put(new Date(), getLastUpdatedKey(rankingType)); - log.debug(`Players last update date updated`, 'AccSaberService'); - }); + log.debug(`Players last update date updated`, "AccSaberService"); + }, + ); accSaberPlayersRepository().addToCache(ranking); keyValueRepository().setCache(getLastUpdatedKey(rankingType), new Date()); - log.debug(`${capitalize(category)} ranking refreshing completed`, 'AccSaberService'); + log.debug( + `${capitalize(category)} ranking refreshing completed`, + "AccSaberService", + ); return ranking.sort((a, b) => a.rank - b.rank); - } - catch (e) { + } catch (e) { if (throwErrors) throw e; - log.debug(` ${capitalize(category)} ranking refreshing error`, 'AccSaberService', e) + log.debug( + ` ${capitalize(category)} ranking refreshing error`, + "AccSaberService", + e, + ); return null; } - } + }; - const refreshAll = async (category = 'overall', forceUpdate = false, priority = queues.PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting AccSaber all data refreshing${forceUpdate ? ' (forced)' : ''}...`, 'AccSaberService') + const refreshAll = async ( + category = "overall", + forceUpdate = false, + priority = queues.PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting AccSaber all data refreshing${ + forceUpdate ? " (forced)" : "" + }...`, + "AccSaberService", + ); try { const dbCategories = await refreshCategories(); - if (!dbCategories || !dbCategories.all) throw 'Can not refresh categories'; + if (!dbCategories || !dbCategories.all) + throw "Can not refresh categories"; const allRankings = await Promise.all( - dbCategories.all.map(c => c.name).map(async category => refreshRanking(category)) - ) + dbCategories.all + .map((c) => c.name) + .map(async (category) => refreshRanking(category)), + ); - log.debug(`All data refreshing completed.`, 'AccSaberService') + log.debug(`All data refreshing completed.`, "AccSaberService"); const rankings = allRankings.reduce((cum, ranking) => { if (!ranking || !ranking.length) return cum; @@ -470,21 +663,28 @@ export default () => { return cum; }, {}); - Promise.all((await playerService.getAllActive()).map(async player => updatePlayerHistory(player))).then(_ => _); + Promise.all( + (await playerService.getAllActive()).map(async (player) => + updatePlayerHistory(player), + ), + ).then((_) => _); - return dbCategories.all.map(c => ({...c, ranking: rankings?.[c.name] ?? []})); + return dbCategories.all.map((c) => ({ + ...c, + ranking: rankings?.[c.name] ?? [], + })); } catch (e) { if (throwErrors) throw e; - log.debug(`All data refreshing error`, 'AccSaberService', e) + log.debug(`All data refreshing error`, "AccSaberService", e); return null; } - } - + }; + const destroyService = () => { service = null; - } + }; service = { isDataForPlayerAvailable, @@ -502,7 +702,7 @@ export default () => { refreshRanking, refreshAll, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/beatmaps.js b/src/services/beatmaps.js index b633095..b24c364 100644 --- a/src/services/beatmaps.js +++ b/src/services/beatmaps.js @@ -1,243 +1,316 @@ -import hashApiClient from '../network/clients/beatmaps/api-hash'; -import keyApiClient from '../network/clients/beatmaps/api-key'; -import {PRIORITY} from '../network/queues/http-queue'; -import log from '../utils/logger' -import {SsrHttpNotFoundError, SsrNetworkError} from '../network/errors' +import hashApiClient from "../network/clients/beatmaps/api-hash"; +import keyApiClient from "../network/clients/beatmaps/api-key"; +import { PRIORITY } from "../network/queues/http-queue"; +import log from "../utils/logger"; +import { SsrHttpNotFoundError, SsrNetworkError } from "../network/errors"; import songsBeatMapsRepository from "../db/repository/songs-beatmaps"; import cacheRepository from "../db/repository/cache"; -import {addToDate, dateFromString, HOUR} from '../utils/date' -import {capitalize, opt} from '../utils/js' +import { addToDate, dateFromString, HOUR } from "../utils/date"; +import { capitalize, opt } from "../utils/js"; -const BM_SUSPENSION_KEY = 'bmSuspension'; -const BM_NOT_FOUND_KEY = 'bm404'; +const BM_SUSPENSION_KEY = "bmSuspension"; +const BM_NOT_FOUND_KEY = "bm404"; const BM_NOT_FOUND_HOURS_BETWEEN_COUNTS = 1; const INVALID_NOTES_COUNT_FIXES = { - 'e738b38b594861745bfb0473c66ca5cca15072ff': [ - {type: 'Standard', diff: "ExpertPlus", notes: 942} - ] -} + e738b38b594861745bfb0473c66ca5cca15072ff: [ + { type: "Standard", diff: "ExpertPlus", notes: 942 }, + ], +}; export default () => { - const cacheSongInfo = async (songInfo, originalHash) => { - if (!songInfo) return null; + const cacheSongInfo = async (songInfo, originalHash) => { + if (!songInfo) return null; - const hash = originalHash && originalHash.length ? originalHash : songInfo.hash; + const hash = + originalHash && originalHash.length ? originalHash : songInfo.hash; - if (!hash || !songInfo.key) return null; + if (!hash || !songInfo.key) return null; - songInfo.hash = hash.toLowerCase(); - songInfo.key = songInfo.key.toLowerCase(); + songInfo.hash = hash.toLowerCase(); + songInfo.key = songInfo.key.toLowerCase(); - delete songInfo.description; + delete songInfo.description; - await songsBeatMapsRepository().set(songInfo); + await songsBeatMapsRepository().set(songInfo); - return songInfo; + return songInfo; + }; + + const isSuspended = (bsSuspension) => + !!bsSuspension && + bsSuspension.activeTo > new Date() && + bsSuspension.started > addToDate(-24 * HOUR); + const getCurrentSuspension = async () => + cacheRepository().get(BM_SUSPENSION_KEY); + const prolongSuspension = async (bsSuspension) => { + const current = new Date(); + + const suspension = isSuspended(bsSuspension) + ? bsSuspension + : { started: current, activeTo: new Date(), count: 0 }; + + suspension.activeTo = addToDate( + Math.pow(2, suspension.count) * HOUR, + suspension.activeTo, + ); + suspension.count++; + + return await cacheRepository().set(suspension, BM_SUSPENSION_KEY); + }; + + const get404Hashes = async () => cacheRepository().get(BM_NOT_FOUND_KEY); + const set404Hashes = async (hashes) => + cacheRepository().set(hashes, BM_NOT_FOUND_KEY); + const setHashNotFound = async (hash) => { + let songs404 = await get404Hashes(); + if (!songs404) songs404 = {}; + + const item = songs404[hash] + ? songs404[hash] + : { firstTry: new Date(), recentTry: null, count: 0 }; + + if ( + !item.recentTry || + addToDate(BM_NOT_FOUND_HOURS_BETWEEN_COUNTS * HOUR, item.recentTry) < + new Date() + ) { + item.recentTry = new Date(); + item.count++; + + songs404[hash] = item; + + await set404Hashes(songs404); } + }; + const isHashUnavailable = async (hash) => { + const songs404 = await get404Hashes(); + return songs404 && songs404[hash] && songs404[hash].count >= 3; + }; - const isSuspended = bsSuspension => !!bsSuspension && bsSuspension.activeTo > new Date() && bsSuspension.started > addToDate(-24 * HOUR); - const getCurrentSuspension = async () => cacheRepository().get(BM_SUSPENSION_KEY); - const prolongSuspension = async bsSuspension => { - const current = new Date(); + const fixInvalidNotesCount = (hash, songInfo) => { + if (!hash) return songInfo; - const suspension = isSuspended(bsSuspension) ? bsSuspension : {started: current, activeTo: new Date(), count: 0}; + if (INVALID_NOTES_COUNT_FIXES[hash] && songInfo?.versions) + songInfo.versions.forEach((si) => { + if (!si?.diffs) return; - suspension.activeTo = addToDate(Math.pow(2, suspension.count) * HOUR, suspension.activeTo); - suspension.count++; + si.diffs.forEach((d) => { + const newNotesCnt = INVALID_NOTES_COUNT_FIXES[hash].find( + (f) => f.type === d?.characteristic && f.diff === d?.difficulty, + ); + if (!newNotesCnt) return; - return await cacheRepository().set(suspension, BM_SUSPENSION_KEY); - } + d.notes = newNotesCnt.notes; + }); + }); - const get404Hashes = async () => cacheRepository().get(BM_NOT_FOUND_KEY); - const set404Hashes = async hashes => cacheRepository().set(hashes, BM_NOT_FOUND_KEY); - const setHashNotFound = async hash => { - let songs404 = await get404Hashes(); - if (!songs404) songs404 = {}; + return songInfo; + }; - const item = songs404[hash] ? songs404[hash] : {firstTry: new Date(), recentTry: null, count: 0}; + const fetchSong = async ( + songInfo, + fetchFunc, + forceUpdate = false, + cacheOnly = false, + errSongId = "", + hash = null, + ) => { + if (!forceUpdate && songInfo) return fixInvalidNotesCount(hash, songInfo); - if (!item.recentTry || addToDate(BM_NOT_FOUND_HOURS_BETWEEN_COUNTS * HOUR, item.recentTry) < new Date()) { - item.recentTry = new Date(); - item.count++; + if (cacheOnly) return null; - songs404[hash] = item; + let bsSuspension = await getCurrentSuspension(); - await set404Hashes(songs404); - } - } - const isHashUnavailable = async hash => { - const songs404 = await get404Hashes(); - return songs404 && songs404[hash] && songs404[hash].count >= 3; - } + try { + if ( + isSuspended(bsSuspension) || + (hash && (await isHashUnavailable(hash))) + ) + return null; - const fixInvalidNotesCount = (hash, songInfo) => { - if (!hash) return songInfo; + const songInfo = await fetchFunc(); + if (!songInfo) { + log.warn(`Song "${errSongId}" is no longer available at BeatSaver.`); + return null; + } - if (INVALID_NOTES_COUNT_FIXES[hash] && songInfo?.versions) - songInfo.versions.forEach(si => { - if (!si?.diffs) return; - - si.diffs.forEach(d => { - const newNotesCnt = INVALID_NOTES_COUNT_FIXES[hash].find(f => f.type === d?.characteristic && f.diff === d?.difficulty); - if (!newNotesCnt) return; - - d.notes = newNotesCnt.notes; - }) - }) - - return songInfo; - } - - const fetchSong = async (songInfo, fetchFunc, forceUpdate = false, cacheOnly = false, errSongId = '', hash = null) => { - if (!forceUpdate && songInfo) return fixInvalidNotesCount(hash, songInfo); - - if(cacheOnly) return null; - - let bsSuspension = await getCurrentSuspension(); + return fixInvalidNotesCount(hash, cacheSongInfo(songInfo, hash)); + } catch (err) { + if (hash && err instanceof SsrHttpNotFoundError) { + await setHashNotFound(hash); + } + if (err instanceof SsrNetworkError && err.message === "Network error") { try { - if (isSuspended(bsSuspension) || (hash && await isHashUnavailable(hash))) return null; + await prolongSuspension(bsSuspension); + } catch {} + } - const songInfo = await fetchFunc(); - if (!songInfo) { - log.warn(`Song "${errSongId}" is no longer available at BeatSaver.`); - return null; - } + log.warn(`Error fetching BeatSaver song "${errSongId}"`); - return fixInvalidNotesCount(hash, cacheSongInfo(songInfo, hash)); - } catch (err) { - if (hash && err instanceof SsrHttpNotFoundError) { - await setHashNotFound(hash); - } - - if (err instanceof SsrNetworkError && err.message === 'Network error') { - try {await prolongSuspension(bsSuspension)} catch {} - } - - log.warn(`Error fetching BeatSaver song "${errSongId}"`); - - return null; - } + return null; } + }; - const byHash = async (hash, forceUpdate = false, cacheOnly = false, signal = null, priority = PRIORITY.FG_LOW) => { - hash = hash.toLowerCase(); + const byHash = async ( + hash, + forceUpdate = false, + cacheOnly = false, + signal = null, + priority = PRIORITY.FG_LOW, + ) => { + hash = hash.toLowerCase(); - const songInfo = await songsBeatMapsRepository().get(hash); + const songInfo = await songsBeatMapsRepository().get(hash); - return fetchSong(songInfo, () => hashApiClient.getProcessed({hash, signal, priority}), forceUpdate, cacheOnly, hash, hash) - } + return fetchSong( + songInfo, + () => hashApiClient.getProcessed({ hash, signal, priority }), + forceUpdate, + cacheOnly, + hash, + hash, + ); + }; - const byKey = async (key, forceUpdate = false, cacheOnly = false, signal = null, priority = PRIORITY.FG_LOW) => { - key = key.toLowerCase(); + const byKey = async ( + key, + forceUpdate = false, + cacheOnly = false, + signal = null, + priority = PRIORITY.FG_LOW, + ) => { + key = key.toLowerCase(); - const songInfo = await songsBeatMapsRepository().getFromIndex('songs-beatmaps-key', key); + const songInfo = await songsBeatMapsRepository().getFromIndex( + "songs-beatmaps-key", + key, + ); - return fetchSong(songInfo, () => keyApiClient.getProcessed({key, signal, priority}), forceUpdate, cacheOnly, key) - } + return fetchSong( + songInfo, + () => keyApiClient.getProcessed({ key, signal, priority }), + forceUpdate, + cacheOnly, + key, + ); + }; - const convertOldBeatSaverToBeatMaps = song => { - let {key, hash, name, metadata: {characteristics}} = song; + const convertOldBeatSaverToBeatMaps = (song) => { + let { + key, + hash, + name, + metadata: { characteristics }, + } = song; - if (!key || !hash || !name || !characteristics || !Array.isArray(characteristics)) return null; + if ( + !key || + !hash || + !name || + !characteristics || + !Array.isArray(characteristics) + ) + return null; - if (hash.toLowerCase) hash = hash.toLowerCase(); + if (hash.toLowerCase) hash = hash.toLowerCase(); - const diffs = characteristics.reduce((diffs, ch) => { - if (!ch.name || !ch.difficulties) return diffs; - const characteristic = ch.name; + const diffs = characteristics.reduce((diffs, ch) => { + if (!ch.name || !ch.difficulties) return diffs; + const characteristic = ch.name; - return diffs.concat( - Object.entries(ch.difficulties) - .map(([difficulty, obj]) => { - if (!obj) return null; - difficulty = capitalize(difficulty); + return diffs + .concat( + Object.entries(ch.difficulties).map(([difficulty, obj]) => { + if (!obj) return null; + difficulty = capitalize(difficulty); - const seconds = opt(obj, 'length', null); - const notes = opt(obj, 'notes', null) + const seconds = opt(obj, "length", null); + const notes = opt(obj, "notes", null); - const nps = notes && seconds ? notes / seconds : null; + const nps = notes && seconds ? notes / seconds : null; - return { - njs: opt(obj, 'njs', null), - offset: opt(obj, 'njsOffset', null), - notes, - bombs: opt(obj, 'bombs', null), - obstacles: opt(obj, 'obstacles', null), - nps, - length: opt(obj, 'duration', null), - characteristic, - difficulty, - events: null, - chroma: null, - me: null, - ne: null, - cinema: null, - seconds, - paritySummary: { - errors: null, - warns: null, - resets: null, - }, - stars: null, - }; - })) - .filter(diff => diff) - }, []); - - return { - lastUpdated: dateFromString(opt(song, 'uploaded', new Date())), - oldBeatSaverId: opt(song, '_id', null), - id: key, - hash, - key, - name, - description: '', - uploader: { - id: null, - name: opt(song, 'uploader.username', null), - hash: null, - avatar: null - }, - metadata: { - bpm: opt(song, 'metadata.bpm', null), - duration: opt(song, 'metadata.duration', null), - songName: opt(song, 'metadata.songName', ''), - songSubName: opt(song, 'metadata.songSubName', ''), - songAuthorName: opt(song, 'metadata.songAuthorName', ''), - levelAuthorName: opt(song, 'metadata.levelAuthorName', '') - }, - stats: { - plays: opt(song, 'stats.plays', 0), - downloads: opt(song, 'stats.downloads', 0), - upvotes: opt(song, 'stats.upVotes', 0), - downvotes: opt(song, 'stats.downVotes', 0), - score: null - }, - uploaded: opt(song, 'uploaded', null), - automapper: !!opt(song, 'metadata.automapper', false), - ranked: null, - qualified: null, - versions: [ - { - hash, - key, - state: "Published", - createdAt: opt(song, 'uploaded', null), - sageScore: null, - diffs, - downloadURL: `https://cdn.beatsaver.com/${hash}.zip`, - coverURL: `https://cdn.beatsaver.com/${hash}.jpg`, - previewURL: `https://cdn.beatsaver.com/${hash}.mp3` - } - ] - } - } + return { + njs: opt(obj, "njs", null), + offset: opt(obj, "njsOffset", null), + notes, + bombs: opt(obj, "bombs", null), + obstacles: opt(obj, "obstacles", null), + nps, + length: opt(obj, "duration", null), + characteristic, + difficulty, + events: null, + chroma: null, + me: null, + ne: null, + cinema: null, + seconds, + paritySummary: { + errors: null, + warns: null, + resets: null, + }, + stars: null, + }; + }), + ) + .filter((diff) => diff); + }, []); return { - byHash, - byKey, - convertOldBeatSaverToBeatMaps - } -} \ No newline at end of file + lastUpdated: dateFromString(opt(song, "uploaded", new Date())), + oldBeatSaverId: opt(song, "_id", null), + id: key, + hash, + key, + name, + description: "", + uploader: { + id: null, + name: opt(song, "uploader.username", null), + hash: null, + avatar: null, + }, + metadata: { + bpm: opt(song, "metadata.bpm", null), + duration: opt(song, "metadata.duration", null), + songName: opt(song, "metadata.songName", ""), + songSubName: opt(song, "metadata.songSubName", ""), + songAuthorName: opt(song, "metadata.songAuthorName", ""), + levelAuthorName: opt(song, "metadata.levelAuthorName", ""), + }, + stats: { + plays: opt(song, "stats.plays", 0), + downloads: opt(song, "stats.downloads", 0), + upvotes: opt(song, "stats.upVotes", 0), + downvotes: opt(song, "stats.downVotes", 0), + score: null, + }, + uploaded: opt(song, "uploaded", null), + automapper: !!opt(song, "metadata.automapper", false), + ranked: null, + qualified: null, + versions: [ + { + hash, + key, + state: "Published", + createdAt: opt(song, "uploaded", null), + sageScore: null, + diffs, + downloadURL: `https://cdn.beatsaver.com/${hash}.zip`, + coverURL: `https://cdn.beatsaver.com/${hash}.jpg`, + previewURL: `https://cdn.beatsaver.com/${hash}.mp3`, + }, + ], + }; + }; + + return { + byHash, + byKey, + convertOldBeatSaverToBeatMaps, + }; +}; diff --git a/src/services/beatsavior.js b/src/services/beatsavior.js index ab6a63b..268c5bf 100644 --- a/src/services/beatsavior.js +++ b/src/services/beatsavior.js @@ -1,16 +1,24 @@ -import {PRIORITY} from '../network/queues/http-queue'; -import createPlayerService from './scoresaber/player' -import createScoresService from './scoresaber/scores' -import beatSaviorApiClient from '../network/clients/beatsavior/api'; -import beatSaviorRepository from '../db/repository/beat-savior' -import beatSaviorPlayersRepository from '../db/repository/beat-savior-players' -import {addToDate, DAY, formatDate, HOUR, MINUTE, SECOND, truncateDate} from '../utils/date' -import log from '../utils/logger' -import {opt} from '../utils/js' -import makePendingPromisePool from '../utils/pending-promises' -import {PLAYER_SCORES_PER_PAGE} from '../utils/scoresaber/consts' -import {roundToPrecision} from '../utils/format' -import {serviceFilterFunc} from './utils' +import { PRIORITY } from "../network/queues/http-queue"; +import createPlayerService from "./scoresaber/player"; +import createScoresService from "./scoresaber/scores"; +import beatSaviorApiClient from "../network/clients/beatsavior/api"; +import beatSaviorRepository from "../db/repository/beat-savior"; +import beatSaviorPlayersRepository from "../db/repository/beat-savior-players"; +import { + addToDate, + DAY, + formatDate, + HOUR, + MINUTE, + SECOND, + truncateDate, +} from "../utils/date"; +import log from "../utils/logger"; +import { opt } from "../utils/js"; +import makePendingPromisePool from "../utils/pending-promises"; +import { PLAYER_SCORES_PER_PAGE } from "../utils/scoresaber/consts"; +import { roundToPrecision } from "../utils/format"; +import { serviceFilterFunc } from "./utils"; const MAIN_PLAYER_REFRESH_INTERVAL = MINUTE * 15; const CACHED_PLAYER_REFRESH_INTERVAL = HOUR * 3; @@ -30,52 +38,73 @@ export default () => { const playerService = createPlayerService(); const scoresService = createScoresService(); - const getPlayerScores = async playerId => resolvePromiseOrWaitForPending(`getPlayerScores/${playerId}`, () => beatSaviorRepository().getAllFromIndex('beat-savior-playerId', playerId)); + const getPlayerScores = async (playerId) => + resolvePromiseOrWaitForPending(`getPlayerScores/${playerId}`, () => + beatSaviorRepository().getAllFromIndex("beat-savior-playerId", playerId), + ); - const getPlayerScoresWithScoreSaber = async playerId => { + const getPlayerScoresWithScoreSaber = async (playerId) => { const [beatSaviorData, playerScores] = await Promise.all([ getPlayerScores(playerId), - resolvePromiseOrWaitForPending(`getSsPlayerScores/${playerId}`, () => scoresService.getPlayerScoresAsObject( - playerId, - score => score?.leaderboard?.song?.hash?.toLowerCase() ?? null, - true, - )), + resolvePromiseOrWaitForPending(`getSsPlayerScores/${playerId}`, () => + scoresService.getPlayerScoresAsObject( + playerId, + (score) => score?.leaderboard?.song?.hash?.toLowerCase() ?? null, + true, + ), + ), ]); - return beatSaviorData.map(bsData => { - if (!bsData?.hash || !playerScores?.[bsData?.hash?.toLowerCase()]) return bsData; + return beatSaviorData.map((bsData) => { + if (!bsData?.hash || !playerScores?.[bsData?.hash?.toLowerCase()]) + return bsData; - const ssScore = playerScores[bsData.hash.toLowerCase()].find(ssScore => isScoreMatchingBsData(ssScore, bsData, true)) ?? null; + const ssScore = + playerScores[bsData.hash.toLowerCase()].find((ssScore) => + isScoreMatchingBsData(ssScore, bsData, true), + ) ?? null; return { ...bsData, - ssScore - } + ssScore, + }; }); - } + }; const isScoreMatchingBsData = (score, bsData, exact = true) => { - if (!bsData.hash || !bsData.score || !bsData.timeSet || !opt(bsData, 'stats.won')) return false; + if ( + !bsData.hash || + !bsData.score || + !bsData.timeSet || + !opt(bsData, "stats.won") + ) + return false; - const diff = opt(score, 'leaderboard.diffInfo.diff'); - const scoreValue = opt(score, 'score.score'); - const timeSet = opt(score, 'score.timeSet') - let hash = opt(score, 'leaderboard.song.hash'); + const diff = opt(score, "leaderboard.diffInfo.diff"); + const scoreValue = opt(score, "score.score"); + const timeSet = opt(score, "score.timeSet"); + let hash = opt(score, "leaderboard.song.hash"); if (!diff || !score || !timeSet || !hash) return false; hash = hash.toLowerCase(); if (bsData.hash === hash && bsData.diff === diff) { - return !exact || (bsData.score === scoreValue && Math.abs(timeSet.getTime() - bsData.timeSet.getTime()) < MINUTE); + return ( + !exact || + (bsData.score === scoreValue && + Math.abs(timeSet.getTime() - bsData.timeSet.getTime()) < MINUTE) + ); } return false; - } + }; - const getScoresHistogramDefinition = (serviceParams = {sort: 'recent', order: 'desc'}) => { - const sort = serviceParams?.sort ?? 'recent'; - const order = serviceParams?.order ?? 'desc'; + const getScoresHistogramDefinition = ( + serviceParams = { sort: "recent", order: "desc" }, + ) => { + const sort = serviceParams?.sort ?? "recent"; + const order = serviceParams?.order ?? "desc"; let round = 2; let bucketSize = 1; @@ -83,57 +112,65 @@ export default () => { let maxBucketSize = null; let bucketSizeStep = null; let bucketSizeValues = null; - let type = 'linear'; - let valFunc = s => s; + let type = "linear"; + let valFunc = (s) => s; let filterFunc = serviceFilterFunc(serviceParams); - let histogramFilterFunc = s => s; - let roundedValFunc = (s, type = type, precision = bucketSize) => type === 'linear' - ? roundToPrecision(valFunc(s), precision) - : truncateDate(valFunc(s), precision); - let prefix = ''; - let prefixLong = ''; - let suffix = ''; - let suffixLong = ''; + let histogramFilterFunc = (s) => s; + let roundedValFunc = (s, type = type, precision = bucketSize) => + type === "linear" + ? roundToPrecision(valFunc(s), precision) + : truncateDate(valFunc(s), precision); + let prefix = ""; + let prefixLong = ""; + let suffix = ""; + let suffixLong = ""; - switch(sort) { - case 'recent': - valFunc = s => s?.timeSet; - type = 'time'; - bucketSize = 'day' + switch (sort) { + case "recent": + valFunc = (s) => s?.timeSet; + type = "time"; + bucketSize = "day"; break; - case 'acc': - valFunc = s => (s?.trackers?.scoreTracker?.rawRatio ?? 0) * 100; - histogramFilterFunc = h => h?.x >= HISTOGRAM_ACC_THRESHOLD; - type = 'linear'; + case "acc": + valFunc = (s) => (s?.trackers?.scoreTracker?.rawRatio ?? 0) * 100; + histogramFilterFunc = (h) => h?.x >= HISTOGRAM_ACC_THRESHOLD; + type = "linear"; bucketSize = 0.25; minBucketSize = 0.05; maxBucketSize = 10; bucketSizeStep = 0.05; round = 2; - suffix = '%'; - suffixLong = '%'; + suffix = "%"; + suffixLong = "%"; break; - case 'mistakes': - valFunc = s => (s?.stats?.miss ?? 0) + (s?.stats?.wallHit ?? 0) + (s?.stats?.bombHit ?? 0); - histogramFilterFunc = h => h?.x <= HISTOGRAM_MISTAKES_THRESHOLD; - type = 'linear'; + case "mistakes": + valFunc = (s) => + (s?.stats?.miss ?? 0) + + (s?.stats?.wallHit ?? 0) + + (s?.stats?.bombHit ?? 0); + histogramFilterFunc = (h) => h?.x <= HISTOGRAM_MISTAKES_THRESHOLD; + type = "linear"; bucketSize = 1; minBucketSize = 1; maxBucketSize = 50; bucketSizeStep = 1; round = 0; - suffixLong = ' mistake(s)'; + suffixLong = " mistake(s)"; break; } return { getValue: valFunc, - getRoundedValue: (bucketSize = bucketSize) => s => roundedValFunc(s, type, bucketSize), + getRoundedValue: + (bucketSize = bucketSize) => + (s) => + roundedValFunc(s, type, bucketSize), filter: filterFunc, histogramFilter: histogramFilterFunc, - sort: (a, b) => order === 'asc' ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), + sort: (a, b) => + order === "asc" ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), type, bucketSize, minBucketSize, @@ -145,37 +182,42 @@ export default () => { prefixLong, suffix, suffixLong, - order - } - } + order, + }; + }; - const getPlayerScoresPage = async (playerId, serviceParams = {sort: 'recent', order: 'desc', page: 1}) => { + const getPlayerScoresPage = async ( + playerId, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + ) => { let page = serviceParams?.page ?? 1; if (page < 1) page = 1; let playerScores = await getPlayerScores(playerId); - if (!playerScores || !playerScores.length) return {total: 0, scores: []}; + if (!playerScores || !playerScores.length) return { total: 0, scores: [] }; - const {sort: sortFunc, filter: filterFunc} = getScoresHistogramDefinition(serviceParams); + const { sort: sortFunc, filter: filterFunc } = + getScoresHistogramDefinition(serviceParams); - playerScores = playerScores.filter(filterFunc).sort(sortFunc) + playerScores = playerScores.filter(filterFunc).sort(sortFunc); const startIdx = (page - 1) * PLAYER_SCORES_PER_PAGE; - if (playerScores.length < startIdx + 1) return {total: 0, scores: []}; + if (playerScores.length < startIdx + 1) return { total: 0, scores: [] }; return { total: playerScores.length, scores: playerScores .slice(startIdx, startIdx + PLAYER_SCORES_PER_PAGE) - .map(bs => { + .map((bs) => { const leaderboard = bs.leaderboard; - if (!leaderboard.leaderboardId) leaderboard.leaderboardId = bs.beatSaviorId; + if (!leaderboard.leaderboardId) + leaderboard.leaderboardId = bs.beatSaviorId; leaderboard.leaderboardId += Math.random(); // ScoresSvelte needs different keys for each scores row - const rawScore = opt(bs, 'trackers.scoreTracker.rawScore', 0); - const rawRatio = opt(bs, 'trackers.scoreTracker.rawRatio', 0); + const rawScore = opt(bs, "trackers.scoreTracker.rawScore", 0); + const rawRatio = opt(bs, "trackers.scoreTracker.rawRatio", 0); const maxScore = rawRatio & rawScore ? rawScore / rawRatio : 0; return { @@ -188,51 +230,76 @@ export default () => { score: { acc: rawRatio * 100, maxScore, - mods: opt(bs, 'trackers.scoreTracker.modifiers', null), - percentage: opt(bs, 'trackers.scoreTracker.rawRatio', 0) * 100, + mods: opt(bs, "trackers.scoreTracker.modifiers", null), + percentage: opt(bs, "trackers.scoreTracker.rawRatio", 0) * 100, pp: 0, ppWeighted: 0, rank: null, - score: opt(bs, 'trackers.scoreTracker.score', 0), + score: opt(bs, "trackers.scoreTracker.score", 0), scoreId: bs.beatSaviorId, timeSet: bs.timeSet, unmodifiedScore: rawScore, weight: 0, }, timeSet: bs.timeSet, - } - }) + }; + }), }; - } + }; const updateData = async (playerId, data) => { - log.debug(`Updating Beat Savior data for player "${playerId}"...`, 'BeatSaviorService') + log.debug( + `Updating Beat Savior data for player "${playerId}"...`, + "BeatSaviorService", + ); - await Promise.all(data.map(async d => beatSaviorRepository().set(d))); + await Promise.all(data.map(async (d) => beatSaviorRepository().set(d))); - log.debug(`Update player "${playerId}" Beat Savior last refresh date...`, 'BeatSaviorService') + log.debug( + `Update player "${playerId}" Beat Savior last refresh date...`, + "BeatSaviorService", + ); - await beatSaviorPlayersRepository().set({playerId, lastRefresh: new Date()}) + await beatSaviorPlayersRepository().set({ + playerId, + lastRefresh: new Date(), + }); - log.debug(`Beat Savior data for player "${playerId}" updated.`, 'BeatSaviorService') + log.debug( + `Beat Savior data for player "${playerId}" updated.`, + "BeatSaviorService", + ); return data; - } + }; const fetchPlayer = async (playerId, priority = PRIORITY.BG_NORMAL) => { try { - log.debug(`Fetching Beat Savior data for player "${playerId}"...`, 'BeatSaviorService'); + log.debug( + `Fetching Beat Savior data for player "${playerId}"...`, + "BeatSaviorService", + ); - const data = await beatSaviorApiClient.getProcessed({playerId, priority}); + const data = await beatSaviorApiClient.getProcessed({ + playerId, + priority, + }); if (!data) { - log.debug(`No Beat Savior data for player "${playerId}"`, 'BeatSaviorService') + log.debug( + `No Beat Savior data for player "${playerId}"`, + "BeatSaviorService", + ); return null; } // TODO: check if data already exists in DB - log.trace(`Beat Savior data for player "${playerId}" fetched`, 'BeatSaviorService', data); + log.trace( + `Beat Savior data for player "${playerId}" fetched`, + "BeatSaviorService", + data, + ); return updateData(playerId, data); } catch (err) { @@ -240,62 +307,121 @@ export default () => { return null; } - } + }; - const refresh = async (playerId, force = false, priority = PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting refreshing BeatSavior for player "${playerId}" ${force ? ' (forced)' : ''}...`, 'BeatSaviorService') + const refresh = async ( + playerId, + force = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting refreshing BeatSavior for player "${playerId}" ${ + force ? " (forced)" : "" + }...`, + "BeatSaviorService", + ); try { const player = await playerService.get(playerId); - const REFRESH_INTERVAL = playerService.isMainPlayer(playerId) ? MAIN_PLAYER_REFRESH_INTERVAL : (player ? CACHED_PLAYER_REFRESH_INTERVAL : OTHER_PLAYER_REFRESH_INTERVAL); + const REFRESH_INTERVAL = playerService.isMainPlayer(playerId) + ? MAIN_PLAYER_REFRESH_INTERVAL + : player + ? CACHED_PLAYER_REFRESH_INTERVAL + : OTHER_PLAYER_REFRESH_INTERVAL; const bsPlayerInfo = await beatSaviorPlayersRepository().get(playerId); - const nextUpdate = bsPlayerInfo && bsPlayerInfo.lastRefresh ? addToDate(REFRESH_INTERVAL, bsPlayerInfo.lastRefresh) : addToDate(-SECOND); + const nextUpdate = + bsPlayerInfo && bsPlayerInfo.lastRefresh + ? addToDate(REFRESH_INTERVAL, bsPlayerInfo.lastRefresh) + : addToDate(-SECOND); if (!force && bsPlayerInfo && nextUpdate > new Date()) { - log.debug(`Beat Savior data is still fresh, skipping. Next refresh on ${formatDate(nextUpdate)}`, 'BeatSaviorService') + log.debug( + `Beat Savior data is still fresh, skipping. Next refresh on ${formatDate( + nextUpdate, + )}`, + "BeatSaviorService", + ); return null; if (player) { - log.trace(`Player "${playerId}" is a cached one, checking recent play date`, 'BeatSaviorService') + log.trace( + `Player "${playerId}" is a cached one, checking recent play date`, + "BeatSaviorService", + ); - if (player.recentPlay && player.recentPlay < bsPlayerInfo.lastRefresh) { - log.debug(`Beat Savior data for player "${playerId}" was refreshed after recent play, skipping`, 'BeatSaviorService') + if ( + player.recentPlay && + player.recentPlay < bsPlayerInfo.lastRefresh + ) { + log.debug( + `Beat Savior data for player "${playerId}" was refreshed after recent play, skipping`, + "BeatSaviorService", + ); return null; } } } - return resolvePromiseOrWaitForPending(`refresh/${playerId}`, () => fetchPlayer(playerId, priority)); + return resolvePromiseOrWaitForPending(`refresh/${playerId}`, () => + fetchPlayer(playerId, priority), + ); } catch (e) { if (throwErrors) throw e; - log.debug(`Beat Savior data refreshing error${e.toString ? `: ${e.toString()}` : ''}`, 'BeatSaviorService', e) + log.debug( + `Beat Savior data refreshing error${ + e.toString ? `: ${e.toString()}` : "" + }`, + "BeatSaviorService", + e, + ); return null; } - } + }; - const refreshAll = async (force = false, priority = PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting refreshing Beat Savior data for all players${force ? ' (forced)' : ''}...`, 'BeatSaviorService'); + const refreshAll = async ( + force = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting refreshing Beat Savior data for all players${ + force ? " (forced)" : "" + }...`, + "BeatSaviorService", + ); const allPlayers = await playerService.getAll(); if (!allPlayers || !allPlayers.length) { - log.trace(`No players in DB, skipping.`, 'BeatSaviorService'); + log.trace(`No players in DB, skipping.`, "BeatSaviorService"); return null; } - const allRefreshed = await Promise.all(allPlayers.map(async player => ({ - playerId: player.playerId, - beatSavior: await refresh(player.playerId, force, priority, throwErrors), - }))); + const allRefreshed = await Promise.all( + allPlayers.map(async (player) => ({ + playerId: player.playerId, + beatSavior: await refresh( + player.playerId, + force, + priority, + throwErrors, + ), + })), + ); - log.trace(`Beat Savior data for all players refreshed.`, 'BeatSaviorService', allRefreshed); + log.trace( + `Beat Savior data for all players refreshed.`, + "BeatSaviorService", + allRefreshed, + ); return allRefreshed; - } + }; const get = async (playerId, score) => { if (score && score.beatSavior) return score.beatSavior; @@ -303,12 +429,18 @@ export default () => { const playerBsData = await getPlayerScores(playerId); if (!playerBsData || !playerBsData.length) return null; - const bsData = playerBsData.find(bsData => isScoreMatchingBsData(score, bsData, true)); + const bsData = playerBsData.find((bsData) => + isScoreMatchingBsData(score, bsData, true), + ); return bsData ? bsData : null; - } + }; - const isDataForPlayerAvailable = async playerId => await beatSaviorRepository().getFromIndex('beat-savior-playerId', playerId) !== undefined; + const isDataForPlayerAvailable = async (playerId) => + (await beatSaviorRepository().getFromIndex( + "beat-savior-playerId", + playerId, + )) !== undefined; const destroyService = () => { serviceCreationCount--; @@ -319,7 +451,7 @@ export default () => { service = null; } - } + }; service = { fetchPlayer, @@ -332,7 +464,7 @@ export default () => { isDataForPlayerAvailable, getScoresHistogramDefinition, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/config.js b/src/services/config.js index 08015b0..f2d0144 100644 --- a/src/services/config.js +++ b/src/services/config.js @@ -1,7 +1,7 @@ -import keyValueRepository from '../db/repository/key-value'; -import {opt} from '../utils/js' +import keyValueRepository from "../db/repository/key-value"; +import { opt } from "../utils/js"; -const STORE_CONFIG_KEY = 'config'; +const STORE_CONFIG_KEY = "config"; let service = null; @@ -9,22 +9,23 @@ export default () => { if (service) return service; const get = async () => keyValueRepository().get(STORE_CONFIG_KEY); - const set = async config => keyValueRepository().set(config, STORE_CONFIG_KEY); + const set = async (config) => + keyValueRepository().set(config, STORE_CONFIG_KEY); const getMainPlayerId = async () => { const config = await get(); - return opt(config, 'users.main'); - } + return opt(config, "users.main"); + }; - const destroyService = () => {} + const destroyService = () => {}; service = { get, set, getMainPlayerId, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/leaderboard.js b/src/services/scoresaber/leaderboard.js index 4f3eda0..8d2be98 100644 --- a/src/services/scoresaber/leaderboard.js +++ b/src/services/scoresaber/leaderboard.js @@ -1,14 +1,14 @@ -import leaderboardPageClient from '../../network/clients/scoresaber/leaderboard/page-leaderboard' -import accSaberLeaderboardApiClient from '../../network/clients/accsaber/api-leaderboard' -import makePendingPromisePool from '../../utils/pending-promises' -import createPlayersService from '../../services/scoresaber/player' -import createScoresService from '../../services/scoresaber/scores' -import {PRIORITY} from '../../network/queues/http-queue' -import {LEADERBOARD_SCORES_PER_PAGE} from '../../utils/scoresaber/consts' -import {LEADERBOARD_SCORES_PER_PAGE as ACCSABER_LEADERBOARD_SCORES_PER_PAGE} from '../../utils/accsaber/consts' -import {formatDateRelative, MINUTE} from '../../utils/date' -import {convertArrayToObjectByKey, opt} from '../../utils/js' -import eventBus from '../../utils/broadcast-channel-pubsub' +import leaderboardPageClient from "../../network/clients/scoresaber/leaderboard/page-leaderboard"; +import accSaberLeaderboardApiClient from "../../network/clients/accsaber/api-leaderboard"; +import makePendingPromisePool from "../../utils/pending-promises"; +import createPlayersService from "../../services/scoresaber/player"; +import createScoresService from "../../services/scoresaber/scores"; +import { PRIORITY } from "../../network/queues/http-queue"; +import { LEADERBOARD_SCORES_PER_PAGE } from "../../utils/scoresaber/consts"; +import { LEADERBOARD_SCORES_PER_PAGE as ACCSABER_LEADERBOARD_SCORES_PER_PAGE } from "../../utils/accsaber/consts"; +import { formatDateRelative, MINUTE } from "../../utils/date"; +import { convertArrayToObjectByKey, opt } from "../../utils/js"; +import eventBus from "../../utils/broadcast-channel-pubsub"; const ACCSABER_LEADERBOARD_NETWORK_TTL = MINUTE * 5; @@ -20,79 +20,118 @@ export default () => { const scoresService = createScoresService(); let friendsPromise = Promise.resolve([]); - const refreshFriends = async () => friendsPromise = playersService.getAll(); - eventBus.on('player-profile-removed', playerId => refreshFriends()); - eventBus.on('player-profile-added', player => refreshFriends()); - eventBus.on('player-profile-changed', player => refreshFriends()); - refreshFriends().then(_ => {}); + const refreshFriends = async () => (friendsPromise = playersService.getAll()); + eventBus.on("player-profile-removed", (playerId) => refreshFriends()); + eventBus.on("player-profile-added", (player) => refreshFriends()); + eventBus.on("player-profile-changed", (player) => refreshFriends()); + refreshFriends().then((_) => {}); const resolvePromiseOrWaitForPending = makePendingPromisePool(); - const fetchPage = async (leaderboardId, page = 1, priority = PRIORITY.FG_LOW, signal = null, force = false) => resolvePromiseOrWaitForPending( - `pageClient/leaderboard/${leaderboardId}/${page}`, - () => leaderboardPageClient.getProcessed({ - leaderboardId, - page, - signal, - priority, - cacheTtl: MINUTE, - })); + const fetchPage = async ( + leaderboardId, + page = 1, + priority = PRIORITY.FG_LOW, + signal = null, + force = false, + ) => + resolvePromiseOrWaitForPending( + `pageClient/leaderboard/${leaderboardId}/${page}`, + () => + leaderboardPageClient.getProcessed({ + leaderboardId, + page, + signal, + priority, + cacheTtl: MINUTE, + }), + ); - const fetchAccSaberPage = async (leaderboardId, page = 1, priority = PRIORITY.FG_LOW, signal = null, force = false) => { + const fetchAccSaberPage = async ( + leaderboardId, + page = 1, + priority = PRIORITY.FG_LOW, + signal = null, + force = false, + ) => { if (page < 1) page = 1; const data = await resolvePromiseOrWaitForPending( `accSaberApiClient/leaderboard/${leaderboardId}/${page}`, - () => accSaberLeaderboardApiClient.getProcessed({ - leaderboardId, - page, - signal, - priority, - cacheTtl: ACCSABER_LEADERBOARD_NETWORK_TTL, - })); + () => + accSaberLeaderboardApiClient.getProcessed({ + leaderboardId, + page, + signal, + priority, + cacheTtl: ACCSABER_LEADERBOARD_NETWORK_TTL, + }), + ); - if (!data || !data.scores) return data + if (!data || !data.scores) return data; const startIdx = (page - 1) * ACCSABER_LEADERBOARD_SCORES_PER_PAGE; if (data.scores.length < startIdx + 1) return data; return { ...data, - scores: data.scores - .slice(startIdx, startIdx + ACCSABER_LEADERBOARD_SCORES_PER_PAGE) - } - } + scores: data.scores.slice( + startIdx, + startIdx + ACCSABER_LEADERBOARD_SCORES_PER_PAGE, + ), + }; + }; - const getFriendsLeaderboard = async (leaderboardId, priority = PRIORITY.FG_LOW, signal = null) => { - const leaderboard = await resolvePromiseOrWaitForPending(`pageClient/leaderboard/${leaderboardId}/1`, () => leaderboardPageClient.getProcessed({leaderboardId, page: 1, signal, priority, cacheTtl: MINUTE})); + const getFriendsLeaderboard = async ( + leaderboardId, + priority = PRIORITY.FG_LOW, + signal = null, + ) => { + const leaderboard = await resolvePromiseOrWaitForPending( + `pageClient/leaderboard/${leaderboardId}/1`, + () => + leaderboardPageClient.getProcessed({ + leaderboardId, + page: 1, + signal, + priority, + cacheTtl: MINUTE, + }), + ); - const friends = convertArrayToObjectByKey(await friendsPromise, 'playerId'); + const friends = convertArrayToObjectByKey(await friendsPromise, "playerId"); const scores = (await scoresService.getLeaderboardScores(leaderboardId)) - .map(score => { + .map((score) => { if (!score || !score.playerId || !friends[score.playerId]) return null; const player = friends[score.playerId]; return { - player: {playerId: player.playerId, name: player.name, playerInfo: {...player.playerInfo}}, - score: {...score.score}, - } + player: { + playerId: player.playerId, + name: player.name, + playerInfo: { ...player.playerInfo }, + }, + score: { ...score.score }, + }; }) - .filter(s => s) - .sort((a, b) => opt(b, 'score.score', 0) - opt(a, 'score.score', 0)) + .filter((s) => s) + .sort((a, b) => opt(b, "score.score", 0) - opt(a, "score.score", 0)) .map((score, idx) => ({ player: score.player, - score: {...score.score, rank: idx + 1, timeSetString: formatDateRelative(score.score.timeSet)}, - })) - ; - - return {...leaderboard, scores, pageQty: 1, totalItems: scores.length}; - } + score: { + ...score.score, + rank: idx + 1, + timeSetString: formatDateRelative(score.score.timeSet), + }, + })); + return { ...leaderboard, scores, pageQty: 1, totalItems: scores.length }; + }; const destroyService = () => { service = null; - } + }; service = { fetchPage, @@ -100,7 +139,7 @@ export default () => { getFriendsLeaderboard, LEADERBOARD_SCORES_PER_PAGE, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/player.js b/src/services/scoresaber/player.js index 683b15b..c0e2de8 100644 --- a/src/services/scoresaber/player.js +++ b/src/services/scoresaber/player.js @@ -1,12 +1,12 @@ -import eventBus from '../../utils/broadcast-channel-pubsub' -import {configStore} from '../../stores/config' -import playerApiClient from '../../network/clients/scoresaber/player/api' -import playerFindApiClient from '../../network/clients/scoresaber/players/api-player-find' -import playerPageClient from '../../network/clients/scoresaber/player/page' -import {PRIORITY} from '../../network/queues/http-queue' -import playersRepository from '../../db/repository/players' -import playersHistoryRepository from '../../db/repository/players-history' -import log from '../../utils/logger' +import eventBus from "../../utils/broadcast-channel-pubsub"; +import { configStore } from "../../stores/config"; +import playerApiClient from "../../network/clients/scoresaber/player/api"; +import playerFindApiClient from "../../network/clients/scoresaber/players/api-player-find"; +import playerPageClient from "../../network/clients/scoresaber/player/page"; +import { PRIORITY } from "../../network/queues/http-queue"; +import playersRepository from "../../db/repository/players"; +import playersHistoryRepository from "../../db/repository/players-history"; +import log from "../../utils/logger"; import { addToDate, formatDate, @@ -14,12 +14,12 @@ import { SECOND, toSsMidnight, truncateDate, -} from '../../utils/date' -import {opt} from '../../utils/js' -import {db} from '../../db/db' -import makePendingPromisePool from '../../utils/pending-promises' -import {worker} from '../../utils/worker-wrappers' -import {getServicePlayerGain} from '../utils' +} from "../../utils/date"; +import { opt } from "../../utils/js"; +import { db } from "../../db/db"; +import makePendingPromisePool from "../../utils/pending-promises"; +import { worker } from "../../utils/worker-wrappers"; +import { getServicePlayerGain } from "../utils"; const MAIN_PLAYER_REFRESH_INTERVAL = MINUTE * 3; const PLAYER_REFRESH_INTERVAL = MINUTE * 20; @@ -34,91 +34,128 @@ export default () => { const resolvePromiseOrWaitForPending = makePendingPromisePool(); - const configStoreUnsubscribe = configStore.subscribe(config => { - const newMainPlayerId = opt(config, 'users.main') + const configStoreUnsubscribe = configStore.subscribe((config) => { + const newMainPlayerId = opt(config, "users.main"); if (mainPlayerId !== newMainPlayerId) { mainPlayerId = newMainPlayerId; - log.debug(`Main player changed to ${mainPlayerId}`, 'PlayerService') + log.debug(`Main player changed to ${mainPlayerId}`, "PlayerService"); } - }) + }); - const isMainPlayer = playerId => mainPlayerId && playerId === mainPlayerId; + const isMainPlayer = (playerId) => mainPlayerId && playerId === mainPlayerId; const getAll = async (force = false) => playersRepository().getAll(force); // TODO: just for now - const getFriends = async () => (await getAll()).filter(player => player && player.playerId && !isPlayerMain(player.playerId)).map(p => p.playerId); + const getFriends = async () => + (await getAll()) + .filter( + (player) => player && player.playerId && !isPlayerMain(player.playerId), + ) + .map((p) => p.playerId); const getAllActive = async () => { const players = await getAll(); if (!players) return []; - return players.filter(player => player && player.playerInfo && !player.playerInfo.inactive && !player.playerInfo.banned); - } + return players.filter( + (player) => + player && + player.playerInfo && + !player.playerInfo.inactive && + !player.playerInfo.banned, + ); + }; - const getPlayer = async playerId => await playersRepository().get(playerId); + const getPlayer = async (playerId) => await playersRepository().get(playerId); const removePlayer = async (playerId, purgeScores = false) => { await playersRepository().delete(playerId); // TODO: purge scores if requested - eventBus.publish('player-profile-removed', playerId); - } + eventBus.publish("player-profile-removed", playerId); + }; const addPlayer = async (playerId, priority = PRIORITY.FG_LOW) => { - log.trace(`Starting to add a player "${playerId}"...`, 'PlayerService'); + log.trace(`Starting to add a player "${playerId}"...`, "PlayerService"); const player = await refresh(playerId, true, priority, false, true); if (!player) { - log.warn(`Can not add player "${playerId}"`, 'PlayerService'); + log.warn(`Can not add player "${playerId}"`, "PlayerService"); return null; } - eventBus.publish('player-profile-added', player); - eventBus.publish('player-profile-changed', player); + eventBus.publish("player-profile-added", player); + eventBus.publish("player-profile-changed", player); - log.trace(`Player "${playerId}" added.`, 'PlayerService') + log.trace(`Player "${playerId}" added.`, "PlayerService"); return player; - } + }; const setPlayer = async (player) => { await playersRepository().set(player); - eventBus.publish('player-profile-changed', player); + eventBus.publish("player-profile-changed", player); return player; - } + }; - const updatePlayer = async (player, waitForSaving = true, forceAdd = false) => { + const updatePlayer = async ( + player, + waitForSaving = true, + forceAdd = false, + ) => { if (!player || !player.playerId) { - log.warn(`Can not update player, empty playerId`, 'PlayerService', player) + log.warn( + `Can not update player, empty playerId`, + "PlayerService", + player, + ); } const dbPlayer = await getPlayer(player.playerId); if (!dbPlayer && !forceAdd) return player; - const finalPlayer = {...dbPlayer, ...player} + const finalPlayer = { ...dbPlayer, ...player }; if (!waitForSaving) { - setPlayer(finalPlayer).then(_ => _) + setPlayer(finalPlayer).then((_) => _); return finalPlayer; } return await setPlayer(finalPlayer); - } + }; - const getPlayerHistory = async playerId => resolvePromiseOrWaitForPending(`playerHistory/${playerId}`, () => playersHistoryRepository().getAllFromIndex('players-history-playerId', playerId)) + const getPlayerHistory = async (playerId) => + resolvePromiseOrWaitForPending(`playerHistory/${playerId}`, () => + playersHistoryRepository().getAllFromIndex( + "players-history-playerId", + playerId, + ), + ); - const getPlayerGain = (playerHistory, daysAgo = 1, maxDaysAgo = 7) => getServicePlayerGain(playerHistory, toSsMidnight, 'ssDate', daysAgo, maxDaysAgo); + const getPlayerGain = (playerHistory, daysAgo = 1, maxDaysAgo = 7) => + getServicePlayerGain( + playerHistory, + toSsMidnight, + "ssDate", + daysAgo, + maxDaysAgo, + ); - const updatePlayerHistory = async player => { + const updatePlayerHistory = async (player) => { if (!player) return null; - const {playerId, profileLastUpdated, playerInfo: {banned, countries, inactive, pp, rank}, scoreStats} = player; + const { + playerId, + profileLastUpdated, + playerInfo: { banned, countries, inactive, pp, rank }, + scoreStats, + } = player; if (!playerId) return null; @@ -130,65 +167,87 @@ export default () => { const playerIdLocalTimestamp = `${playerId}_${localDate.getTime()}`; const playerIdSsTimestamp = `${playerId}_${ssDate.getTime()}`; - return playersHistoryRepository().getFromIndex('players-history-playerIdSsTimestamp', playerIdSsTimestamp) - .then(async ph => { + return playersHistoryRepository() + .getFromIndex("players-history-playerIdSsTimestamp", playerIdSsTimestamp) + .then(async (ph) => { if (ph && ph._idbId) { await playersHistoryRepository().delete(ph._idbId); - const {_idbId, ...previous} = ph; + const { _idbId, ...previous } = ph; return previous; } return null; }) - .then(async previous => { + .then(async (previous) => { let accStats = {}; if (worker) { const stats = await worker.calcPlayerStats(playerId); - const ppBoundary = await worker.calcPpBoundary(playerId) ?? null; + const ppBoundary = (await worker.calcPpBoundary(playerId)) ?? null; - const {badges, totalScore, playCount, ...playerStats} = stats ?? {}; + const { badges, totalScore, playCount, ...playerStats } = stats ?? {}; - accStats = {...playerStats} + accStats = { ...playerStats }; if (ppBoundary) accStats.ppBoundary = ppBoundary; - if (badges?.length) accStats.accBadges = badges.reduce((cum, b) => ({...cum, [b.label]: b.value}), {}); + if (badges?.length) + accStats.accBadges = badges.reduce( + (cum, b) => ({ ...cum, [b.label]: b.value }), + {}, + ); } return playersHistoryRepository().set({ ...previous, ...accStats, - playerId, banned, countries, inactive, pp, rank, ...scoreStats, - localDate, ssDate, + playerId, + banned, + countries, + inactive, + pp, + rank, + ...scoreStats, + localDate, + ssDate, playerIdLocalTimestamp, playerIdSsTimestamp, - }) + }); }) - .catch(err => {}) // swallow error - } + .catch((err) => {}); // swallow error + }; - const isPlayerMain = playerId => playerId === mainPlayerId; + const isPlayerMain = (playerId) => playerId === mainPlayerId; const getProfileFreshnessDate = (player, refreshInterval = null) => { - const lastUpdated = player && player.profileLastUpdated ? player.profileLastUpdated : null; + const lastUpdated = + player && player.profileLastUpdated ? player.profileLastUpdated : null; if (!lastUpdated) return addToDate(-SECOND); - const REFRESH_INTERVAL = refreshInterval ? refreshInterval : (isPlayerMain(player.playerId) ? MAIN_PLAYER_REFRESH_INTERVAL : PLAYER_REFRESH_INTERVAL); + const REFRESH_INTERVAL = refreshInterval + ? refreshInterval + : isPlayerMain(player.playerId) + ? MAIN_PLAYER_REFRESH_INTERVAL + : PLAYER_REFRESH_INTERVAL; return addToDate(REFRESH_INTERVAL, lastUpdated); - } + }; - const isProfileFresh = (player, refreshInterval = null) => getProfileFreshnessDate(player, refreshInterval) > new Date(); + const isProfileFresh = (player, refreshInterval = null) => + getProfileFreshnessDate(player, refreshInterval) > new Date(); - const updatePlayerRecentPlay = async (playerId, recentPlay, recentPlayLastUpdated = new Date()) => { + const updatePlayerRecentPlay = async ( + playerId, + recentPlay, + recentPlayLastUpdated = new Date(), + ) => { let player; try { - await db.runInTransaction(['players'], async tx => { - const playersStore = tx.objectStore('players') + await db.runInTransaction(["players"], async (tx) => { + const playersStore = tx.objectStore("players"); player = await playersStore.get(playerId); if (player) { player.recentPlayLastUpdated = recentPlayLastUpdated; @@ -200,61 +259,135 @@ export default () => { if (player) { playersRepository().addToCache([player]); - eventBus.publish('player-profile-changed', player); + eventBus.publish("player-profile-changed", player); - eventBus.publish('player-recent-play-updated', {playerId, player, recentPlay, recentPlayLastUpdated}); + eventBus.publish("player-recent-play-updated", { + playerId, + player, + recentPlay, + recentPlayLastUpdated, + }); } - } - catch(err) { - // swallow error - } - } - - const fetchPlayerAndUpdateRecentPlay = async playerId => { - try { - const player = await resolvePromiseOrWaitForPending(`pageClient/${playerId}`, () =>playerPageClient.getProcessed({playerId})); - const recentPlay = opt(player, 'playerInfo.recentPlay'); - const recentPlayLastUpdated = opt(player, 'playerInfo.recentPlayLastUpdated'); - if (!recentPlay || !recentPlayLastUpdated) return null; - - return updatePlayerRecentPlay(playerId, recentPlay, recentPlayLastUpdated); } catch (err) { // swallow error } - } + }; - const isResponseCached = response => playerApiClient.isResponseCached(response); - const getDataFromResponse = response => playerApiClient.getDataFromResponse(response); + const fetchPlayerAndUpdateRecentPlay = async (playerId) => { + try { + const player = await resolvePromiseOrWaitForPending( + `pageClient/${playerId}`, + () => playerPageClient.getProcessed({ playerId }), + ); + const recentPlay = opt(player, "playerInfo.recentPlay"); + const recentPlayLastUpdated = opt( + player, + "playerInfo.recentPlayLastUpdated", + ); + if (!recentPlay || !recentPlayLastUpdated) return null; - const fetchPlayer = async (playerId, priority = PRIORITY.FG_LOW, {fullResponse = false, ...options} = {}) => resolvePromiseOrWaitForPending(`apiClient/${playerId}/${fullResponse}`, () => playerApiClient.getProcessed({...options, playerId, priority, fullResponse})); + return updatePlayerRecentPlay( + playerId, + recentPlay, + recentPlayLastUpdated, + ); + } catch (err) { + // swallow error + } + }; - const findPlayer = async (query, priority = PRIORITY.FG_LOW, {fullResponse = false, ...options} = {}) => resolvePromiseOrWaitForPending(`apiClient/find/${query}/${fullResponse}`, () => playerFindApiClient.getProcessed({...options, query, priority, fullResponse})); + const isResponseCached = (response) => + playerApiClient.isResponseCached(response); + const getDataFromResponse = (response) => + playerApiClient.getDataFromResponse(response); - const fetchPlayerOrGetFromCache = async (playerId, refreshInterval = MINUTE, priority = PRIORITY.FG_LOW, signal = null, force = false) => { + const fetchPlayer = async ( + playerId, + priority = PRIORITY.FG_LOW, + { fullResponse = false, ...options } = {}, + ) => + resolvePromiseOrWaitForPending( + `apiClient/${playerId}/${fullResponse}`, + () => + playerApiClient.getProcessed({ + ...options, + playerId, + priority, + fullResponse, + }), + ); + + const findPlayer = async ( + query, + priority = PRIORITY.FG_LOW, + { fullResponse = false, ...options } = {}, + ) => + resolvePromiseOrWaitForPending( + `apiClient/find/${query}/${fullResponse}`, + () => + playerFindApiClient.getProcessed({ + ...options, + query, + priority, + fullResponse, + }), + ); + + const fetchPlayerOrGetFromCache = async ( + playerId, + refreshInterval = MINUTE, + priority = PRIORITY.FG_LOW, + signal = null, + force = false, + ) => { const player = await getPlayer(playerId); if (!player || !isProfileFresh(player, refreshInterval)) { - const fetchedPlayerResponse = await fetchPlayer(playerId, priority, {signal, cacheTtl: MINUTE, maxAge: force ? 0 : refreshInterval, fullResponse: true}); - if (isResponseCached(fetchedPlayerResponse)) return getDataFromResponse(fetchedPlayerResponse); + const fetchedPlayerResponse = await fetchPlayer(playerId, priority, { + signal, + cacheTtl: MINUTE, + maxAge: force ? 0 : refreshInterval, + fullResponse: true, + }); + if (isResponseCached(fetchedPlayerResponse)) + return getDataFromResponse(fetchedPlayerResponse); - return updatePlayer({...player, ...getDataFromResponse(fetchedPlayerResponse), profileLastUpdated: new Date()}, false) - .then(player => { - fetchPlayerAndUpdateRecentPlay(player.playerId); + return updatePlayer( + { + ...player, + ...getDataFromResponse(fetchedPlayerResponse), + profileLastUpdated: new Date(), + }, + false, + ).then((player) => { + fetchPlayerAndUpdateRecentPlay(player.playerId); - updatePlayerHistory(player); + updatePlayerHistory(player); - return player; - }) + return player; + }); } return player; - } + }; - const refresh = async (playerId, force = false, priority = PRIORITY.BG_NORMAL, throwErrors = false, addIfNotExists = false) => { - log.trace(`Starting refreshing player "${playerId}" ${force ? ' (forced)' : ''}...`, 'PlayerService') + const refresh = async ( + playerId, + force = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + addIfNotExists = false, + ) => { + log.trace( + `Starting refreshing player "${playerId}" ${force ? " (forced)" : ""}...`, + "PlayerService", + ); if (!playerId) { - log.warn(`Can not refresh player if an empty playerId is given`, 'PlayerService'); + log.warn( + `Can not refresh player if an empty playerId is given`, + "PlayerService", + ); return null; } @@ -262,66 +395,101 @@ export default () => { try { let player = await getPlayer(playerId); if (!player && !addIfNotExists) { - log.debug(`Profile is not added to DB, skipping.`, 'PlayerService') + log.debug(`Profile is not added to DB, skipping.`, "PlayerService"); return null; } - log.trace(`Player fetched from DB`, 'PlayerService', player); + log.trace(`Player fetched from DB`, "PlayerService", player); if (!force) { const profileFreshnessDate = getProfileFreshnessDate(player); if (profileFreshnessDate > new Date()) { - - log.debug(`Profile is still fresh, skipping. Next refresh on ${formatDate(profileFreshnessDate)}`, 'PlayerService') + log.debug( + `Profile is still fresh, skipping. Next refresh on ${formatDate( + profileFreshnessDate, + )}`, + "PlayerService", + ); return player; } } - log.trace(`Fetching player ${playerId} from ScoreSaber...`, 'PlayerService') + log.trace( + `Fetching player ${playerId} from ScoreSaber...`, + "PlayerService", + ); const fetchedPlayer = await fetchPlayer(playerId, priority); - if (!fetchedPlayer || !fetchedPlayer.playerId || !fetchedPlayer.name || !fetchedPlayer.playerInfo || !fetchedPlayer.scoreStats) { - log.warn(`ScoreSaber returned empty info for player ${playerId}`, 'PlayerService') + if ( + !fetchedPlayer || + !fetchedPlayer.playerId || + !fetchedPlayer.name || + !fetchedPlayer.playerInfo || + !fetchedPlayer.scoreStats + ) { + log.warn( + `ScoreSaber returned empty info for player ${playerId}`, + "PlayerService", + ); return null; } - log.trace(`Player fetched`, 'PlayerService', fetchedPlayer); + log.trace(`Player fetched`, "PlayerService", fetchedPlayer); - player = await updatePlayer({...fetchedPlayer, profileLastUpdated: new Date()}, true, addIfNotExists); + player = await updatePlayer( + { ...fetchedPlayer, profileLastUpdated: new Date() }, + true, + addIfNotExists, + ); - updatePlayerHistory(player).then(_ => _); + updatePlayerHistory(player).then((_) => _); - log.debug(`Player refreshed.`, 'PlayerService', player); + log.debug(`Player refreshed.`, "PlayerService", player); return player; } catch (e) { if (throwErrors) throw e; - log.debug(`Player refreshing error${e.toString ? `: ${e.toString()}` : ''}`, 'PlayerService', e) + log.debug( + `Player refreshing error${e.toString ? `: ${e.toString()}` : ""}`, + "PlayerService", + e, + ); return null; } - } + }; - const refreshAll = async (force = false, priority = PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting refreshing all players${force ? ' (forced)' : ''}...`, 'PlayerService'); + const refreshAll = async ( + force = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting refreshing all players${force ? " (forced)" : ""}...`, + "PlayerService", + ); const allPlayers = await getAll(); if (!allPlayers || !allPlayers.length) { - log.trace(`No players in DB, skipping.`, 'PlayerService'); + log.trace(`No players in DB, skipping.`, "PlayerService"); return null; } - const allRefreshed = await Promise.all(allPlayers.map(player => refresh(player.playerId, force, priority, throwErrors))); + const allRefreshed = await Promise.all( + allPlayers.map((player) => + refresh(player.playerId, force, priority, throwErrors), + ), + ); - log.trace(`All players refreshed.`, 'PlayerService', allRefreshed); + log.trace(`All players refreshed.`, "PlayerService", allRefreshed); return allRefreshed; - } + }; const destroyService = () => { serviceCreationCount--; @@ -331,7 +499,7 @@ export default () => { service = null; } - } + }; service = { isMainPlayer, @@ -356,7 +524,7 @@ export default () => { destroyService, isResponseCached, getDataFromResponse, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/pp.js b/src/services/scoresaber/pp.js index 05686e0..d1349a7 100644 --- a/src/services/scoresaber/pp.js +++ b/src/services/scoresaber/pp.js @@ -1,6 +1,6 @@ -import createScoresService from './scores' -import makePendingPromisePool from '../../utils/pending-promises' -import {getTotalPpFromSortedPps} from '../../utils/scoresaber/pp' +import createScoresService from "./scores"; +import makePendingPromisePool from "../../utils/pending-promises"; +import { getTotalPpFromSortedPps } from "../../utils/scoresaber/pp"; let service = null; let serviceCreationCount = 0; @@ -12,28 +12,32 @@ export default () => { const resolvePromiseOrWaitForPending = makePendingPromisePool(); - const getTotalPp = scores => scores && Array.isArray(scores) - ? getTotalPpFromSortedPps( - scores - .filter(s => s.pp > 0) - .map(s => s.pp) - .sort((a, b) => b - a), - ) - : null; + const getTotalPp = (scores) => + scores && Array.isArray(scores) + ? getTotalPpFromSortedPps( + scores + .filter((s) => s.pp > 0) + .map((s) => s.pp) + .sort((a, b) => b - a), + ) + : null; - const getTotalPlayerPp = async (playerId, modifiedScores = {}) => getTotalPp( - Object.values({ - ...(await resolvePromiseOrWaitForPending(`scores/${playerId}`, () => scoresService.getPlayerScoresAsObject(playerId))), - ...modifiedScores, - }), - ); + const getTotalPlayerPp = async (playerId, modifiedScores = {}) => + getTotalPp( + Object.values({ + ...(await resolvePromiseOrWaitForPending(`scores/${playerId}`, () => + scoresService.getPlayerScoresAsObject(playerId), + )), + ...modifiedScores, + }), + ); async function getWhatIfScore(playerId, leaderboardId, pp = 0) { const currentTotalPp = await getTotalPlayerPp(playerId); if (!currentTotalPp) return null; const newTotalPp = await getTotalPlayerPp(playerId, { - [leaderboardId]: {pp}, + [leaderboardId]: { pp }, }); return { @@ -67,7 +71,7 @@ export default () => { if (!acc || acc <= 0) { return 0; } - let index = ppCurve.findIndex(o => o.at >= acc); + let index = ppCurve.findIndex((o) => o.at >= acc); if (index === -1) { return ppCurve[ppCurve.length - 1].value; } @@ -83,7 +87,7 @@ export default () => { function accFromPpFactor(ppFactor) { if (!ppFactor || ppFactor <= 0) return 0; - const idx = ppCurve.findIndex(o => o.value >= ppFactor); + const idx = ppCurve.findIndex((o) => o.value >= ppFactor); if (idx < 0) return ppCurve[ppCurve.length - 1].at; const from = ppCurve[idx - 1]; @@ -101,7 +105,7 @@ export default () => { service = null; } - } + }; service = { getWhatIfScore, @@ -111,7 +115,7 @@ export default () => { accFromPpFactor, PP_PER_STAR, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/rankeds.js b/src/services/scoresaber/rankeds.js index 71bbf39..aeee8fe 100644 --- a/src/services/scoresaber/rankeds.js +++ b/src/services/scoresaber/rankeds.js @@ -1,13 +1,17 @@ -import {db} from '../../db/db' -import queues from '../../network/queues/queues'; -import rankedsPageClient from '../../network/clients/scoresaber/rankeds/page'; -import eventBus from '../../utils/broadcast-channel-pubsub' -import {arrayDifference, convertArrayToObjectByKey, opt} from '../../utils/js' -import rankedsRepository from '../../db/repository/rankeds' -import rankedsChangesRepository from '../../db/repository/rankeds-changes' -import keyValueRepository from '../../db/repository/key-value' -import log from '../../utils/logger' -import {addToDate, formatDate, HOUR} from '../../utils/date' +import { db } from "../../db/db"; +import queues from "../../network/queues/queues"; +import rankedsPageClient from "../../network/clients/scoresaber/rankeds/page"; +import eventBus from "../../utils/broadcast-channel-pubsub"; +import { + arrayDifference, + convertArrayToObjectByKey, + opt, +} from "../../utils/js"; +import rankedsRepository from "../../db/repository/rankeds"; +import rankedsChangesRepository from "../../db/repository/rankeds-changes"; +import keyValueRepository from "../../db/repository/key-value"; +import log from "../../utils/logger"; +import { addToDate, formatDate, HOUR } from "../../utils/date"; const REFRESH_INTERVAL = HOUR; @@ -16,16 +20,27 @@ export default () => { if (service) return service; const getRankeds = async () => { - const dbRankeds = await rankedsRepository().getAll() + const dbRankeds = await rankedsRepository().getAll(); - return dbRankeds ? convertArrayToObjectByKey(dbRankeds, 'leaderboardId') : {} - } + return dbRankeds + ? convertArrayToObjectByKey(dbRankeds, "leaderboardId") + : {}; + }; - const getLastUpdated = async () => keyValueRepository().get('rankedsLastUpdated'); - const setLastUpdated = async date => keyValueRepository().set(date, 'rankedsLastUpdated'); + const getLastUpdated = async () => + keyValueRepository().get("rankedsLastUpdated"); + const setLastUpdated = async (date) => + keyValueRepository().set(date, "rankedsLastUpdated"); - const refreshRankeds = async (forceUpdate = false, priority = queues.PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting rankeds refreshing${forceUpdate ? ' (forced)' : ''}...`, 'RankedsService') + const refreshRankeds = async ( + forceUpdate = false, + priority = queues.PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting rankeds refreshing${forceUpdate ? " (forced)" : ""}...`, + "RankedsService", + ); try { let fetchedRankedSongs; @@ -33,40 +48,50 @@ export default () => { if (!forceUpdate) { const lastUpdated = await getLastUpdated(); if (lastUpdated && lastUpdated > new Date() - REFRESH_INTERVAL) { - log.debug(`Refresh interval not yet expired, skipping. Next refresh on ${formatDate(addToDate(REFRESH_INTERVAL, lastUpdated))}`, 'RankedsService') + log.debug( + `Refresh interval not yet expired, skipping. Next refresh on ${formatDate( + addToDate(REFRESH_INTERVAL, lastUpdated), + )}`, + "RankedsService", + ); return null; } } - log.trace(`Fetching current rankeds from ScoreSaber...`, 'RankedsService') - fetchedRankedSongs = await rankedsPageClient.getProcessed({priority}); + log.trace( + `Fetching current rankeds from ScoreSaber...`, + "RankedsService", + ); + fetchedRankedSongs = await rankedsPageClient.getProcessed({ priority }); if (!fetchedRankedSongs || !fetchedRankedSongs.length) { - log.warn(`ScoreSaber returned empty rankeds list`, 'RankedsService') + log.warn(`ScoreSaber returned empty rankeds list`, "RankedsService"); return null; } - log.trace('Fetching rankeds from DB', 'RankedsService'); + log.trace("Fetching rankeds from DB", "RankedsService"); const oldRankedSongs = await getRankeds(); // add firstSeen & oldStars properties fetchedRankedSongs = convertArrayToObjectByKey( - fetchedRankedSongs.map(s => { - const firstSeen = oldRankedSongs[s.leaderboardId] && oldRankedSongs[s.leaderboardId].firstSeen - ? oldRankedSongs[s.leaderboardId].firstSeen - : new Date(); + fetchedRankedSongs.map((s) => { + const firstSeen = + oldRankedSongs[s.leaderboardId] && + oldRankedSongs[s.leaderboardId].firstSeen + ? oldRankedSongs[s.leaderboardId].firstSeen + : new Date(); - return {...s, firstSeen, oldStars: null} + return { ...s, firstSeen, oldStars: null }; }), - 'leaderboardId', + "leaderboardId", ); // find differences between old and new ranked songs const newRankeds = arrayDifference( Object.keys(fetchedRankedSongs), Object.keys(oldRankedSongs), - ).map(leaderboardId => ({ + ).map((leaderboardId) => ({ leaderboardId: parseInt(leaderboardId, 10), oldStars: null, stars: fetchedRankedSongs[leaderboardId].stars, @@ -74,77 +99,99 @@ export default () => { })); if (newRankeds && newRankeds.length) - log.debug(`${newRankeds.length} ranked(s) found`, 'RankedsService'); + log.debug(`${newRankeds.length} ranked(s) found`, "RankedsService"); const changed = // concat new rankeds with changed rankeds - newRankeds - .concat( - Object.values(oldRankedSongs) - .filter(s => s.stars !== (fetchedRankedSongs[s.leaderboardId] ? opt(fetchedRankedSongs[s.leaderboardId], 'stars', null) : null)) - .map(s => ({ - leaderboardId: s.leaderboardId, - oldStars: s.stars, - stars: opt(fetchedRankedSongs[s.leaderboardId], 'stars', null), - timestamp: Date.now(), - }), - ) - ); + newRankeds.concat( + Object.values(oldRankedSongs) + .filter( + (s) => + s.stars !== + (fetchedRankedSongs[s.leaderboardId] + ? opt(fetchedRankedSongs[s.leaderboardId], "stars", null) + : null), + ) + .map((s) => ({ + leaderboardId: s.leaderboardId, + oldStars: s.stars, + stars: opt(fetchedRankedSongs[s.leaderboardId], "stars", null), + timestamp: Date.now(), + })), + ); - if(newRankeds && changed && changed.length - newRankeds.length > 0) - log.debug(`${changed.length - newRankeds.length} changed ranked(s) found`, 'RankedsService'); + if (newRankeds && changed && changed.length - newRankeds.length > 0) + log.debug( + `${changed.length - newRankeds.length} changed ranked(s) found`, + "RankedsService", + ); const changedLeaderboards = changed - .map(s => { - const ranked = fetchedRankedSongs[s.leaderboardId] ? fetchedRankedSongs[s.leaderboardId] : oldRankedSongs[s.leaderboardId]; + .map((s) => { + const ranked = fetchedRankedSongs[s.leaderboardId] + ? fetchedRankedSongs[s.leaderboardId] + : oldRankedSongs[s.leaderboardId]; - return { - ...ranked, - ...s, - } - }, - ) - .filter(s => s && s.hash) - .map(l => { - const {oldStars, timestamp, ...leaderboard} = l; + return { + ...ranked, + ...s, + }; + }) + .filter((s) => s && s.hash) + .map((l) => { + const { oldStars, timestamp, ...leaderboard } = l; return leaderboard; }); - log.trace('Saving rankeds to DB...', 'RankedsService'); + log.trace("Saving rankeds to DB...", "RankedsService"); - await db.runInTransaction(['rankeds', 'rankeds-changes', 'key-value'], async tx => { - await Promise.all(changedLeaderboards.map(async ranked => rankedsRepository().set(ranked, undefined, tx))); - await Promise.all(changed.map(async rc => rankedsChangesRepository().set(rc, undefined, tx))); - await setLastUpdated(new Date()) - }); + await db.runInTransaction( + ["rankeds", "rankeds-changes", "key-value"], + async (tx) => { + await Promise.all( + changedLeaderboards.map(async (ranked) => + rankedsRepository().set(ranked, undefined, tx), + ), + ); + await Promise.all( + changed.map(async (rc) => + rankedsChangesRepository().set(rc, undefined, tx), + ), + ); + await setLastUpdated(new Date()); + }, + ); - log.trace('Rankeds saved', 'RankedsService'); + log.trace("Rankeds saved", "RankedsService"); if (changed.length) { - eventBus.publish('rankeds-changed', {changed, allRankeds: fetchedRankedSongs}); + eventBus.publish("rankeds-changed", { + changed, + allRankeds: fetchedRankedSongs, + }); } - log.debug(`Rankeds refreshing complete.`, 'RankedsService') + log.debug(`Rankeds refreshing complete.`, "RankedsService"); return changed; } catch (e) { if (throwErrors) throw e; - log.debug(`Rankeds refreshing error`, 'RankedsService', e) + log.debug(`Rankeds refreshing error`, "RankedsService", e); return null; } - } + }; const destroyService = () => { service = null; - } + }; service = { get: getRankeds, refresh: refreshRankeds, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/ranking.js b/src/services/scoresaber/ranking.js index 28fbcc2..e88cb91 100644 --- a/src/services/scoresaber/ranking.js +++ b/src/services/scoresaber/ranking.js @@ -1,10 +1,10 @@ -import playersGlobalRankingApiClient from '../../network/clients/scoresaber/players/api-ranking-global' -import playersGlobalRankingPagesApiClient from '../../network/clients/scoresaber/players/api-ranking-global-pages' -import playersCountryRankingPageClient from '../../network/clients/scoresaber/players/page-ranking-country' -import makePendingPromisePool from '../../utils/pending-promises' -import {PRIORITY} from '../../network/queues/http-queue' -import {PLAYERS_PER_PAGE} from '../../utils/scoresaber/consts' -import {opt} from '../../utils/js' +import playersGlobalRankingApiClient from "../../network/clients/scoresaber/players/api-ranking-global"; +import playersGlobalRankingPagesApiClient from "../../network/clients/scoresaber/players/api-ranking-global-pages"; +import playersCountryRankingPageClient from "../../network/clients/scoresaber/players/page-ranking-country"; +import makePendingPromisePool from "../../utils/pending-promises"; +import { PRIORITY } from "../../network/queues/http-queue"; +import { PLAYERS_PER_PAGE } from "../../utils/scoresaber/consts"; +import { opt } from "../../utils/js"; let service = null; export default () => { @@ -12,24 +12,52 @@ export default () => { const resolvePromiseOrWaitForPending = makePendingPromisePool(); - const fetchGlobal = async (page = 1, priority = PRIORITY.FG_LOW, signal = null) => resolvePromiseOrWaitForPending(`apiClient/ranking/global/${page}`, () => playersGlobalRankingApiClient.getProcessed({page, signal, priority})); + const fetchGlobal = async ( + page = 1, + priority = PRIORITY.FG_LOW, + signal = null, + ) => + resolvePromiseOrWaitForPending(`apiClient/ranking/global/${page}`, () => + playersGlobalRankingApiClient.getProcessed({ page, signal, priority }), + ); - const fetchCountry = async (country, page = 1, priority = PRIORITY.FG_LOW, signal = null) => resolvePromiseOrWaitForPending(`pageClient/ranking/${country}/${page}`, () => playersCountryRankingPageClient.getProcessed({country, page, signal, priority})); + const fetchCountry = async ( + country, + page = 1, + priority = PRIORITY.FG_LOW, + signal = null, + ) => + resolvePromiseOrWaitForPending( + `pageClient/ranking/${country}/${page}`, + () => + playersCountryRankingPageClient.getProcessed({ + country, + page, + signal, + priority, + }), + ); - const fetchGlobalPages = async (priority = PRIORITY.FG_LOW, signal = null) => resolvePromiseOrWaitForPending(`apiClient/rankingGlobalPages`, () => playersGlobalRankingPagesApiClient.getProcessed({signal, priority})); + const fetchGlobalPages = async (priority = PRIORITY.FG_LOW, signal = null) => + resolvePromiseOrWaitForPending(`apiClient/rankingGlobalPages`, () => + playersGlobalRankingPagesApiClient.getProcessed({ signal, priority }), + ); - const fetchGlobalCount = async (priority = PRIORITY.FG_LOW, signal = null) => { + const fetchGlobalCount = async ( + priority = PRIORITY.FG_LOW, + signal = null, + ) => { const pages = await fetchGlobalPages(priority, signal); if (!pages || !Number.isFinite(pages)) return 0; return pages * PLAYERS_PER_PAGE; - } + }; async function fetchMiniRanking(rank, country = null, numOfPlayers = 5) { try { if (!Number.isFinite(numOfPlayers)) numOfPlayers = 5; - const getPage = rank => Math.floor((rank - 1) / PLAYERS_PER_PAGE) + 1; + const getPage = (rank) => Math.floor((rank - 1) / PLAYERS_PER_PAGE) + 1; const playerPage = getPage(rank); let firstPlayerRank = rank - (numOfPlayers - (numOfPlayers > 2 ? 2 : 1)); @@ -38,25 +66,33 @@ export default () => { const lastPlayerRank = firstPlayerRank + numOfPlayers - 1; const lastPlayerRankPage = getPage(lastPlayerRank); - const pages = [...new Set([playerPage, firstPlayerRankPage, lastPlayerRankPage])].filter(p => p); + const pages = [ + ...new Set([playerPage, firstPlayerRankPage, lastPlayerRankPage]), + ].filter((p) => p); - const ranking = (await Promise.all(pages.map(async page => (country ? fetchCountry(country, page) : fetchGlobal(page))))) + const ranking = ( + await Promise.all( + pages.map(async (page) => + country ? fetchCountry(country, page) : fetchGlobal(page), + ), + ) + ) .reduce((cum, arr) => cum.concat(arr), []) - .filter(player => { - const rank = opt(player, 'playerInfo.rank') + .filter((player) => { + const rank = opt(player, "playerInfo.rank"); return rank >= firstPlayerRank && rank <= lastPlayerRank; }) - .sort((a,b) => opt(a, 'playerInfo.rank') - opt(b, 'playerInfo.rank')) + .sort((a, b) => opt(a, "playerInfo.rank") - opt(b, "playerInfo.rank")); return ranking; - } catch(err) { + } catch (err) { return null; } } const destroyService = () => { service = null; - } + }; service = { getGlobal: fetchGlobal, @@ -66,7 +102,7 @@ export default () => { getMiniRanking: fetchMiniRanking, PLAYERS_PER_PAGE, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/scoresaber/scores.js b/src/services/scoresaber/scores.js index 750bd31..0c089f6 100644 --- a/src/services/scoresaber/scores.js +++ b/src/services/scoresaber/scores.js @@ -1,23 +1,30 @@ -import {db} from '../../db/db' -import eventBus from '../../utils/broadcast-channel-pubsub' -import {configStore} from '../../stores/config' -import createPlayerService from './player'; -import createRankedsStore from '../../stores/scoresaber/rankeds' -import {PRIORITY} from '../../network/queues/http-queue' -import recentScoresApiClient from '../../network/clients/scoresaber/scores/api-recent' -import topScoresApiClient from '../../network/clients/scoresaber/scores/api-top' -import playersRepository from '../../db/repository/players' -import scoresRepository from '../../db/repository/scores' -import scoresUpdateQueueRepository from '../../db/repository/scores-update-queue' -import log from '../../utils/logger' -import {addToDate, formatDate, HOUR, MINUTE, SECOND, truncateDate} from '../../utils/date' -import {opt} from '../../utils/js' -import scores from '../../db/repository/scores' -import {SsrHttpNotFoundError} from '../../network/errors' -import {PLAYER_SCORES_PER_PAGE} from '../../utils/scoresaber/consts' -import makePendingPromisePool from '../../utils/pending-promises' -import {roundToPrecision} from '../../utils/format' -import {serviceFilterFunc} from '../utils' +import { db } from "../../db/db"; +import eventBus from "../../utils/broadcast-channel-pubsub"; +import { configStore } from "../../stores/config"; +import createPlayerService from "./player"; +import createRankedsStore from "../../stores/scoresaber/rankeds"; +import { PRIORITY } from "../../network/queues/http-queue"; +import recentScoresApiClient from "../../network/clients/scoresaber/scores/api-recent"; +import topScoresApiClient from "../../network/clients/scoresaber/scores/api-top"; +import playersRepository from "../../db/repository/players"; +import scoresRepository from "../../db/repository/scores"; +import scoresUpdateQueueRepository from "../../db/repository/scores-update-queue"; +import log from "../../utils/logger"; +import { + addToDate, + formatDate, + HOUR, + MINUTE, + SECOND, + truncateDate, +} from "../../utils/date"; +import { opt } from "../../utils/js"; +import scores from "../../db/repository/scores"; +import { SsrHttpNotFoundError } from "../../network/errors"; +import { PLAYER_SCORES_PER_PAGE } from "../../utils/scoresaber/consts"; +import makePendingPromisePool from "../../utils/pending-promises"; +import { roundToPrecision } from "../../utils/format"; +import { serviceFilterFunc } from "../utils"; const MAIN_PLAYER_REFRESH_INTERVAL = MINUTE * 3; const PLAYER_REFRESH_INTERVAL = MINUTE * 30; @@ -44,109 +51,155 @@ export default () => { let refreshCallCounter = 0; - const refreshingFinished = async (samplingTime = 100, timeout = 30000) => new Promise((resolve, reject) => { - let callCounter = 0; - const maxCallCount = samplingTime ? timeout / samplingTime : timeout; + const refreshingFinished = async (samplingTime = 100, timeout = 30000) => + new Promise((resolve, reject) => { + let callCounter = 0; + const maxCallCount = samplingTime ? timeout / samplingTime : timeout; - const sampler = () => { - if (refreshCallCounter === 0) { - resolve(true); - return; - } + const sampler = () => { + if (refreshCallCounter === 0) { + resolve(true); + return; + } - callCounter++; - if (callCounter > maxCallCount) { - reject(timeout); - return; - } + callCounter++; + if (callCounter > maxCallCount) { + reject(timeout); + return; + } - setTimeout(sampler, samplingTime); - } + setTimeout(sampler, samplingTime); + }; - sampler(); - }) + sampler(); + }); - const configStoreUnsubscribe = configStore.subscribe(config => { - const newMainPlayerId = opt(config, 'users.main') + const configStoreUnsubscribe = configStore.subscribe((config) => { + const newMainPlayerId = opt(config, "users.main"); if (mainPlayerId !== newMainPlayerId) { mainPlayerId = newMainPlayerId; - log.debug(`Main player changed to ${mainPlayerId}`, 'ScoresService') + log.debug(`Main player changed to ${mainPlayerId}`, "ScoresService"); } - }) + }); let rankedStoreUnsubscribe = null; - createRankedsStore().then(rankedStore => { - rankedStoreUnsubscribe = rankedStore.subscribe(rankeds => { - allRankeds = rankeds + createRankedsStore().then((rankedStore) => { + rankedStoreUnsubscribe = rankedStore.subscribe((rankeds) => { + allRankeds = rankeds; - log.debug(`Ranked songs updated`, 'ScoresService', allRankeds) - }) - }) + log.debug(`Ranked songs updated`, "ScoresService", allRankeds); + }); + }); - const isDataForPlayerAvailable = async playerId => (await Promise.all([ - scoresRepository().getFromIndex('scores-playerId', playerId), - playersRepository().get(playerId), - ])) - .every(p => p !== undefined); + const isDataForPlayerAvailable = async (playerId) => + ( + await Promise.all([ + scoresRepository().getFromIndex("scores-playerId", playerId), + playersRepository().get(playerId), + ]) + ).every((p) => p !== undefined); const getAllScores = async () => scoresRepository().getAll(); - const getLeaderboardScores = async leaderboardId => scoresRepository().getAllFromIndex('scores-leaderboardId', leaderboardId); - const getPlayerScores = async playerId => resolvePromiseOrWaitForPending(`getPlayerScores/${playerId}`, async () => { - return (await scoresRepository().getAllFromIndex('scores-playerId', playerId)) - .map(s => ({...s, leaderboard: {...s?.leaderboard, stars: allRankeds[s?.leaderboardId]?.stars ?? null}})) - }) - const getPlayerScoresAsObject = async (playerId, idFunc = score => opt(score, 'leaderboard.leaderboardId'), asArray = false) => convertScoresToObject(await getPlayerScores(playerId), idFunc, asArray) - const getPlayerSongScore = async (playerId, leaderboardId) => scoresRepository().get(playerId + '_' + leaderboardId); - const getPlayerRankedScores = async playerId => { - const [scores, rankeds] = await Promise.all([getPlayerScores(playerId), allRankeds]); + const getLeaderboardScores = async (leaderboardId) => + scoresRepository().getAllFromIndex("scores-leaderboardId", leaderboardId); + const getPlayerScores = async (playerId) => + resolvePromiseOrWaitForPending(`getPlayerScores/${playerId}`, async () => { + return ( + await scoresRepository().getAllFromIndex("scores-playerId", playerId) + ).map((s) => ({ + ...s, + leaderboard: { + ...s?.leaderboard, + stars: allRankeds[s?.leaderboardId]?.stars ?? null, + }, + })); + }); + const getPlayerScoresAsObject = async ( + playerId, + idFunc = (score) => opt(score, "leaderboard.leaderboardId"), + asArray = false, + ) => convertScoresToObject(await getPlayerScores(playerId), idFunc, asArray); + const getPlayerSongScore = async (playerId, leaderboardId) => + scoresRepository().get(playerId + "_" + leaderboardId); + const getPlayerRankedScores = async (playerId) => { + const [scores, rankeds] = await Promise.all([ + getPlayerScores(playerId), + allRankeds, + ]); if (!scores) return []; - return scores.filter(s => s.leaderboardId && rankeds[s.leaderboardId]); - } - const updateScore = async score => scoresRepository().set(score); + return scores.filter((s) => s.leaderboardId && rankeds[s.leaderboardId]); + }; + const updateScore = async (score) => scoresRepository().set(score); - const reduceScoresArr = scores => scores.reduce((allScores, scorePage) => [...allScores, ...scorePage], []); - const isAnyScoreOlderThan = (scores, olderThan) => scores.some(s => s.score && s.score.timeSet && s.score.timeSet <= olderThan); - const createFetchUntilLastUpdated = olderThan => scores => isAnyScoreOlderThan(scores, olderThan); + const reduceScoresArr = (scores) => + scores.reduce((allScores, scorePage) => [...allScores, ...scorePage], []); + const isAnyScoreOlderThan = (scores, olderThan) => + scores.some( + (s) => s.score && s.score.timeSet && s.score.timeSet <= olderThan, + ); + const createFetchUntilLastUpdated = (olderThan) => (scores) => + isAnyScoreOlderThan(scores, olderThan); - const convertScoresToObject = (scores, idFunc = score => opt(score, 'leaderboard.leaderboardId'), asArray = false) => scores.reduce((scoresObj, score) => { - const _id = idFunc(score); - if (!_id) return scoresObj; + const convertScoresToObject = ( + scores, + idFunc = (score) => opt(score, "leaderboard.leaderboardId"), + asArray = false, + ) => + scores.reduce((scoresObj, score) => { + const _id = idFunc(score); + if (!_id) return scoresObj; - if (asArray) { - if (!scoresObj[_id]) scoresObj[_id] = []; + if (asArray) { + if (!scoresObj[_id]) scoresObj[_id] = []; - scoresObj[_id].push({...score}) - } else { - scoresObj[_id] = {...score}; - } + scoresObj[_id].push({ ...score }); + } else { + scoresObj[_id] = { ...score }; + } - return scoresObj; - }, {}) + return scoresObj; + }, {}); const getScoreKey = (playerId, score) => { - const leaderboardId = opt(score, 'leaderboard.leaderboardId'); + const leaderboardId = opt(score, "leaderboard.leaderboardId"); if (!leaderboardId) return null; return `${playerId}_${leaderboardId}`; - } - const convertScoresById = (playerId, scores) => convertScoresToObject(scores, score => getScoreKey(playerId, score)); + }; + const convertScoresById = (playerId, scores) => + convertScoresToObject(scores, (score) => getScoreKey(playerId, score)); - const fetchScoresUntil = async (playerId, startPage = 1, priority = PRIORITY.BG_NORMAL, signal = null, untilFunc = null, dontReduce = false) => { - log.debug(`Fetching scores of player "${playerId}" starting from page #${startPage}`, 'ScoresService'); + const fetchScoresUntil = async ( + playerId, + startPage = 1, + priority = PRIORITY.BG_NORMAL, + signal = null, + untilFunc = null, + dontReduce = false, + ) => { + log.debug( + `Fetching scores of player "${playerId}" starting from page #${startPage}`, + "ScoresService", + ); let data = []; let page = startPage; while (page) { try { - log.trace(`Fetching scores page #${page}`, 'ScoresService'); + log.trace(`Fetching scores page #${page}`, "ScoresService"); - const pageData = await recentScoresApiClient.getProcessed({playerId, page, signal, priority}); - log.trace(`Scores page #${page} fetched`, 'ScoresService', pageData); + const pageData = await recentScoresApiClient.getProcessed({ + playerId, + page, + signal, + priority, + }); + log.trace(`Scores page #${page} fetched`, "ScoresService", pageData); if (!pageData) { - log.trace(`Scores page #${page} is empty`, 'ScoresService'); + log.trace(`Scores page #${page} is empty`, "ScoresService"); break; } @@ -158,7 +211,9 @@ export default () => { (untilFunc && untilFunc(pageData)) ) { // push only relevant scores and return - data.push(pageData.filter(score => !untilFunc || !untilFunc([score]))); + data.push( + pageData.filter((score) => !untilFunc || !untilFunc([score])), + ); break; } @@ -169,7 +224,7 @@ export default () => { if (!(err instanceof SsrHttpNotFoundError)) throw err; // stop fetching at 404 - log.trace(`Received 404 Not Found, abort download`, 'ScoresService'); + log.trace(`Received 404 Not Found, abort download`, "ScoresService"); break; } @@ -177,34 +232,67 @@ export default () => { } return dontReduce ? data : reduceScoresArr(data); - } + }; - const fetchAllScores = async (playerId, numOfPages, priority = PRIORITY.BG_NORMAL, signal = null) => { - log.debug(`Fetching all scores of player "${playerId}, number of pages: ${numOfPages}`, 'ScoresService'); + const fetchAllScores = async ( + playerId, + numOfPages, + priority = PRIORITY.BG_NORMAL, + signal = null, + ) => { + log.debug( + `Fetching all scores of player "${playerId}, number of pages: ${numOfPages}`, + "ScoresService", + ); - const pages = Array(numOfPages).fill(0).map((_, idx) => idx + 1); + const pages = Array(numOfPages) + .fill(0) + .map((_, idx) => idx + 1); - let data = await Promise.all(pages.map(page => recentScoresApiClient.getProcessed({playerId, page, signal, priority}))); + let data = await Promise.all( + pages.map((page) => + recentScoresApiClient.getProcessed({ + playerId, + page, + signal, + priority, + }), + ), + ); if (!data || !data.length) return []; if (data[data.length - 1].length === PLAYER_SCORES_PER_PAGE) { data = [ ...data, - ...(await fetchScoresUntil(playerId, data.length + 1, priority, signal, null, true)), + ...(await fetchScoresUntil( + playerId, + data.length + 1, + priority, + signal, + null, + true, + )), ]; } return reduceScoresArr(data); - } + }; - const getRecentPlayFromScores = (scores, defaultRecentPlay = null) => scores.reduce((recentPlay, s) => opt(s, 'score.timeSet') && s.score.timeSet > recentPlay ? s.score.timeSet : recentPlay, defaultRecentPlay); + const getRecentPlayFromScores = (scores, defaultRecentPlay = null) => + scores.reduce( + (recentPlay, s) => + opt(s, "score.timeSet") && s.score.timeSet > recentPlay + ? s.score.timeSet + : recentPlay, + defaultRecentPlay, + ); const addScoreIndexFields = (playerId, score) => { const id = getScoreKey(playerId, score); - const leaderboardId = opt(score, 'leaderboard.leaderboardId'); - const timeSet = opt(score, 'score.timeSet'); - const pp = opt(score, 'score.pp'); + const leaderboardId = opt(score, "leaderboard.leaderboardId"); + const timeSet = opt(score, "score.timeSet"); + const pp = opt(score, "score.pp"); return { ...score, @@ -212,99 +300,130 @@ export default () => { playerId, leaderboardId, timeSet, - pp - } - } + pp, + }; + }; const updateRankAndPpFromTheQueue = async () => { - log.debug('Processing rank and pp update queue', 'ScoresService'); + log.debug("Processing rank and pp update queue", "ScoresService"); try { - log.debug('Rank and pp update queue, waiting for the scores to finish refreshing.', 'ScoresService'); + log.debug( + "Rank and pp update queue, waiting for the scores to finish refreshing.", + "ScoresService", + ); await refreshingFinished(); - log.debug('Rank and pp update queue, scores refreshed, start queue processing.', 'ScoresService'); + log.debug( + "Rank and pp update queue, scores refreshed, start queue processing.", + "ScoresService", + ); - await db.runInTransaction(['scores-update-queue', 'scores'], async tx => { - // get all scores updates at least one minute old (some time to download new scores) - let cursor = await tx.objectStore('scores-update-queue').index('scores-update-queue-fetchedAt').openCursor(IDBKeyRange.upperBound(addToDate(-1 * MINUTE))); - const scoresStore = tx.objectStore('scores'); + await db.runInTransaction( + ["scores-update-queue", "scores"], + async (tx) => { + // get all scores updates at least one minute old (some time to download new scores) + let cursor = await tx + .objectStore("scores-update-queue") + .index("scores-update-queue-fetchedAt") + .openCursor(IDBKeyRange.upperBound(addToDate(-1 * MINUTE))); + const scoresStore = tx.objectStore("scores"); - while (cursor) { - try { - const scoreUpdate = {...cursor.value}; + while (cursor) { + try { + const scoreUpdate = { ...cursor.value }; - await cursor.delete(); + await cursor.delete(); + + if (!scoreUpdate.id) { + cursor = await cursor.continue(); + continue; + } + + const dbScore = await scoresStore.get(scoreUpdate.id); + if (!dbScore) { + cursor = await cursor.continue(); + continue; + } + + const scoreLastUpdated = dbScore.lastUpdated; + + if ( + (!scoreLastUpdated || + scoreLastUpdated < scoreUpdate.fetchedAt) && + (opt(dbScore, "score.scoreId") === + opt(scoreUpdate, "score.scoreId") || + opt(dbScore, "score.unmodifiedScore") <= + opt(scoreUpdate, "score.unmodifiedScore")) && + opt(scoreUpdate, "score.scoreId") && + !!opt(scoreUpdate, "score.timeSet") + ) { + dbScore.score = scoreUpdate.score; + + dbScore.pp = scoreUpdate.score.pp; + dbScore.timeSet = scoreUpdate.score.timeSet; + dbScore.lastUpdated = new Date(); + + await scoresStore.put(dbScore); + scoresRepository().addToCache([dbScore]); + } - if (!scoreUpdate.id) { cursor = await cursor.continue(); - continue; + } catch (err) { + // swallow error + if (cursor) cursor = await cursor.continue(); } - - const dbScore = await scoresStore.get(scoreUpdate.id) - if (!dbScore) { - cursor = await cursor.continue(); - continue; - } - - const scoreLastUpdated = dbScore.lastUpdated; - - if ( - (!scoreLastUpdated || scoreLastUpdated < scoreUpdate.fetchedAt) && - ( - opt(dbScore, 'score.scoreId') === opt(scoreUpdate, 'score.scoreId') || - (opt(dbScore, 'score.unmodifiedScore') <= opt(scoreUpdate, 'score.unmodifiedScore')) - ) && - opt(scoreUpdate, 'score.scoreId') && !!opt(scoreUpdate, 'score.timeSet') - ) { - dbScore.score = scoreUpdate.score; - - dbScore.pp = scoreUpdate.score.pp; - dbScore.timeSet = scoreUpdate.score.timeSet; - dbScore.lastUpdated = new Date(); - - await scoresStore.put(dbScore); - scoresRepository().addToCache([dbScore]) - } - - cursor = await cursor.continue(); - } catch (err) { - // swallow error - if (cursor) cursor = await cursor.continue(); } - } - }) + }, + ); - log.debug('Rank and pp update queue processed.', 'ScoresService'); + log.debug("Rank and pp update queue processed.", "ScoresService"); + } catch (err) { + log.debug( + "Rank and pp update queue has NOT been processed.", + "ScoresService", + ); } - catch(err) { - log.debug('Rank and pp update queue has NOT been processed.', 'ScoresService'); - } - } + }; - const addRankAndPpToUpdateQueue = async scoresToUpdate => { + const addRankAndPpToUpdateQueue = async (scoresToUpdate) => { if (!scoresToUpdate || !scoresToUpdate.length) return; - log.debug('Queueing rank and pp update for bunch of scores', 'ScoresService', scoresToUpdate); + log.debug( + "Queueing rank and pp update for bunch of scores", + "ScoresService", + scoresToUpdate, + ); try { - await Promise.all(scoresToUpdate.map(async s => scoresUpdateQueueRepository().set(s))) - } - catch(err) { + await Promise.all( + scoresToUpdate.map(async (s) => scoresUpdateQueueRepository().set(s)), + ); + } catch (err) { // swallow error } - log.debug('Scores rank & pp queued for update.', 'ScoresService', scoresToUpdate) - } + log.debug( + "Scores rank & pp queued for update.", + "ScoresService", + scoresToUpdate, + ); + }; const updatePlayerScores = async (player, priority = PRIORITY.BG_NORMAL) => { if (!player || !player.playerId) { - log.warn(`Can not refresh scores, empty playerId`, 'ScoresService', player); + log.warn( + `Can not refresh scores, empty playerId`, + "ScoresService", + player, + ); return null; } - const numOfScores = opt(player, 'scoreStats.totalPlayCount', null); - const numOfPages = numOfScores ? Math.ceil(numOfScores / PLAYER_SCORES_PER_PAGE) : null; + const numOfScores = opt(player, "scoreStats.totalPlayCount", null); + const numOfPages = numOfScores + ? Math.ceil(numOfScores / PLAYER_SCORES_PER_PAGE) + : null; const newLastUpdated = new Date(); @@ -312,8 +431,11 @@ export default () => { let newScores; const abortController = new AbortController(); - const playerScores = await getPlayerScores(player.playerId) - const currentScoresById = convertScoresById(player.playerId, playerScores); + const playerScores = await getPlayerScores(player.playerId); + const currentScoresById = convertScoresById( + player.playerId, + playerScores, + ); let mostRecentPlayFromScores = null; if (!player.recentPlay) { @@ -321,20 +443,44 @@ export default () => { player.recentPlay = mostRecentPlayFromScores; } - const startUpdatingDate = !player.scoresLastUpdated || (mostRecentPlayFromScores && mostRecentPlayFromScores < player.scoresLastUpdated) - ? mostRecentPlayFromScores - : player.scoresLastUpdated; + const startUpdatingDate = + !player.scoresLastUpdated || + (mostRecentPlayFromScores && + mostRecentPlayFromScores < player.scoresLastUpdated) + ? mostRecentPlayFromScores + : player.scoresLastUpdated; - if (numOfPages && !startUpdatingDate) newScores = await fetchAllScores(player.playerId, numOfPages, priority, abortController.signal); - else newScores = await fetchScoresUntil(player.playerId, 1, priority, abortController.signal, createFetchUntilLastUpdated(startUpdatingDate)) + if (numOfPages && !startUpdatingDate) + newScores = await fetchAllScores( + player.playerId, + numOfPages, + priority, + abortController.signal, + ); + else + newScores = await fetchScoresUntil( + player.playerId, + 1, + priority, + abortController.signal, + createFetchUntilLastUpdated(startUpdatingDate), + ); if (!newScores || !newScores.length) { // no new scores - just update player profile - const playerData = {...player, scoresLastUpdated: newLastUpdated, recentPlayLastUpdated: newLastUpdated} + const playerData = { + ...player, + scoresLastUpdated: newLastUpdated, + recentPlayLastUpdated: newLastUpdated, + }; await playersRepository().set(playerData); - return {recentPlay: player.recentPlay, newScores: null, scores: currentScoresById}; + return { + recentPlay: player.recentPlay, + newScores: null, + scores: currentScoresById, + }; } const recentPlay = getRecentPlayFromScores(newScores, player.recentPlay); @@ -342,8 +488,8 @@ export default () => { // TODO: calculate pp contribution of score let updatedScores = []; - await db.runInTransaction(['scores', 'players'], async tx => { - const playersStore = tx.objectStore('players') + await db.runInTransaction(["scores", "players"], async (tx) => { + const playersStore = tx.objectStore("players"); player = await playersStore.get(player.playerId); player.scoresLastUpdated = newLastUpdated; player.recentPlayLastUpdated = newLastUpdated; @@ -352,26 +498,41 @@ export default () => { await playersStore.put(player); playersRepository().addToCache([player]); - const scoresStore = tx.objectStore('scores'); + const scoresStore = tx.objectStore("scores"); - for(let score of newScores) { + for (let score of newScores) { const id = getScoreKey(player.playerId, score); - const leaderboardId = opt(score, 'leaderboard.leaderboardId'); - const scoreValue = opt(score, 'score.score'); - const unmodifiedScore = opt(score, 'score.unmodifiedScore') - const scoreTimeSet = opt(score, 'score.timeSet'); - const scorePp = opt(score, 'score.pp'); + const leaderboardId = opt(score, "leaderboard.leaderboardId"); + const scoreValue = opt(score, "score.score"); + const unmodifiedScore = opt(score, "score.unmodifiedScore"); + const scoreTimeSet = opt(score, "score.timeSet"); + const scorePp = opt(score, "score.pp"); - if (!id || !leaderboardId || !scoreTimeSet || scoreValue === undefined || scorePp === undefined) { + if ( + !id || + !leaderboardId || + !scoreTimeSet || + scoreValue === undefined || + scorePp === undefined + ) { return null; } - const dbScore = await scoresStore.get(id) + const dbScore = await scoresStore.get(id); if (dbScore) { - const prevScoreScorePart = {...dbScore.score}; - if (prevScoreScorePart && prevScoreScorePart.timeSet && prevScoreScorePart.score !== undefined && prevScoreScorePart.unmodifiedScore < unmodifiedScore) { - const prevHistory = opt(dbScore, 'history.length') ? dbScore.history.filter(h => h.timeSet) : []; - score.history = [prevScoreScorePart].concat(prevHistory).slice(0,3); + const prevScoreScorePart = { ...dbScore.score }; + if ( + prevScoreScorePart && + prevScoreScorePart.timeSet && + prevScoreScorePart.score !== undefined && + prevScoreScorePart.unmodifiedScore < unmodifiedScore + ) { + const prevHistory = opt(dbScore, "history.length") + ? dbScore.history.filter((h) => h.timeSet) + : []; + score.history = [prevScoreScorePart] + .concat(prevHistory) + .slice(0, 3); } } @@ -385,40 +546,63 @@ export default () => { } }); - return {player, recentPlay, newScores, scores: {...currentScoresById, ...convertScoresToObject(updatedScores, score => opt(score, 'id'))}}; + return { + player, + recentPlay, + newScores, + scores: { + ...currentScoresById, + ...convertScoresToObject(updatedScores, (score) => opt(score, "id")), + }, + }; } catch (err) { - if (![opt(err, 'name'), opt(err, 'message')].includes('AbortError')) throw err; + if (![opt(err, "name"), opt(err, "message")].includes("AbortError")) + throw err; return null; } - } + }; - const isPlayerMain = playerId => playerId === mainPlayerId; + const isPlayerMain = (playerId) => playerId === mainPlayerId; - const getScoresFreshnessDate = (player, refreshInterval = null, key = 'scoresLastUpdated') => { + const getScoresFreshnessDate = ( + player, + refreshInterval = null, + key = "scoresLastUpdated", + ) => { const lastUpdated = player && player[key] ? player[key] : null; if (!lastUpdated) return addToDate(-SECOND); - const REFRESH_INTERVAL = refreshInterval ? refreshInterval : (isPlayerMain(player.playerId) ? MAIN_PLAYER_REFRESH_INTERVAL : PLAYER_REFRESH_INTERVAL); + const REFRESH_INTERVAL = refreshInterval + ? refreshInterval + : isPlayerMain(player.playerId) + ? MAIN_PLAYER_REFRESH_INTERVAL + : PLAYER_REFRESH_INTERVAL; return addToDate(REFRESH_INTERVAL, lastUpdated); - } + }; - const isScoreDateFresh = (player, refreshInterval = null, key = 'scoresLastUpdated') => getScoresFreshnessDate(player, refreshInterval, key) > new Date(); + const isScoreDateFresh = ( + player, + refreshInterval = null, + key = "scoresLastUpdated", + ) => getScoresFreshnessDate(player, refreshInterval, key) > new Date(); - const getPlayerScoresPage = async (playerId, serviceParams = {sort: 'recent', order: 'desc', page: 1}) => { + const getPlayerScoresPage = async ( + playerId, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + ) => { let page = serviceParams?.page ?? 1; if (page < 1) page = 1; - let playerScores = (await getPlayerScores(playerId)); + let playerScores = await getPlayerScores(playerId); if (!playerScores || !playerScores.length) return null; - const {sort: sortFunc, filter: filterFunc} = getScoresHistogramDefinition(serviceParams); + const { sort: sortFunc, filter: filterFunc } = + getScoresHistogramDefinition(serviceParams); - playerScores = playerScores - .filter(filterFunc) - .sort(sortFunc); + playerScores = playerScores.filter(filterFunc).sort(sortFunc); const startIdx = (page - 1) * PLAYER_SCORES_PER_PAGE; @@ -426,13 +610,15 @@ export default () => { return { total: playerScores.length, - scores: playerScores.slice(startIdx, startIdx + PLAYER_SCORES_PER_PAGE) + scores: playerScores.slice(startIdx, startIdx + PLAYER_SCORES_PER_PAGE), }; - } + }; - const getScoresHistogramDefinition = (serviceParams = {sort: 'recent', order: 'desc'}) => { - const sort = serviceParams?.sort ?? 'recent'; - const order = serviceParams?.order ?? 'desc'; + const getScoresHistogramDefinition = ( + serviceParams = { sort: "recent", order: "desc" }, + ) => { + const sort = serviceParams?.sort ?? "recent"; + const order = serviceParams?.order ?? "desc"; const commonFilterFunc = serviceFilterFunc(serviceParams); @@ -442,82 +628,91 @@ export default () => { let maxBucketSize = null; let bucketSizeStep = null; let bucketSizeValues = null; - let type = 'linear'; - let valFunc = s => s; + let type = "linear"; + let valFunc = (s) => s; let filterFunc = commonFilterFunc; - let histogramFilterFunc = h => h; - let roundedValFunc = (s, type = type, precision = bucketSize) => type === 'linear' - ? roundToPrecision(valFunc(s), precision) - : truncateDate(valFunc(s), precision); - let prefix = ''; - let prefixLong = ''; - let suffix = ''; - let suffixLong = ''; + let histogramFilterFunc = (h) => h; + let roundedValFunc = (s, type = type, precision = bucketSize) => + type === "linear" + ? roundToPrecision(valFunc(s), precision) + : truncateDate(valFunc(s), precision); + let prefix = ""; + let prefixLong = ""; + let suffix = ""; + let suffixLong = ""; - switch(sort) { - case 'recent': - valFunc = s => s?.timeSet; - type = 'time'; - bucketSize = 'day' + switch (sort) { + case "recent": + valFunc = (s) => s?.timeSet; + type = "time"; + bucketSize = "day"; break; - case 'top': - valFunc = s => s?.pp ?? 0; - filterFunc = s => (s?.pp ?? 0) > 0 && commonFilterFunc(s) - type = 'linear'; + case "top": + valFunc = (s) => s?.pp ?? 0; + filterFunc = (s) => (s?.pp ?? 0) > 0 && commonFilterFunc(s); + type = "linear"; bucketSize = HISTOGRAM_PP_PRECISION; minBucketSize = 1; maxBucketSize = 100; bucketSizeStep = 1; round = 0; - suffix = 'pp'; - suffixLong = 'pp'; + suffix = "pp"; + suffixLong = "pp"; break; - case 'rank': - valFunc = s => s?.score?.rank ?? 1000000; - type = 'linear'; + case "rank": + valFunc = (s) => s?.score?.rank ?? 1000000; + type = "linear"; bucketSize = HISTOGRAM_RANK_PRECISION; minBucketSize = 1; maxBucketSize = 100; bucketSizeStep = 1; round = 0; - prefixLong = '#'; + prefixLong = "#"; break; - case 'acc': - valFunc = s => s?.score?.maxScore && s?.score?.unmodifiedScore ? s.score.unmodifiedScore / s.score.maxScore * 100 : (s?.score?.acc ?? null); - filterFunc = s => (valFunc(s) ?? 0) > 0 && commonFilterFunc(s) - type = 'linear'; + case "acc": + valFunc = (s) => + s?.score?.maxScore && s?.score?.unmodifiedScore + ? (s.score.unmodifiedScore / s.score.maxScore) * 100 + : s?.score?.acc ?? null; + filterFunc = (s) => (valFunc(s) ?? 0) > 0 && commonFilterFunc(s); + type = "linear"; bucketSize = HISTOGRAM_ACC_PRECISION; minBucketSize = 0.05; maxBucketSize = 10; bucketSizeStep = 0.05; round = 2; - suffix = '%'; - suffixLong = '%'; + suffix = "%"; + suffixLong = "%"; break; - case 'stars': - valFunc = s => s?.leaderboard?.stars ?? null; - filterFunc = s => (s?.leaderboard?.stars ?? 0) > 0 && commonFilterFunc(s) - type = 'linear'; + case "stars": + valFunc = (s) => s?.leaderboard?.stars ?? null; + filterFunc = (s) => + (s?.leaderboard?.stars ?? 0) > 0 && commonFilterFunc(s); + type = "linear"; bucketSize = HISTOGRAM_STARS_PRECISION; minBucketSize = 0.1; maxBucketSize = 10; bucketSizeStep = 0.1; round = 2; - suffix = '★'; - suffixLong = '★'; + suffix = "★"; + suffixLong = "★"; break; } return { getValue: valFunc, - getRoundedValue: (bucketSize = bucketSize) => s => roundedValFunc(s, type, bucketSize), + getRoundedValue: + (bucketSize = bucketSize) => + (s) => + roundedValFunc(s, type, bucketSize), filter: filterFunc, histogramFilter: histogramFilterFunc, - sort: (a, b) => order === 'asc' ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), + sort: (a, b) => + order === "asc" ? valFunc(a) - valFunc(b) : valFunc(b) - valFunc(a), type, bucketSize, minBucketSize, @@ -529,34 +724,66 @@ export default () => { prefixLong, suffix, suffixLong, - order - } - } + order, + }; + }; - const fetchScoresPage = async (playerId, serviceParams = {sort: 'recent', order: 'desc', page: 1}, priority = PRIORITY.FG_LOW, {...options} = {}) => - ((serviceParams?.sort ?? 'recent') === 'top' ? topScoresApiClient : recentScoresApiClient) - .getProcessed({...options, playerId, page: serviceParams?.page ?? 1, priority}); + const fetchScoresPage = async ( + playerId, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + priority = PRIORITY.FG_LOW, + { ...options } = {}, + ) => + ((serviceParams?.sort ?? "recent") === "top" + ? topScoresApiClient + : recentScoresApiClient + ).getProcessed({ + ...options, + playerId, + page: serviceParams?.page ?? 1, + priority, + }); - const fetchScoresPageAndUpdateIfNeeded = async (playerId, serviceParams = {sort: 'recent', order: 'desc', page: 1}, priority = PRIORITY.FG_LOW, signal = null, canUseBrowserCache = false, refreshInterval = MINUTE) => { - const fetchedScoresResponse = await fetchScoresPage(playerId, serviceParams, priority, {signal, cacheTtl: MINUTE, maxAge: canUseBrowserCache ? 0 : refreshInterval, fullResponse: true}); - if (topScoresApiClient.isResponseCached(fetchedScoresResponse)) return topScoresApiClient.getDataFromResponse(fetchedScoresResponse); + const fetchScoresPageAndUpdateIfNeeded = async ( + playerId, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + priority = PRIORITY.FG_LOW, + signal = null, + canUseBrowserCache = false, + refreshInterval = MINUTE, + ) => { + const fetchedScoresResponse = await fetchScoresPage( + playerId, + serviceParams, + priority, + { + signal, + cacheTtl: MINUTE, + maxAge: canUseBrowserCache ? 0 : refreshInterval, + fullResponse: true, + }, + ); + if (topScoresApiClient.isResponseCached(fetchedScoresResponse)) + return topScoresApiClient.getDataFromResponse(fetchedScoresResponse); - const fetchedScores = topScoresApiClient.getDataFromResponse(fetchedScoresResponse); + const fetchedScores = topScoresApiClient.getDataFromResponse( + fetchedScoresResponse, + ); const playerScores = await getPlayerScores(playerId); if (fetchedScores && playerScores && playerScores.length) { - const playerScoresObj = convertScoresToObject(playerScores) + const playerScoresObj = convertScoresToObject(playerScores); // update rank and pp in DB const scoresToUpdate = fetchedScores - .map(score => { + .map((score) => { try { score = addScoreIndexFields(playerId, score); - const leaderboardId = opt(score, 'leaderboard.leaderboardId') + const leaderboardId = opt(score, "leaderboard.leaderboardId"); if (!leaderboardId || !score.id) return null; - const scoreObj = opt(score, 'score') + const scoreObj = opt(score, "score"); if (!scoreObj || !Object.keys(scoreObj).length) return null; const cachedScore = playerScoresObj[leaderboardId]; @@ -565,80 +792,139 @@ export default () => { const id = score.id; const lastUpdated = cachedScore.lastUpdated; - if (lastUpdated && lastUpdated > addToDate(-RANK_AND_PP_REFRESH_INTERVAL)) return null; + if ( + lastUpdated && + lastUpdated > addToDate(-RANK_AND_PP_REFRESH_INTERVAL) + ) + return null; if ( (!lastUpdated || lastUpdated < score.fetchedAt) && - ( - opt(cachedScore, 'score.scoreId') === opt(score, 'score.scoreId') || - (opt(cachedScore, 'score.unmodifiedScore') <= opt(score, 'score.unmodifiedScore')) - ) + (opt(cachedScore, "score.scoreId") === + opt(score, "score.scoreId") || + opt(cachedScore, "score.unmodifiedScore") <= + opt(score, "score.unmodifiedScore")) ) { - scoresRepository().addToCache([{...cachedScore, score: {...scoreObj}}]); + scoresRepository().addToCache([ + { ...cachedScore, score: { ...scoreObj } }, + ]); } - return {id, leaderboardId, fetchedAt: score.fetchedAt, score: {...scoreObj}} + return { + id, + leaderboardId, + fetchedAt: score.fetchedAt, + score: { ...scoreObj }, + }; } catch { return null; } }) - .filter(score => score) + .filter((score) => score); - if (scoresToUpdate.length) addRankAndPpToUpdateQueue(scoresToUpdate).then(_ => {}); + if (scoresToUpdate.length) + addRankAndPpToUpdateQueue(scoresToUpdate).then((_) => {}); } return fetchedScores; - } + }; - const fetchScoresPageOrGetFromCache = async (player, serviceParams = {sort: 'recent', order: 'desc', page: 1}, refreshInterval = MINUTE, priority = PRIORITY.FG_LOW, signal = null, force = false) => { + const fetchScoresPageOrGetFromCache = async ( + player, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + refreshInterval = MINUTE, + priority = PRIORITY.FG_LOW, + signal = null, + force = false, + ) => { if (!player || !player.playerId) return null; - const canUseBrowserCache = !force && isScoreDateFresh(player, refreshInterval, 'recentPlayLastUpdated') + const canUseBrowserCache = + !force && + isScoreDateFresh(player, refreshInterval, "recentPlayLastUpdated"); - const scoresPage = await getPlayerScoresPage(player.playerId, serviceParams); + const scoresPage = await getPlayerScoresPage( + player.playerId, + serviceParams, + ); - if - (Object.entries(serviceParams?.filters ?? {})?.filter(([key, val]) => val)?.length || - !['recent', 'top'].includes(serviceParams.sort ?? 'recent') - ) return scoresPage; + if ( + Object.entries(serviceParams?.filters ?? {})?.filter(([key, val]) => val) + ?.length || + !["recent", "top"].includes(serviceParams.sort ?? "recent") + ) + return scoresPage; - const scores = Array.isArray(scoresPage) ? scoresPage : (scoresPage?.scores ?? []); + const scores = Array.isArray(scoresPage) + ? scoresPage + : scoresPage?.scores ?? []; // force fetch from time to time even when in cache (in order to update rank/pp) OR if cached score is ranked and pp === 0 - const shouldPageBeRefetched = scores && scores.reduce((shouldRefresh, score) => { - if (!score.pp && allRankeds[score.leaderboard]) return true; + const shouldPageBeRefetched = + scores && + scores.reduce((shouldRefresh, score) => { + if (!score.pp && allRankeds[score.leaderboard]) return true; - if (!score.lastUpdated || score.lastUpdated < addToDate(-RANK_AND_PP_REFRESH_INTERVAL)) return true; + if ( + !score.lastUpdated || + score.lastUpdated < addToDate(-RANK_AND_PP_REFRESH_INTERVAL) + ) + return true; - return shouldRefresh - }, false) + return shouldRefresh; + }, false); if ( force || !scoresPage || shouldPageBeRefetched || - !isScoreDateFresh(player, refreshInterval, 'recentPlayLastUpdated') || - !player.recentPlay || !player.scoresLastUpdated || player.recentPlay > player.scoresLastUpdated + !isScoreDateFresh(player, refreshInterval, "recentPlayLastUpdated") || + !player.recentPlay || + !player.scoresLastUpdated || + player.recentPlay > player.scoresLastUpdated ) - return fetchScoresPageAndUpdateIfNeeded(player.playerId, serviceParams, priority, signal, canUseBrowserCache && !shouldPageBeRefetched, refreshInterval); + return fetchScoresPageAndUpdateIfNeeded( + player.playerId, + serviceParams, + priority, + signal, + canUseBrowserCache && !shouldPageBeRefetched, + refreshInterval, + ); return scoresPage; - } + }; - const refresh = async (playerId, forceUpdate = false, priority = PRIORITY.BG_NORMAL, throwErrors = false) => { + const refresh = async ( + playerId, + forceUpdate = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { refreshCallCounter++; try { - log.trace(`Starting player "${playerId}" scores refreshing${forceUpdate ? ' (forced)' : ''}...`, 'ScoresService') + log.trace( + `Starting player "${playerId}" scores refreshing${ + forceUpdate ? " (forced)" : "" + }...`, + "ScoresService", + ); if (!playerId) { - log.warn(`Can not refresh player scores if an empty playerId is given`, 'ScoresService'); + log.warn( + `Can not refresh player scores if an empty playerId is given`, + "ScoresService", + ); return null; } if (updateInProgress.includes(playerId)) { - log.warn(`Player "${playerId}" scores are being fetched, skipping.`, 'ScoresService'); + log.warn( + `Player "${playerId}" scores are being fetched, skipping.`, + "ScoresService", + ); return null; } @@ -648,88 +934,142 @@ export default () => { let player; player = await playerService.refresh(playerId, false, priority); - if (!player) player = await playerService.refresh(playerId, true, priority); + if (!player) + player = await playerService.refresh(playerId, true, priority); if (!player) { - log.debug(`Can not refresh the scores of player "${playerId}" because it has not been added to the DB`); + log.debug( + `Can not refresh the scores of player "${playerId}" because it has not been added to the DB`, + ); return null; } if (!forceUpdate) { const scoresFreshnessDate = getScoresFreshnessDate(player); if (scoresFreshnessDate > new Date()) { + log.debug( + `Player "${playerId}" scores are still fresh, skipping. Next refresh on ${formatDate( + scoresFreshnessDate, + )}`, + "ScoresService", + ); - log.debug(`Player "${playerId}" scores are still fresh, skipping. Next refresh on ${formatDate(scoresFreshnessDate)}`, 'ScoresService') - - return {recentPlay: player.recentPlay, newScores: null, scores: convertScoresById(player.playerId, await getPlayerScores(player.playerId))}; + return { + recentPlay: player.recentPlay, + newScores: null, + scores: convertScoresById( + player.playerId, + await getPlayerScores(player.playerId), + ), + }; } } - log.trace(`Fetching player "${playerId}" scores from ScoreSaber...`, 'ScoresService') + log.trace( + `Fetching player "${playerId}" scores from ScoreSaber...`, + "ScoresService", + ); - const updatedPlayerScores = await resolvePromiseOrWaitForPending(`service/updatePlayerScores/${playerId}`, () => updatePlayerScores(player, priority)); + const updatedPlayerScores = await resolvePromiseOrWaitForPending( + `service/updatePlayerScores/${playerId}`, + () => updatePlayerScores(player, priority), + ); if (!updatedPlayerScores) { - log.warn(`Can not refresh player "${playerId}" scores`, 'ScoresService') + log.warn( + `Can not refresh player "${playerId}" scores`, + "ScoresService", + ); return null; } - const {player: updatedPlayer, ...scoresInfo} = updatedPlayerScores; + const { player: updatedPlayer, ...scoresInfo } = updatedPlayerScores; - log.trace(`Player "${playerId}" scores updated`, 'ScoresService', scoresInfo.newScores); + log.trace( + `Player "${playerId}" scores updated`, + "ScoresService", + scoresInfo.newScores, + ); if (scoresInfo.newScores && scoresInfo.newScores.length) { // TODO: update country ranks - eventBus.publish('player-scores-updated', {player: updatedPlayer, ...scoresInfo}); + eventBus.publish("player-scores-updated", { + player: updatedPlayer, + ...scoresInfo, + }); } - log.debug(`Player "${playerId}" refreshing complete.`, 'ScoresService'); + log.debug(`Player "${playerId}" refreshing complete.`, "ScoresService"); return scoresInfo; } catch (e) { if (throwErrors) throw e; - log.debug(`Player "${playerId}" scores refreshing error${e.toString ? `: ${e.toString()}` : ''}`, 'ScoresService', e) + log.debug( + `Player "${playerId}" scores refreshing error${ + e.toString ? `: ${e.toString()}` : "" + }`, + "ScoresService", + e, + ); return null; - } - finally { - updateInProgress = updateInProgress.filter(pId => pId !== playerId); + } finally { + updateInProgress = updateInProgress.filter((pId) => pId !== playerId); refreshCallCounter--; } - } + }; - const refreshAll = async (force = false, priority = PRIORITY.BG_NORMAL, throwErrors = false) => { - log.trace(`Starting refreshing all players scores${force ? ' (forced)' : ''}...`, 'ScoresService'); + const refreshAll = async ( + force = false, + priority = PRIORITY.BG_NORMAL, + throwErrors = false, + ) => { + log.trace( + `Starting refreshing all players scores${force ? " (forced)" : ""}...`, + "ScoresService", + ); const allActivePlayers = await playerService.getAllActive(); if (!allActivePlayers || !allActivePlayers.length) { - log.trace(`No active players in DB, skipping.`, 'ScoresService'); + log.trace(`No active players in DB, skipping.`, "ScoresService"); return null; } - const allNewScores = await Promise.all(allActivePlayers.map(player => refresh(player.playerId, force, priority, throwErrors))); - const allPlayersWithNewScores = allActivePlayers.map((player, idx) => allNewScores[idx] ? {player, ...allNewScores[idx]} : {player, newScores: null, scores: null, recentPlay: null}) + const allNewScores = await Promise.all( + allActivePlayers.map((player) => + refresh(player.playerId, force, priority, throwErrors), + ), + ); + const allPlayersWithNewScores = allActivePlayers.map((player, idx) => + allNewScores[idx] + ? { player, ...allNewScores[idx] } + : { player, newScores: null, scores: null, recentPlay: null }, + ); - log.trace(`All players scores refreshed.`, 'ScoresService', allPlayersWithNewScores); + log.trace( + `All players scores refreshed.`, + "ScoresService", + allPlayersWithNewScores, + ); return allPlayersWithNewScores; - } + }; const destroyService = () => { serviceCreationCount--; if (serviceCreationCount === 0) { - if(configStoreUnsubscribe) configStoreUnsubscribe(); + if (configStoreUnsubscribe) configStoreUnsubscribe(); if (rankedStoreUnsubscribe) rankedStoreUnsubscribe(); playerService.destroyService(); service = null; } - } + }; service = { isDataForPlayerAvailable, @@ -750,8 +1090,8 @@ export default () => { refreshAll, updateRankAndPpFromTheQueue, destroyService, - convertScoresToObject - } + convertScoresToObject, + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/twitch.js b/src/services/twitch.js index 3b2b875..b3b9b0b 100644 --- a/src/services/twitch.js +++ b/src/services/twitch.js @@ -1,16 +1,23 @@ -import queues from '../network/queues/queues'; -import keyValueRepository from '../db/repository/key-value' -import twitchRepository from '../db/repository/twitch' -import createPlayerService from '../services/scoresaber/player' -import profileApiClient from '../network/clients/twitch/api-profile' -import videosApiClient from '../network/clients/twitch/api-videos' -import eventBus from '../utils/broadcast-channel-pubsub' -import log from '../utils/logger' -import {addToDate, dateFromString, durationToMillis, formatDate, millisToDuration, MINUTE} from '../utils/date' -import {PRIORITY} from '../network/queues/http-queue' -import makePendingPromisePool from '../utils/pending-promises' +import queues from "../network/queues/queues"; +import keyValueRepository from "../db/repository/key-value"; +import twitchRepository from "../db/repository/twitch"; +import createPlayerService from "../services/scoresaber/player"; +import profileApiClient from "../network/clients/twitch/api-profile"; +import videosApiClient from "../network/clients/twitch/api-videos"; +import eventBus from "../utils/broadcast-channel-pubsub"; +import log from "../utils/logger"; +import { + addToDate, + dateFromString, + durationToMillis, + formatDate, + millisToDuration, + MINUTE, +} from "../utils/date"; +import { PRIORITY } from "../network/queues/http-queue"; +import makePendingPromisePool from "../utils/pending-promises"; -const TWITCH_TOKEN_KEY = 'twitchToken'; +const TWITCH_TOKEN_KEY = "twitchToken"; const REFRESH_INTERVAL = 5 * MINUTE; @@ -24,31 +31,38 @@ export default () => { const playerService = createPlayerService(); - const getAuthUrl = (state = '', scopes = '') => queues.TWITCH.getAuthUrl(state, scopes) + const getAuthUrl = (state = "", scopes = "") => + queues.TWITCH.getAuthUrl(state, scopes); const getTwitchTokenFromUrl = () => { - const url = (new URL(document.location)); + const url = new URL(document.location); - const error = url.searchParams.get('error') + const error = url.searchParams.get("error"); if (error) { - const errorMsg = url.searchParams.get('error_description'); + const errorMsg = url.searchParams.get("error_description"); throw new Error(errorMsg ? errorMsg : error); } const hash = url.hash; - if (!hash || !hash.length) throw new Error("Twitch did not return access token") + if (!hash || !hash.length) + throw new Error("Twitch did not return access token"); const accessTokenMatch = /access_token=(.*?)(&|$)/.exec(hash); - if (!accessTokenMatch) throw new Error("Twitch did not return access token") + if (!accessTokenMatch) + throw new Error("Twitch did not return access token"); const stateMatch = /state=(.*?)(&|$)/.exec(hash); - return {accessToken: accessTokenMatch[1], url: stateMatch ? decodeURIComponent(stateMatch[1]) : ''}; - } + return { + accessToken: accessTokenMatch[1], + url: stateMatch ? decodeURIComponent(stateMatch[1]) : "", + }; + }; - const processToken = async accessToken => { + const processToken = async (accessToken) => { // validate token - const tokenValidation = (await queues.TWITCH.validateToken(accessToken)).body; + const tokenValidation = (await queues.TWITCH.validateToken(accessToken)) + .body; const expiresIn = tokenValidation.expires_in * 1000; @@ -58,39 +72,77 @@ export default () => { obtained: new Date(), expires: new Date(Date.now() + expiresIn), expires_in: expiresIn, - } + }; await keyValueRepository().set(twitchToken, TWITCH_TOKEN_KEY); - eventBus.publish('twitch-token-refreshed', twitchToken) + eventBus.publish("twitch-token-refreshed", twitchToken); - return twitchToken - } + return twitchToken; + }; - const getCurrentToken = async () => keyValueRepository().get(TWITCH_TOKEN_KEY, true); + const getCurrentToken = async () => + keyValueRepository().get(TWITCH_TOKEN_KEY, true); - const fetchProfile = async (login, priority = PRIORITY.FG_LOW, {fullResponse = false, ...options} = {}) => { + const fetchProfile = async ( + login, + priority = PRIORITY.FG_LOW, + { fullResponse = false, ...options } = {}, + ) => { const token = await getCurrentToken(); if (!token || !token.expires || token.expires <= new Date()) return null; - return resolvePromiseOrWaitForPending(`profileApiClient/${login}/${fullResponse}`, () => profileApiClient.getProcessed({...options, accessToken: token.accessToken, login, priority, fullResponse})); - } + return resolvePromiseOrWaitForPending( + `profileApiClient/${login}/${fullResponse}`, + () => + profileApiClient.getProcessed({ + ...options, + accessToken: token.accessToken, + login, + priority, + fullResponse, + }), + ); + }; - const fetchVideos = async (userId, priority = PRIORITY.FG_LOW, {fullResponse = false, ...options} = {}) => { + const fetchVideos = async ( + userId, + priority = PRIORITY.FG_LOW, + { fullResponse = false, ...options } = {}, + ) => { const token = await getCurrentToken(); if (!token || !token.expires || token.expires <= new Date()) return null; - return resolvePromiseOrWaitForPending(`videosApiClient/${userId}/${fullResponse}`, () => videosApiClient.getProcessed({...options, accessToken: token.accessToken, userId, priority, fullResponse})); - } + return resolvePromiseOrWaitForPending( + `videosApiClient/${userId}/${fullResponse}`, + () => + videosApiClient.getProcessed({ + ...options, + accessToken: token.accessToken, + userId, + priority, + fullResponse, + }), + ); + }; - const getPlayerProfile = async playerId => twitchRepository().get(playerId); - const updatePlayerProfile = async twitchProfile => twitchRepository().set(twitchProfile); + const getPlayerProfile = async (playerId) => twitchRepository().get(playerId); + const updatePlayerProfile = async (twitchProfile) => + twitchRepository().set(twitchProfile); - const refresh = async (playerId, forceUpdate = false, priority = queues.PRIORITY.FG_LOW, throwErrors = false) => { - log.trace(`Starting Twitch videos refreshing${forceUpdate ? ' (forced)' : ''}...`, 'TwitchService') + const refresh = async ( + playerId, + forceUpdate = false, + priority = queues.PRIORITY.FG_LOW, + throwErrors = false, + ) => { + log.trace( + `Starting Twitch videos refreshing${forceUpdate ? " (forced)" : ""}...`, + "TwitchService", + ); if (!playerId) { - log.debug(`No playerId provided, skipping`, 'TwitchService') + log.debug(`No playerId provided, skipping`, "TwitchService"); return null; } @@ -98,7 +150,10 @@ export default () => { try { let twitchProfile = await twitchRepository().get(playerId); if (!twitchProfile || !twitchProfile.login) { - log.debug(`Twitch profile for player ${playerId} is not set, skipping`, 'TwitchService') + log.debug( + `Twitch profile for player ${playerId} is not set, skipping`, + "TwitchService", + ); return null; } @@ -106,7 +161,12 @@ export default () => { const lastUpdated = twitchProfile.lastUpdated; if (!forceUpdate) { if (lastUpdated && lastUpdated > new Date() - REFRESH_INTERVAL) { - log.debug(`Refresh interval not yet expired, skipping. Next refresh on ${formatDate(addToDate(REFRESH_INTERVAL, lastUpdated))}`, 'TwitchService') + log.debug( + `Refresh interval not yet expired, skipping. Next refresh on ${formatDate( + addToDate(REFRESH_INTERVAL, lastUpdated), + )}`, + "TwitchService", + ); return twitchProfile; } @@ -115,7 +175,10 @@ export default () => { const player = playerService.get(playerId); if (player && player.recentPlay) { if (lastUpdated && lastUpdated > player.recentPlay) { - log.debug(`Twitch updated after recent player play, skipping`, 'TwitchService') + log.debug( + `Twitch updated after recent player play, skipping`, + "TwitchService", + ); return twitchProfile; } @@ -124,12 +187,15 @@ export default () => { if (!twitchProfile.id) { const fetchedProfile = await fetchProfile(twitchProfile.login); if (!fetchedProfile) { - log.debug(`Can not fetch Twitch profile for player ${playerId}, skipping`, 'TwitchService') + log.debug( + `Can not fetch Twitch profile for player ${playerId}, skipping`, + "TwitchService", + ); return twitchProfile; } - twitchProfile = {...twitchProfile, ...fetchedProfile, playerId}; + twitchProfile = { ...twitchProfile, ...fetchedProfile, playerId }; await updatePlayerProfile(twitchProfile); } @@ -141,7 +207,7 @@ export default () => { await updatePlayerProfile(twitchProfile); if (videos && videos.length) { - eventBus.publish('player-twitch-videos-updated', { + eventBus.publish("player-twitch-videos-updated", { playerId, twitchProfile, }); @@ -149,27 +215,48 @@ export default () => { return twitchProfile; } catch (e) { - if (throwErrors) throw e; + if (throwErrors) throw e; - log.debug(`Twitch player ${playerId} refreshing error`, 'TwitchService', e) + log.debug( + `Twitch player ${playerId} refreshing error`, + "TwitchService", + e, + ); - return null; - } - } + return null; + } + }; async function findTwitchVideo(playerTwitchProfile, timeset, songLength) { - if (!playerTwitchProfile || !playerTwitchProfile.videos || !timeset || !songLength) return null; + if ( + !playerTwitchProfile || + !playerTwitchProfile.videos || + !timeset || + !songLength + ) + return null; - const songStarted = addToDate(-songLength * 1000, timeset) + const songStarted = addToDate(-songLength * 1000, timeset); const video = playerTwitchProfile.videos - .map(v => ({ + .map((v) => ({ ...v, created_at: dateFromString(v.created_at), - ended_at: addToDate(durationToMillis(v.duration), dateFromString(v.created_at)), + ended_at: addToDate( + durationToMillis(v.duration), + dateFromString(v.created_at), + ), })) - .find(v => v.created_at <= songStarted && songStarted < v.ended_at); + .find((v) => v.created_at <= songStarted && songStarted < v.ended_at); - return video ? {...video, url: video.url + '?t=' + millisToDuration(songStarted - video.created_at)} : null; + return video + ? { + ...video, + url: + video.url + + "?t=" + + millisToDuration(songStarted - video.created_at), + } + : null; } const destroyService = () => { @@ -179,7 +266,7 @@ export default () => { service = null; playerService.destroyService(); } - } + }; service = { getAuthUrl, @@ -192,7 +279,7 @@ export default () => { findTwitchVideo, refresh, destroyService, - } + }; return service; -} \ No newline at end of file +}; diff --git a/src/services/utils.js b/src/services/utils.js index 2b45649..ff0390c 100644 --- a/src/services/utils.js +++ b/src/services/utils.js @@ -1,43 +1,67 @@ -import {DateTime} from 'luxon'; +import { DateTime } from "luxon"; -export const getServicePlayerGain = (playerHistory, dateTruncFunc, dateKey, daysAgo = 1, maxDaysAgo = 7) => { +export const getServicePlayerGain = ( + playerHistory, + dateTruncFunc, + dateKey, + daysAgo = 1, + maxDaysAgo = 7, +) => { if (!playerHistory?.length) return null; let todayServiceMidnightDate = dateTruncFunc(new Date()); - const compareToDate = DateTime.fromJSDate(todayServiceMidnightDate).minus({days: daysAgo}).toJSDate(); - const maxServiceDate = DateTime.fromJSDate(todayServiceMidnightDate).minus({days: maxDaysAgo}).toJSDate(); + const compareToDate = DateTime.fromJSDate(todayServiceMidnightDate) + .minus({ days: daysAgo }) + .toJSDate(); + const maxServiceDate = DateTime.fromJSDate(todayServiceMidnightDate) + .minus({ days: maxDaysAgo }) + .toJSDate(); return playerHistory .sort((a, b) => b?.[dateKey]?.getTime() - a?.[dateKey]?.getTime()) - .find(h => h?.[dateKey] <= compareToDate && h?.[dateKey] >= maxServiceDate); -} + .find( + (h) => h?.[dateKey] <= compareToDate && h?.[dateKey] >= maxServiceDate, + ); +}; -export const serviceFilterFunc = serviceParams => s => { +export const serviceFilterFunc = (serviceParams) => (s) => { // accept score if there is no non-empty filter - if (!Object.entries(serviceParams?.filters ?? {})?.filter(([key, val]) => val)?.length) return true; + if ( + !Object.entries(serviceParams?.filters ?? {})?.filter(([key, val]) => val) + ?.length + ) + return true; let filterVal = true; if (serviceParams?.filters?.search?.length) { const song = s?.leaderboard?.song ?? null; if (song) { - const name = `${song?.name?.toLowerCase() ?? ''} ${song?.subName?.toLowerCase() ?? ''} ${song?.authorName?.toLowerCase() ?? ''} ${song?.levelAuthorName?.toLowerCase() ?? ''}` + const name = `${song?.name?.toLowerCase() ?? ""} ${ + song?.subName?.toLowerCase() ?? "" + } ${song?.authorName?.toLowerCase() ?? ""} ${ + song?.levelAuthorName?.toLowerCase() ?? "" + }`; - filterVal &= name.indexOf(serviceParams.filters.search.toLowerCase()) >= 0; + filterVal &= + name.indexOf(serviceParams.filters.search.toLowerCase()) >= 0; } else { filterVal &= false; } } if (serviceParams?.filters.diff?.length) { - filterVal &= s?.leaderboard?.diffInfo?.diff?.toLowerCase() === serviceParams.filters.diff?.toLowerCase() + filterVal &= + s?.leaderboard?.diffInfo?.diff?.toLowerCase() === + serviceParams.filters.diff?.toLowerCase(); } if (serviceParams?.filters?.songType?.length) { - filterVal &= (serviceParams.filters.songType === 'ranked' && s?.pp > 0) || - (serviceParams.filters.songType === 'unranked' && (s?.pp ?? 0) === 0) + filterVal &= + (serviceParams.filters.songType === "ranked" && s?.pp > 0) || + (serviceParams.filters.songType === "unranked" && (s?.pp ?? 0) === 0); } return filterVal; -} \ No newline at end of file +}; diff --git a/src/stores/config.js b/src/stores/config.js index 34e2410..f8e4e62 100644 --- a/src/stores/config.js +++ b/src/stores/config.js @@ -1,21 +1,22 @@ -import {writable} from 'svelte/store' -import keyValueRepository from '../db/repository/key-value'; -import {opt} from '../utils/js' +import { writable } from "svelte/store"; +import keyValueRepository from "../db/repository/key-value"; +import { opt } from "../utils/js"; -const STORE_CONFIG_KEY = 'config'; +const STORE_CONFIG_KEY = "config"; -export const DEFAULT_LOCALE = 'en-US'; +export const DEFAULT_LOCALE = "en-US"; export let configStore = null; const locales = { - 'de-DE': {id: 'de-DE', name: 'Deutschland'}, - 'es-ES': {id: 'es-ES', name: 'España'}, - 'pl-PL': {id: 'pl-PL', name: 'Polska'}, - 'en-GB': {id: 'en-GB', name: 'United Kingdom'}, - 'en-US': {id: 'en-US', name: 'United States'}, + "de-DE": { id: "de-DE", name: "Deutschland" }, + "es-ES": { id: "es-ES", name: "España" }, + "pl-PL": { id: "pl-PL", name: "Polska" }, + "en-GB": { id: "en-GB", name: "United Kingdom" }, + "en-US": { id: "en-US", name: "United States" }, }; -export const getCurrentLocale = () => configStore ? configStore.getLocale() : DEFAULT_LOCALE; +export const getCurrentLocale = () => + configStore ? configStore.getLocale() : DEFAULT_LOCALE; export const getSupportedLocales = () => Object.values(locales); const DEFAULT_CONFIG = { @@ -24,41 +25,42 @@ const DEFAULT_CONFIG = { country: null, }, scoreComparison: { - method: 'in-place', + method: "in-place", }, preferences: { - secondaryPp: 'attribution', - avatarIcons: 'only-if-needed', + secondaryPp: "attribution", + avatarIcons: "only-if-needed", }, locale: DEFAULT_LOCALE, -} +}; const newSettingsAvailableDefinition = { - 'scoreComparison.method': 'Method of displaying the comparison of scores', - 'preferences.secondaryPp': 'Setting the second PP metric', - 'preferences.avatarIcons': 'Showing icons on avatars', - 'locale': 'Locale selection', -} + "scoreComparison.method": "Method of displaying the comparison of scores", + "preferences.secondaryPp": "Setting the second PP metric", + "preferences.avatarIcons": "Showing icons on avatars", + locale: "Locale selection", +}; export default async () => { if (configStore) return configStore; - let currentConfig = {...DEFAULT_CONFIG}; + let currentConfig = { ...DEFAULT_CONFIG }; let newSettingsAvailable = undefined; - const {subscribe, set: storeSet} = writable(currentConfig); + const { subscribe, set: storeSet } = writable(currentConfig); - const get = key => key ? (currentConfig[key] ? currentConfig[key] : null) : currentConfig; + const get = (key) => + key ? (currentConfig[key] ? currentConfig[key] : null) : currentConfig; const set = async (config, persist = true) => { - const newConfig = {...DEFAULT_CONFIG}; - Object.keys(config).forEach(key => { - if (key === 'locale') { + const newConfig = { ...DEFAULT_CONFIG }; + Object.keys(config).forEach((key) => { + if (key === "locale") { newConfig[key] = config?.[key] ?? newConfig?.[key] ?? DEFAULT_LOCALE; return; } - newConfig[key] = {...newConfig?.[key], ...config?.[key]} + newConfig[key] = { ...newConfig?.[key], ...config?.[key] }; }); if (persist) await keyValueRepository().set(newConfig, STORE_CONFIG_KEY); @@ -69,27 +71,31 @@ export default async () => { storeSet(newConfig); return newConfig; - } + }; - const getLocale = () => opt(currentConfig, 'locale', DEFAULT_LOCALE); + const getLocale = () => opt(currentConfig, "locale", DEFAULT_LOCALE); - const determineNewSettingsAvailable = dbConfig => Object.entries(newSettingsAvailableDefinition) - .map(([key, description]) => opt(dbConfig, key) === undefined ? description : null) - .filter(d => d) + const determineNewSettingsAvailable = (dbConfig) => + Object.entries(newSettingsAvailableDefinition) + .map(([key, description]) => + opt(dbConfig, key) === undefined ? description : null, + ) + .filter((d) => d); const dbConfig = await keyValueRepository().get(STORE_CONFIG_KEY); - const newSettings= determineNewSettingsAvailable(dbConfig); + const newSettings = determineNewSettingsAvailable(dbConfig); if (dbConfig) await set(dbConfig, false); - newSettingsAvailable = newSettings && newSettings.length ? newSettings : undefined; + newSettingsAvailable = + newSettings && newSettings.length ? newSettings : undefined; - configStore = { + configStore = { subscribe, set, get, - getMainPlayerId: () => opt(currentConfig, 'users.main'), + getMainPlayerId: () => opt(currentConfig, "users.main"), getLocale, getNewSettingsAvailable: () => newSettingsAvailable, - } + }; return configStore; -} \ No newline at end of file +}; diff --git a/src/stores/container.js b/src/stores/container.js index e41af0a..f918580 100644 --- a/src/stores/container.js +++ b/src/stores/container.js @@ -1,8 +1,10 @@ -import {writable} from 'svelte/store' +import { writable } from "svelte/store"; -export default (sizes = {phone: 0, tablet: 768, desktop: 1024, xxl: 1749}) => { - const defaultValue = {name: null, width: null, nodeWidth: null, rect: null} - const {subscribe, unsubscribe, set} = writable(defaultValue); +export default ( + sizes = { phone: 0, tablet: 768, desktop: 1024, xxl: 1749 }, +) => { + const defaultValue = { name: null, width: null, nodeWidth: null, rect: null }; + const { subscribe, unsubscribe, set } = writable(defaultValue); let ro = null; let node = null; @@ -10,12 +12,12 @@ export default (sizes = {phone: 0, tablet: 768, desktop: 1024, xxl: 1749}) => { const unobserve = () => { if (!node) return; - ro.unobserve(node) + ro.unobserve(node); node = null; - } + }; - const observe = nodeToObserve => { + const observe = (nodeToObserve) => { if (!nodeToObserve) return null; if (node) unobserve(); @@ -34,19 +36,25 @@ export default (sizes = {phone: 0, tablet: 768, desktop: 1024, xxl: 1749}) => { set( Object.entries(sizes) .sort((a, b) => a[1] - b[1]) - .reduce((cum, item) => item[1] <= nodeWidth ? {name: item[0], width: item[1], nodeWidth, rect} : cum, defaultValue), - ) + .reduce( + (cum, item) => + item[1] <= nodeWidth + ? { name: item[0], width: item[1], nodeWidth, rect } + : cum, + defaultValue, + ), + ); }); - ro.observe(node) + ro.observe(node); return node; - } + }; return { subscribe, unsubscribe, observe, unobserve, - } + }; }; diff --git a/src/stores/http/enhancers/common/acc-calc.js b/src/stores/http/enhancers/common/acc-calc.js index 37dd128..8f1ca00 100644 --- a/src/stores/http/enhancers/common/acc-calc.js +++ b/src/stores/http/enhancers/common/acc-calc.js @@ -1,12 +1,18 @@ -import {getFixedLeaderboardMaxScore, getMaxScore} from '../../../../utils/scoresaber/song' +import { + getFixedLeaderboardMaxScore, + getMaxScore, +} from "../../../../utils/scoresaber/song"; export default (score, bmStats, leaderboardId) => { let maxScore; if (bmStats && bmStats.notes) { - maxScore = getMaxScore(bmStats.notes) + maxScore = getMaxScore(bmStats.notes); } else if (leaderboardId) { - maxScore = getFixedLeaderboardMaxScore(leaderboardId, score?.maxScore ?? null) + maxScore = getFixedLeaderboardMaxScore( + leaderboardId, + score?.maxScore ?? null, + ); } if (maxScore) { @@ -17,14 +23,14 @@ export default (score, bmStats, leaderboardId) => { if (!unmodifiedScore) unmodifiedScore = score?.score ?? null; if (unmodifiedScore && score.maxScore) { - score.acc = unmodifiedScore ? unmodifiedScore / maxScore * 100 : null; + score.acc = unmodifiedScore ? (unmodifiedScore / maxScore) * 100 : null; - if (score.score) score.percentage = score.score / score.maxScore * 100; + if (score.score) score.percentage = (score.score / score.maxScore) * 100; } if (score?.score && score?.maxScore) { - score.percentage = score.score / score.maxScore * 100; + score.percentage = (score.score / score.maxScore) * 100; } return score; -} \ No newline at end of file +}; diff --git a/src/stores/http/enhancers/common/beatmaps.js b/src/stores/http/enhancers/common/beatmaps.js index 41c426f..02971e6 100644 --- a/src/stores/http/enhancers/common/beatmaps.js +++ b/src/stores/http/enhancers/common/beatmaps.js @@ -1,10 +1,14 @@ -import createBeatMapsService from '../../../../services/beatmaps' -import {opt} from '../../../../utils/js' +import createBeatMapsService from "../../../../services/beatmaps"; +import { opt } from "../../../../utils/js"; const beatMaps = createBeatMapsService(); export default async (data, cachedOnly = false) => { - if (!opt(data, 'leaderboard.song.hash.length')) return; + if (!opt(data, "leaderboard.song.hash.length")) return; - data.leaderboard.beatMaps = await beatMaps.byHash(data.leaderboard.song.hash, false, cachedOnly); -} \ No newline at end of file + data.leaderboard.beatMaps = await beatMaps.byHash( + data.leaderboard.song.hash, + false, + cachedOnly, + ); +}; diff --git a/src/stores/http/enhancers/leaderboard/rankeds.js b/src/stores/http/enhancers/leaderboard/rankeds.js index 65d78f5..afcd086 100644 --- a/src/stores/http/enhancers/leaderboard/rankeds.js +++ b/src/stores/http/enhancers/leaderboard/rankeds.js @@ -1,17 +1,20 @@ -import createRankedsStore from '../../../../stores/scoresaber/rankeds' -import {opt} from '../../../../utils/js' +import createRankedsStore from "../../../../stores/scoresaber/rankeds"; +import { opt } from "../../../../utils/js"; let rankeds; export default async (data) => { - if (rankeds === undefined) { - rankeds = (await createRankedsStore()).get(); - } + if (rankeds === undefined) { + rankeds = (await createRankedsStore()).get(); + } - if (!rankeds) return; + if (!rankeds) return; - const leaderboardId = opt(data, 'leaderboard.leaderboardId'); - if (!leaderboardId) return; + const leaderboardId = opt(data, "leaderboard.leaderboardId"); + if (!leaderboardId) return; - data.leaderboard.stars = rankeds[leaderboardId] && rankeds[leaderboardId].stars ? rankeds[leaderboardId].stars : null; -} \ No newline at end of file + data.leaderboard.stars = + rankeds[leaderboardId] && rankeds[leaderboardId].stars + ? rankeds[leaderboardId].stars + : null; +}; diff --git a/src/stores/http/enhancers/scores/acc.js b/src/stores/http/enhancers/scores/acc.js index 599851c..2ec1888 100644 --- a/src/stores/http/enhancers/scores/acc.js +++ b/src/stores/http/enhancers/scores/acc.js @@ -1,16 +1,22 @@ -import {opt} from '../../../../utils/js' -import calculateAcc from '../common/acc-calc' -import {findDiffInfoWithDiffAndTypeFromBeatMaps} from '../../../../utils/scoresaber/song' +import { opt } from "../../../../utils/js"; +import calculateAcc from "../common/acc-calc"; +import { findDiffInfoWithDiffAndTypeFromBeatMaps } from "../../../../utils/scoresaber/song"; export default async (data) => { if (!data || !data.score) return; - const leaderboardId = opt(data, 'leaderboard.leaderboardId') - const diffInfo = opt(data, 'leaderboard.diffInfo'); + const leaderboardId = opt(data, "leaderboard.leaderboardId"); + const diffInfo = opt(data, "leaderboard.diffInfo"); - const versions = opt(data, 'leaderboard.beatMaps.versions') - const versionsLastIdx = versions && Array.isArray(versions) && versions.length ? versions.length - 1 : 0; - const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps(opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), diffInfo); + const versions = opt(data, "leaderboard.beatMaps.versions"); + const versionsLastIdx = + versions && Array.isArray(versions) && versions.length + ? versions.length - 1 + : 0; + const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps( + opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), + diffInfo, + ); data.score = calculateAcc(data.score, bmStats, leaderboardId); -} \ No newline at end of file +}; diff --git a/src/stores/http/enhancers/scores/beatsavior.js b/src/stores/http/enhancers/scores/beatsavior.js index 9536f36..faf0479 100644 --- a/src/stores/http/enhancers/scores/beatsavior.js +++ b/src/stores/http/enhancers/scores/beatsavior.js @@ -1,6 +1,6 @@ -import createBeatSaviorService from '../../../../services/beatsavior' -import {opt} from '../../../../utils/js' -import {PRIORITY} from '../../../../network/queues/http-queue' +import createBeatSaviorService from "../../../../services/beatsavior"; +import { opt } from "../../../../utils/js"; +import { PRIORITY } from "../../../../network/queues/http-queue"; let beatSaviorService; @@ -15,19 +15,19 @@ export default async (data, playerId = null) => { if (!bsData) return; if (bsData?.stats) - ['left', 'right'].forEach(hand => { - ['Preswing', 'Postswing'].forEach(stat => { + ["left", "right"].forEach((hand) => { + ["Preswing", "Postswing"].forEach((stat) => { const key = `${hand}${stat}`; if (!bsData?.stats?.[key]) bsData.stats[key] = bsData?.trackers?.accuracyTracker?.[key] ?? null; - }) - }) + }); + }); - const acc = opt(bsData, 'trackers.scoreTracker.rawRatio'); + const acc = opt(bsData, "trackers.scoreTracker.rawRatio"); if (acc) data.score.acc = acc * 100; - const percentage = opt(bsData, 'trackers.scoreTracker.modifiedRatio'); + const percentage = opt(bsData, "trackers.scoreTracker.modifiedRatio"); if (percentage) data.score.percentage = percentage * 100; data.beatSavior = bsData; -} \ No newline at end of file +}; diff --git a/src/stores/http/enhancers/scores/compare.js b/src/stores/http/enhancers/scores/compare.js index 14ac6c8..5c02ef7 100644 --- a/src/stores/http/enhancers/scores/compare.js +++ b/src/stores/http/enhancers/scores/compare.js @@ -1,10 +1,10 @@ -import {configStore} from '../../../config' -import createScoresService from '../../../../services/scoresaber/scores' -import accEnhancer from './acc' -import beatSaviorEnhancer from './beatsavior' -import beatMapsEnhancer from '../common/beatmaps' -import {opt} from '../../../../utils/js' -import produce from 'immer' +import { configStore } from "../../../config"; +import createScoresService from "../../../../services/scoresaber/scores"; +import accEnhancer from "./acc"; +import beatSaviorEnhancer from "./beatsavior"; +import beatMapsEnhancer from "../common/beatmaps"; +import { opt } from "../../../../utils/js"; +import produce from "immer"; let scoresService = null; let mainPlayerId = null; @@ -17,20 +17,29 @@ export const initCompareEnhancer = async () => { scoresService = createScoresService(); - configStoreUnsubscribe = configStore.subscribe(async config => { - const newMainPlayerId = opt(config, 'users.main') + configStoreUnsubscribe = configStore.subscribe(async (config) => { + const newMainPlayerId = opt(config, "users.main"); if (mainPlayerId !== newMainPlayerId) { mainPlayerId = newMainPlayerId; - if (!playerScores[mainPlayerId]) playerScores[mainPlayerId] = await scoresService.getPlayerScoresAsObject(mainPlayerId); + if (!playerScores[mainPlayerId]) + playerScores[mainPlayerId] = + await scoresService.getPlayerScoresAsObject(mainPlayerId); } - }) -} + }); +}; export default async (data, playerId = null) => { - if (!data || !data.score || data.comparePlayers || !mainPlayerId || mainPlayerId === playerId) return; + if ( + !data || + !data.score || + data.comparePlayers || + !mainPlayerId || + mainPlayerId === playerId + ) + return; - const leaderboardId = opt(data, 'leaderboard.leaderboardId'); + const leaderboardId = opt(data, "leaderboard.leaderboardId"); if (!leaderboardId) return; const comparePlayerScores = await playerScores[mainPlayerId]; @@ -38,14 +47,15 @@ export default async (data, playerId = null) => { const mainPlayerScore = await produce( await produce( - await produce( - comparePlayerScores[leaderboardId], - draft => beatMapsEnhancer(draft), + await produce(comparePlayerScores[leaderboardId], (draft) => + beatMapsEnhancer(draft), ), - draft => accEnhancer(draft, true), + (draft) => accEnhancer(draft, true), ), - draft => beatSaviorEnhancer(draft, mainPlayerId), + (draft) => beatSaviorEnhancer(draft, mainPlayerId), ); - data.comparePlayers = [{...mainPlayerScore, playerId: mainPlayerId, playerName: 'Me'}]; -} \ No newline at end of file + data.comparePlayers = [ + { ...mainPlayerScore, playerId: mainPlayerId, playerName: "Me" }, + ]; +}; diff --git a/src/stores/http/enhancers/scores/diff.js b/src/stores/http/enhancers/scores/diff.js index 8e6b4ab..f1931a1 100644 --- a/src/stores/http/enhancers/scores/diff.js +++ b/src/stores/http/enhancers/scores/diff.js @@ -1,7 +1,7 @@ -import createScoresService from '../../../../services/scoresaber/scores'; -import calculateAcc from '../common/acc-calc' -import {opt} from '../../../../utils/js' -import {findDiffInfoWithDiffAndTypeFromBeatMaps} from '../../../../utils/scoresaber/song' +import createScoresService from "../../../../services/scoresaber/scores"; +import calculateAcc from "../common/acc-calc"; +import { opt } from "../../../../utils/js"; +import { findDiffInfoWithDiffAndTypeFromBeatMaps } from "../../../../utils/scoresaber/song"; let scoresService; @@ -10,27 +10,39 @@ export default async (data, playerId = null) => { if (data.prevScore) delete data.prevScore; - const leaderboardId = opt(data, 'leaderboard.leaderboardId'); + const leaderboardId = opt(data, "leaderboard.leaderboardId"); if (!scoresService) scoresService = createScoresService(); - const playerScores = scoresService.convertScoresToObject(await scoresService.getPlayerScores(playerId)); + const playerScores = scoresService.convertScoresToObject( + await scoresService.getPlayerScores(playerId), + ); // skip if no cached score if (!playerScores[leaderboardId]) return; // compare to cached score if cached is equal to current or to cached history score otherwise - let prevScore = playerScores[leaderboardId].score.score === data.score.score - ? (playerScores[leaderboardId].history && playerScores[leaderboardId].history.length ? playerScores[leaderboardId].history[0] : null) - : playerScores[leaderboardId].score; + let prevScore = + playerScores[leaderboardId].score.score === data.score.score + ? playerScores[leaderboardId].history && + playerScores[leaderboardId].history.length + ? playerScores[leaderboardId].history[0] + : null + : playerScores[leaderboardId].score; // skip if no score to compare if (!prevScore) return; - const diffInfo = opt(data, 'leaderboard.diffInfo'); - const versions = opt(data, 'leaderboard.beatMaps.versions') - const versionsLastIdx = versions && Array.isArray(versions) && versions.length ? versions.length - 1 : 0; - const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps(opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), diffInfo); + const diffInfo = opt(data, "leaderboard.diffInfo"); + const versions = opt(data, "leaderboard.beatMaps.versions"); + const versionsLastIdx = + versions && Array.isArray(versions) && versions.length + ? versions.length - 1 + : 0; + const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps( + opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), + diffInfo, + ); data.prevScore = calculateAcc(prevScore, bmStats, leaderboardId); -} \ No newline at end of file +}; diff --git a/src/stores/http/enhancers/scores/pp-attribution.js b/src/stores/http/enhancers/scores/pp-attribution.js index 613443c..aa01ebb 100644 --- a/src/stores/http/enhancers/scores/pp-attribution.js +++ b/src/stores/http/enhancers/scores/pp-attribution.js @@ -1,24 +1,28 @@ -import createPpService from '../../../../services/scoresaber/pp' -import {configStore} from '../../../config' -import {opt} from '../../../../utils/js' +import createPpService from "../../../../services/scoresaber/pp"; +import { configStore } from "../../../config"; +import { opt } from "../../../../utils/js"; let ppService; export default async (data, playerId = null, whatIfOnly = false) => { if (!playerId) return; - const leaderboardId = opt(data, 'leaderboard.leaderboardId'); + const leaderboardId = opt(data, "leaderboard.leaderboardId"); if (!leaderboardId) return; - const pp = opt(data, 'score.pp'); + const pp = opt(data, "score.pp"); if (!pp) return; if (!ppService) ppService = createPpService(); const mainPlayerId = configStore.getMainPlayerId(); if (mainPlayerId && mainPlayerId !== playerId) { - const whatIfPp = await ppService.getWhatIfScore(mainPlayerId, leaderboardId, pp) - if (whatIfPp && whatIfPp.diff >= 0.01) data.score.whatIfPp = whatIfPp + const whatIfPp = await ppService.getWhatIfScore( + mainPlayerId, + leaderboardId, + pp, + ); + if (whatIfPp && whatIfPp.diff >= 0.01) data.score.whatIfPp = whatIfPp; } if (whatIfOnly) return; @@ -27,4 +31,4 @@ export default async (data, playerId = null, whatIfOnly = false) => { if (!ppAttribution) return; data.score.ppAttribution = -ppAttribution.diff; -} \ No newline at end of file +}; diff --git a/src/stores/http/enhancers/scores/twitch.js b/src/stores/http/enhancers/scores/twitch.js index 86b975d..24ba84a 100644 --- a/src/stores/http/enhancers/scores/twitch.js +++ b/src/stores/http/enhancers/scores/twitch.js @@ -1,15 +1,22 @@ -import createTwitchService from '../../../../services/twitch' -import {findDiffInfoWithDiffAndTypeFromBeatMaps} from '../../../../utils/scoresaber/song' -import {opt} from '../../../../utils/js' +import createTwitchService from "../../../../services/twitch"; +import { findDiffInfoWithDiffAndTypeFromBeatMaps } from "../../../../utils/scoresaber/song"; +import { opt } from "../../../../utils/js"; let twitchService; export default async (data, playerId = null) => { - if (!data || !data.score || !data.leaderboard || !data.leaderboard.beatMaps) return; + if (!data || !data.score || !data.leaderboard || !data.leaderboard.beatMaps) + return; - const versions = opt(data, 'leaderboard.beatMaps.versions') - const versionsLastIdx = versions && Array.isArray(versions) && versions.length ? versions.length - 1 : 0; - const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps(opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), data.leaderboard.diffInfo); + const versions = opt(data, "leaderboard.beatMaps.versions"); + const versionsLastIdx = + versions && Array.isArray(versions) && versions.length + ? versions.length - 1 + : 0; + const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps( + opt(data, `leaderboard.beatMaps.versions.${versionsLastIdx}.diffs`), + data.leaderboard.diffInfo, + ); if (!bmStats || !bmStats.seconds) return; if (!twitchService) twitchService = createTwitchService(); @@ -17,8 +24,12 @@ export default async (data, playerId = null) => { const twitchProfile = await twitchService.refresh(playerId); if (!twitchProfile) return; - const video = await twitchService.findTwitchVideo(twitchProfile, data.score.timeSet, bmStats.seconds); + const video = await twitchService.findTwitchVideo( + twitchProfile, + data.score.timeSet, + bmStats.seconds, + ); if (!video || !video.url) return; data.twitchVideo = video; -} \ No newline at end of file +}; diff --git a/src/stores/http/http-leaderboard-store.js b/src/stores/http/http-leaderboard-store.js index 4df2bb1..326e311 100644 --- a/src/stores/http/http-leaderboard-store.js +++ b/src/stores/http/http-leaderboard-store.js @@ -1,44 +1,53 @@ -import createHttpStore from './http-store'; -import beatMapsEnhancer from './enhancers/common/beatmaps' -import accEnhancer from './enhancers/scores/acc' -import createLeaderboardPageProvider from './providers/page-leaderboard' -import {writable} from 'svelte/store' -import {findDiffInfoWithDiffAndTypeFromBeatMaps} from '../../utils/scoresaber/song' -import {debounce} from '../../utils/debounce' -import produce, {applyPatches} from 'immer' -import ppAttributionEnhancer from './enhancers/scores/pp-attribution' +import createHttpStore from "./http-store"; +import beatMapsEnhancer from "./enhancers/common/beatmaps"; +import accEnhancer from "./enhancers/scores/acc"; +import createLeaderboardPageProvider from "./providers/page-leaderboard"; +import { writable } from "svelte/store"; +import { findDiffInfoWithDiffAndTypeFromBeatMaps } from "../../utils/scoresaber/song"; +import { debounce } from "../../utils/debounce"; +import produce, { applyPatches } from "immer"; +import ppAttributionEnhancer from "./enhancers/scores/pp-attribution"; -export default (leaderboardId, type = 'global', page = 1, initialState = null, initialStateType = 'initial') => { +export default ( + leaderboardId, + type = "global", + page = 1, + initialState = null, + initialStateType = "initial", +) => { let currentLeaderboardId = leaderboardId ? leaderboardId : null; - let currentType = type ? type : 'global'; + let currentType = type ? type : "global"; let currentPage = page ? page : 1; - const {subscribe: subscribeEnhanced, set: setEnhanced} = writable(null); + const { subscribe: subscribeEnhanced, set: setEnhanced } = writable(null); - const getCurrentEnhanceTaskId = () => `${currentLeaderboardId}/${currentPage}/${currentType}`; - const getPatchId = (leaderboardId, scoreRow) => `${leaderboardId}/${scoreRow?.player?.playerId}` + const getCurrentEnhanceTaskId = () => + `${currentLeaderboardId}/${currentPage}/${currentType}`; + const getPatchId = (leaderboardId, scoreRow) => + `${leaderboardId}/${scoreRow?.player?.playerId}`; let enhancePatches = {}; let currentEnhanceTaskId = null; - const onNewData = ({fetchParams, state, set}) => { + const onNewData = ({ fetchParams, state, set }) => { currentLeaderboardId = fetchParams?.leaderboardId ?? null; - currentType = fetchParams?.type ?? 'global'; + currentType = fetchParams?.type ?? "global"; currentPage = fetchParams?.page ?? 1; if (!state) return; const enhanceTaskId = getCurrentEnhanceTaskId(); if (currentEnhanceTaskId !== enhanceTaskId) { - enhancePatches = {} + enhancePatches = {}; currentEnhanceTaskId = enhanceTaskId; } - const stateProduce = (state, patchId, producer) => produce(state, producer, patches => { - if (!enhancePatches[patchId]) enhancePatches[patchId] = []; + const stateProduce = (state, patchId, producer) => + produce(state, producer, (patches) => { + if (!enhancePatches[patchId]) enhancePatches[patchId] = []; - enhancePatches[patchId].push(...patches) - }) + enhancePatches[patchId].push(...patches); + }); const debouncedSetState = debounce((enhanceTaskId, state) => { if (currentEnhanceTaskId !== enhanceTaskId) return; @@ -46,78 +55,119 @@ export default (leaderboardId, type = 'global', page = 1, initialState = null, i set(state); }, 100); - const newState = {...state}; + const newState = { ...state }; const setStateRow = (enhanceTaskId, scoreRow) => { if (currentEnhanceTaskId !== enhanceTaskId) return null; - const patchId = getPatchId(currentLeaderboardId, scoreRow) - const stateRowIdx = newState.scores.findIndex(s => getPatchId(currentLeaderboardId, s) === patchId) + const patchId = getPatchId(currentLeaderboardId, scoreRow); + const stateRowIdx = newState.scores.findIndex( + (s) => getPatchId(currentLeaderboardId, s) === patchId, + ); if (stateRowIdx < 0) return; - newState.scores[stateRowIdx] = applyPatches(newState.scores[stateRowIdx], enhancePatches[patchId]); + newState.scores[stateRowIdx] = applyPatches( + newState.scores[stateRowIdx], + enhancePatches[patchId], + ); debouncedSetState(enhanceTaskId, newState); return newState.scores[stateRowIdx]; - } + }; if (newState.leaderboard) beatMapsEnhancer(newState) - .then(_ => { - const versions = newState?.leaderboard?.beatMaps?.versions ?? null - const versionsLastIdx = versions && Array.isArray(versions) && versions.length ? versions.length - 1 : 0; + .then((_) => { + const versions = newState?.leaderboard?.beatMaps?.versions ?? null; + const versionsLastIdx = + versions && Array.isArray(versions) && versions.length + ? versions.length - 1 + : 0; const bpm = newState?.leaderboard?.beatMaps?.metadata?.bpm ?? null; - const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps(newState?.leaderboard?.beatMaps?.versions?.[versionsLastIdx]?.diffs, newState?.leaderboard?.diffInfo); + const bmStats = findDiffInfoWithDiffAndTypeFromBeatMaps( + newState?.leaderboard?.beatMaps?.versions?.[versionsLastIdx]?.diffs, + newState?.leaderboard?.diffInfo, + ); if (!bmStats) return null; - newState.leaderboard.stats = {...newState.leaderboard.stats, ...bmStats, bpm}; + newState.leaderboard.stats = { + ...newState.leaderboard.stats, + ...bmStats, + bpm, + }; - setEnhanced({leaderboardId, type, page, enhancedAt: new Date()}) + setEnhanced({ leaderboardId, type, page, enhancedAt: new Date() }); debouncedSetState(enhanceTaskId, newState); return newState.leaderboard.beatMaps; }) - .then(_ => { + .then((_) => { if (!newState.scores || !newState.scores.length) return; for (const scoreRow of newState.scores) { - stateProduce({ - ...scoreRow, - leaderboard: newState.leaderboard - }, getPatchId(currentLeaderboardId, scoreRow), draft => accEnhancer(draft)) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce({...scoreRow, leaderboard: newState.leaderboard}, getPatchId(currentLeaderboardId, scoreRow), draft => ppAttributionEnhancer(draft, scoreRow?.player?.playerId, true)) + stateProduce( + { + ...scoreRow, + leaderboard: newState.leaderboard, + }, + getPatchId(currentLeaderboardId, scoreRow), + (draft) => accEnhancer(draft), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + { ...scoreRow, leaderboard: newState.leaderboard }, + getPatchId(currentLeaderboardId, scoreRow), + (draft) => + ppAttributionEnhancer( + draft, + scoreRow?.player?.playerId, + true, + ), + ), ) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); } - }) - } + }); + }; const provider = createLeaderboardPageProvider(); const httpStore = createHttpStore( provider, - {leaderboardId, type, page}, + { leaderboardId, type, page }, initialState, { onInitialized: onNewData, onAfterStateChange: onNewData, - onSetPending: ({fetchParams}) => ({...fetchParams}), + onSetPending: ({ fetchParams }) => ({ ...fetchParams }), }, - initialStateType + initialStateType, ); - const fetch = async (leaderboardId = currentLeaderboardId, type = currentType, page = currentPage, force = false) => { + const fetch = async ( + leaderboardId = currentLeaderboardId, + type = currentType, + page = currentPage, + force = false, + ) => { if (!leaderboardId) return false; - if (leaderboardId === currentLeaderboardId && (!type || type === currentType) && (!page || page === currentPage) && !force) return false; + if ( + leaderboardId === currentLeaderboardId && + (!type || type === currentType) && + (!page || page === currentPage) && + !force + ) + return false; - return httpStore.fetch({leaderboardId, type, page}, force, provider); - } + return httpStore.fetch({ leaderboardId, type, page }, force, provider); + }; - const refresh = async () => fetch(currentLeaderboardId, currentType, currentPage, true); + const refresh = async () => + fetch(currentLeaderboardId, currentType, currentPage, true); return { ...httpStore, @@ -126,7 +176,6 @@ export default (leaderboardId, type = 'global', page = 1, initialState = null, i getLeaderboardId: () => currentLeaderboardId, getType: () => currentType, getPage: () => currentPage, - enhanced: {subscribe: subscribeEnhanced}, - } -} - + enhanced: { subscribe: subscribeEnhanced }, + }; +}; diff --git a/src/stores/http/http-player-store.js b/src/stores/http/http-player-store.js index 7c8c238..0d7351d 100644 --- a/src/stores/http/http-player-store.js +++ b/src/stores/http/http-player-store.js @@ -1,16 +1,20 @@ -import createHttpStore from './http-store'; -import playerApiClient from '../../network/clients/scoresaber/player/api' +import createHttpStore from "./http-store"; +import playerApiClient from "../../network/clients/scoresaber/player/api"; -export default (playerId = null, initialState = null, initialStateType = 'initial') => { +export default ( + playerId = null, + initialState = null, + initialStateType = "initial", +) => { let currentPlayerId = playerId; - const onNewData = ({fetchParams}) => { + const onNewData = ({ fetchParams }) => { currentPlayerId = fetchParams?.playerId ?? null; - } + }; const httpStore = createHttpStore( playerApiClient, - playerId ? {playerId} : null, + playerId ? { playerId } : null, initialState, { onInitialized: onNewData, @@ -22,13 +26,12 @@ export default (playerId = null, initialState = null, initialStateType = 'initia const fetch = async (playerId = currentPlayerId, force = false) => { if (!playerId || (playerId === currentPlayerId && !force)) return false; - return httpStore.fetch({playerId}, force, playerApiClient); - } + return httpStore.fetch({ playerId }, force, playerApiClient); + }; return { ...httpStore, fetch, getPlayerId: () => currentPlayerId, - } -} - + }; +}; diff --git a/src/stores/http/http-player-with-scores-store.js b/src/stores/http/http-player-with-scores-store.js index 33c9577..e109770 100644 --- a/src/stores/http/http-player-with-scores-store.js +++ b/src/stores/http/http-player-with-scores-store.js @@ -1,49 +1,61 @@ -import stringify from 'json-stable-stringify'; -import eventBus from '../../utils/broadcast-channel-pubsub' -import createHttpStore from './http-store'; -import createApiPlayerWithScoresProvider from './providers/api-player-with-scores' -import createPlayerService from '../../services/scoresaber/player' -import {addToDate, MINUTE} from '../../utils/date' -import {writable} from 'svelte/store' +import stringify from "json-stable-stringify"; +import eventBus from "../../utils/broadcast-channel-pubsub"; +import createHttpStore from "./http-store"; +import createApiPlayerWithScoresProvider from "./providers/api-player-with-scores"; +import createPlayerService from "../../services/scoresaber/player"; +import { addToDate, MINUTE } from "../../utils/date"; +import { writable } from "svelte/store"; -export default (playerId = null, service = 'scoresaber', serviceParams = {type: 'recent', page: 1}, initialState = null, initialStateType = 'initial') => { +export default ( + playerId = null, + service = "scoresaber", + serviceParams = { type: "recent", page: 1 }, + initialState = null, + initialStateType = "initial", +) => { let currentPlayerId = playerId; let currentService = service; let currentServiceParams = serviceParams; - const {subscribe: subscribeParams, set: setParams} = writable(null); + const { subscribe: subscribeParams, set: setParams } = writable(null); let playerService = createPlayerService(); let lastRecentPlay = null; let playerForLastRecentPlay = null; - const onNewData = ({fetchParams}) => { + const onNewData = ({ fetchParams }) => { currentPlayerId = fetchParams?.playerId ?? null; currentService = fetchParams?.service ?? null; currentServiceParams = fetchParams?.serviceParams ?? null; - setParams({currentPlayerId, currentService, currentServiceParams}) - } + setParams({ currentPlayerId, currentService, currentServiceParams }); + }; const provider = createApiPlayerWithScoresProvider(); const httpStore = createHttpStore( provider, - playerId ? {playerId, service, serviceParams} : null, + playerId ? { playerId, service, serviceParams } : null, initialState, { onInitialized: onNewData, onAfterStateChange: onNewData, }, - initialStateType + initialStateType, ); - const fetch = async (playerId = currentPlayerId, service = currentService, serviceParams = currentServiceParams, force = false) => { + const fetch = async ( + playerId = currentPlayerId, + service = currentService, + serviceParams = currentServiceParams, + force = false, + ) => { if ( (!playerId || playerId === currentPlayerId) && (!service || stringify(service) === stringify(currentService)) && - (!serviceParams || stringify(serviceParams) === stringify(currentServiceParams)) && + (!serviceParams || + stringify(serviceParams) === stringify(currentServiceParams)) && !force ) return false; @@ -54,75 +66,89 @@ export default (playerId = null, service = 'scoresaber', serviceParams = {type: playerForLastRecentPlay = playerId; } - return httpStore.fetch({playerId, service, serviceParams}, force, provider, !playerId || playerId !== currentPlayerId || force); - } + return httpStore.fetch( + { playerId, service, serviceParams }, + force, + provider, + !playerId || playerId !== currentPlayerId || force, + ); + }; - const refresh = async () => fetch(currentPlayerId, currentService, currentServiceParams, true); + const refresh = async () => + fetch(currentPlayerId, currentService, currentServiceParams, true); - const playerRecentPlayUpdatedUnsubscribe = eventBus.on('player-recent-play-updated', async ({playerId, recentPlay}) => { - if (!playerId || !currentPlayerId || playerId !== currentPlayerId) return; + const playerRecentPlayUpdatedUnsubscribe = eventBus.on( + "player-recent-play-updated", + async ({ playerId, recentPlay }) => { + if (!playerId || !currentPlayerId || playerId !== currentPlayerId) return; - if (!recentPlay || !lastRecentPlay || recentPlay <= lastRecentPlay) { - if (recentPlay) { - lastRecentPlay = recentPlay; - playerForLastRecentPlay = playerId; + if (!recentPlay || !lastRecentPlay || recentPlay <= lastRecentPlay) { + if (recentPlay) { + lastRecentPlay = recentPlay; + playerForLastRecentPlay = playerId; + } + return; } - return; - } - lastRecentPlay = recentPlay; - playerForLastRecentPlay = playerId; + lastRecentPlay = recentPlay; + playerForLastRecentPlay = playerId; - await refresh(); - }); + await refresh(); + }, + ); - const subscribe = fn => { + const subscribe = (fn) => { const storeUnsubscribe = httpStore.subscribe(fn); return () => { storeUnsubscribe(); playerRecentPlayUpdatedUnsubscribe(); - } - } + }; + }; const DEFAULT_RECENT_PLAY_REFRESH_INTERVAL = MINUTE; const enqueueRecentPlayRefresh = async () => { if (!currentPlayerId) { - setTimeout(() => enqueueRecentPlayRefresh(), DEFAULT_RECENT_PLAY_REFRESH_INTERVAL); + setTimeout( + () => enqueueRecentPlayRefresh(), + DEFAULT_RECENT_PLAY_REFRESH_INTERVAL, + ); return; } await playerService.fetchPlayerAndUpdateRecentPlay(currentPlayerId); - const refreshInterval = !lastRecentPlay || lastRecentPlay >= addToDate(-30 * MINUTE, new Date()) - ? DEFAULT_RECENT_PLAY_REFRESH_INTERVAL - : 15 * MINUTE; + const refreshInterval = + !lastRecentPlay || lastRecentPlay >= addToDate(-30 * MINUTE, new Date()) + ? DEFAULT_RECENT_PLAY_REFRESH_INTERVAL + : 15 * MINUTE; setTimeout(() => enqueueRecentPlayRefresh(), refreshInterval); + }; - } - - setTimeout(() => enqueueRecentPlayRefresh(), DEFAULT_RECENT_PLAY_REFRESH_INTERVAL); + setTimeout( + () => enqueueRecentPlayRefresh(), + DEFAULT_RECENT_PLAY_REFRESH_INTERVAL, + ); return { ...httpStore, subscribe, fetch, refresh, - params: {subscribe: subscribeParams}, + params: { subscribe: subscribeParams }, getPlayerId: () => currentPlayerId, getService: () => currentService, - setService: type => { + setService: (type) => { currentService = type; - setParams({currentPlayerId, currentService, currentServiceParams}) + setParams({ currentPlayerId, currentService, currentServiceParams }); }, getServiceParams: () => currentServiceParams, - setServiceParams: page => { - currentServiceParams = page - setParams({currentPlayerId, currentService, currentServiceParams}) + setServiceParams: (page) => { + currentServiceParams = page; + setParams({ currentPlayerId, currentService, currentServiceParams }); }, - } -} - + }; +}; diff --git a/src/stores/http/http-ranking-store.js b/src/stores/http/http-ranking-store.js index 152100c..1260d19 100644 --- a/src/stores/http/http-ranking-store.js +++ b/src/stores/http/http-ranking-store.js @@ -1,34 +1,48 @@ -import createHttpStore from './http-store'; -import createApiRankingProvider from './providers/api-ranking' +import createHttpStore from "./http-store"; +import createApiRankingProvider from "./providers/api-ranking"; -export default (type = 'global', page = 1, initialState = null, initialStateType = 'initial') => { - let currentType = type ? type : 'global'; +export default ( + type = "global", + page = 1, + initialState = null, + initialStateType = "initial", +) => { + let currentType = type ? type : "global"; let currentPage = page ? page : 1; - const onNewData = ({fetchParams}) => { - currentType = fetchParams?.type ?? 'global'; + const onNewData = ({ fetchParams }) => { + currentType = fetchParams?.type ?? "global"; currentPage = fetchParams?.page ?? 1; - } + }; const provider = createApiRankingProvider(); const httpStore = createHttpStore( provider, - {type, page}, + { type, page }, initialState, { onInitialized: onNewData, onAfterStateChange: onNewData, - onSetPending: ({fetchParams}) => ({...fetchParams}), + onSetPending: ({ fetchParams }) => ({ ...fetchParams }), }, - initialStateType + initialStateType, ); - const fetch = async (type = currentType, page = currentPage, force = false) => { - if ((!type || type === currentType) && (!page || page === currentPage) && !force) return false; + const fetch = async ( + type = currentType, + page = currentPage, + force = false, + ) => { + if ( + (!type || type === currentType) && + (!page || page === currentPage) && + !force + ) + return false; - return httpStore.fetch({type, page}, force, provider); - } + return httpStore.fetch({ type, page }, force, provider); + }; const refresh = async () => fetch(currentType, currentPage, true); @@ -38,6 +52,5 @@ export default (type = 'global', page = 1, initialState = null, initialStateType refresh, getType: () => currentType, getPage: () => currentPage, - } -} - + }; +}; diff --git a/src/stores/http/http-scores-store.js b/src/stores/http/http-scores-store.js index 7bb06bd..9bff65d 100644 --- a/src/stores/http/http-scores-store.js +++ b/src/stores/http/http-scores-store.js @@ -1,26 +1,34 @@ -import createHttpStore from './http-store'; -import beatMapsEnhancer from './enhancers/common/beatmaps' -import accEnhancer from './enhancers/scores/acc' -import beatSaviorEnhancer from './enhancers/scores/beatsavior' -import rankedsEnhancer from './enhancers/leaderboard/rankeds' -import compareEnhancer from './enhancers/scores/compare' -import diffEnhancer from './enhancers/scores/diff' -import twitchEnhancer from './enhancers/scores/twitch' -import ppAttributionEnhancer from './enhancers/scores/pp-attribution' -import {debounce} from '../../utils/debounce' -import createApiScoresProvider from './providers/api-scores' -import produce, {applyPatches} from 'immer' -import stringify from 'json-stable-stringify' +import createHttpStore from "./http-store"; +import beatMapsEnhancer from "./enhancers/common/beatmaps"; +import accEnhancer from "./enhancers/scores/acc"; +import beatSaviorEnhancer from "./enhancers/scores/beatsavior"; +import rankedsEnhancer from "./enhancers/leaderboard/rankeds"; +import compareEnhancer from "./enhancers/scores/compare"; +import diffEnhancer from "./enhancers/scores/diff"; +import twitchEnhancer from "./enhancers/scores/twitch"; +import ppAttributionEnhancer from "./enhancers/scores/pp-attribution"; +import { debounce } from "../../utils/debounce"; +import createApiScoresProvider from "./providers/api-scores"; +import produce, { applyPatches } from "immer"; +import stringify from "json-stable-stringify"; -export default (playerId = null, service = 'scoresaber', serviceParams = {type: 'recent', page: 1}, initialState = null, initialStateType = 'initial') => { +export default ( + playerId = null, + service = "scoresaber", + serviceParams = { type: "recent", page: 1 }, + initialState = null, + initialStateType = "initial", +) => { let currentPlayerId = playerId; let currentService = service; let currentServiceParams = serviceParams; let totalScores = null; - const getCurrentEnhanceTaskId = () => `${currentPlayerId}/${currentService}/${stringify(currentServiceParams)}`; - const getPatchId = (playerId, scoreRow) => `${playerId}/${scoreRow?.leaderboard?.leaderboardId}` + const getCurrentEnhanceTaskId = () => + `${currentPlayerId}/${currentService}/${stringify(currentServiceParams)}`; + const getPatchId = (playerId, scoreRow) => + `${playerId}/${scoreRow?.leaderboard?.leaderboardId}`; let enhancePatches = {}; let currentEnhanceTaskId = null; @@ -34,9 +42,9 @@ export default (playerId = null, service = 'scoresaber', serviceParams = {type: totalScores = state !== null ? null : 0; return state; - } + }; - const onNewData = ({fetchParams, state, stateType, set}) => { + const onNewData = ({ fetchParams, state, stateType, set }) => { currentPlayerId = fetchParams?.playerId ?? null; currentService = fetchParams?.service ?? null; currentServiceParams = fetchParams?.serviceParams ?? null; @@ -50,15 +58,16 @@ export default (playerId = null, service = 'scoresaber', serviceParams = {type: const enhanceTaskId = getCurrentEnhanceTaskId(); if (currentEnhanceTaskId !== enhanceTaskId) { - enhancePatches = {} + enhancePatches = {}; currentEnhanceTaskId = enhanceTaskId; } - const stateProduce = (state, patchId, producer) => produce(state, producer, patches => { - if (!enhancePatches[patchId]) enhancePatches[patchId] = []; + const stateProduce = (state, patchId, producer) => + produce(state, producer, (patches) => { + if (!enhancePatches[patchId]) enhancePatches[patchId] = []; - enhancePatches[patchId].push(...patches) - }) + enhancePatches[patchId].push(...patches); + }); const debouncedSetState = debounce((enhanceTaskId, state) => { if (currentEnhanceTaskId !== enhanceTaskId) return; @@ -71,77 +80,139 @@ export default (playerId = null, service = 'scoresaber', serviceParams = {type: const setStateRow = (enhanceTaskId, scoreRow) => { if (currentEnhanceTaskId !== enhanceTaskId) return null; - const patchId = getPatchId(currentPlayerId, scoreRow) - const stateRowIdx = newState.findIndex(s => getPatchId(currentPlayerId, s) === patchId) + const patchId = getPatchId(currentPlayerId, scoreRow); + const stateRowIdx = newState.findIndex( + (s) => getPatchId(currentPlayerId, s) === patchId, + ); if (stateRowIdx < 0) return; - newState[stateRowIdx] = applyPatches(newState[stateRowIdx], enhancePatches[patchId]); + newState[stateRowIdx] = applyPatches( + newState[stateRowIdx], + enhancePatches[patchId], + ); debouncedSetState(enhanceTaskId, newState); return newState[stateRowIdx]; - } + }; for (const scoreRow of newState) { - if (currentService !== 'accsaber') { - stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => beatMapsEnhancer(draft)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => accEnhancer(draft))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => diffEnhancer(draft, currentPlayerId))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => compareEnhancer(draft, currentPlayerId))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => twitchEnhancer(draft, currentPlayerId))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + if (currentService !== "accsaber") { + stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), (draft) => + beatMapsEnhancer(draft), + ) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => accEnhancer(draft), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => diffEnhancer(draft, currentPlayerId), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => compareEnhancer(draft, currentPlayerId), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => twitchEnhancer(draft, currentPlayerId), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); - stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => rankedsEnhancer(draft)) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), (draft) => + rankedsEnhancer(draft), + ).then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); - stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => ppAttributionEnhancer(draft, currentPlayerId)) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), (draft) => + ppAttributionEnhancer(draft, currentPlayerId), + ).then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); - if (stateType && stateType === 'live') - stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => beatSaviorEnhancer(draft, currentPlayerId)) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + if (stateType && stateType === "live") + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => beatSaviorEnhancer(draft, currentPlayerId), + ).then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); } else { - stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => beatMapsEnhancer(draft)) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => twitchEnhancer(draft, currentPlayerId))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) - .then(scoreRow => stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), draft => beatSaviorEnhancer(draft, currentPlayerId))) - .then(scoreRow => setStateRow(enhanceTaskId, scoreRow)) + stateProduce(scoreRow, getPatchId(currentPlayerId, scoreRow), (draft) => + beatMapsEnhancer(draft), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => twitchEnhancer(draft, currentPlayerId), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)) + .then((scoreRow) => + stateProduce( + scoreRow, + getPatchId(currentPlayerId, scoreRow), + (draft) => beatSaviorEnhancer(draft, currentPlayerId), + ), + ) + .then((scoreRow) => setStateRow(enhanceTaskId, scoreRow)); } } - } + }; const provider = createApiScoresProvider(); const httpStore = createHttpStore( provider, - playerId ? {playerId, service, serviceParams} : null, + playerId ? { playerId, service, serviceParams } : null, initialState, { onInitialized: onNewData, onBeforeStateChange, onAfterStateChange: onNewData, - onSetPending: ({fetchParams}) => ({...fetchParams}), + onSetPending: ({ fetchParams }) => ({ ...fetchParams }), }, - initialStateType + initialStateType, ); - const fetch = async (serviceParams = currentServiceParams, service = currentService, playerId = currentPlayerId, force = false) => { + const fetch = async ( + serviceParams = currentServiceParams, + service = currentService, + playerId = currentPlayerId, + force = false, + ) => { if ( (!playerId || playerId === currentPlayerId) && (!service || stringify(service) === stringify(currentService)) && - (!serviceParams || stringify(serviceParams) === stringify(currentServiceParams)) && + (!serviceParams || + stringify(serviceParams) === stringify(currentServiceParams)) && !force ) return false; - return httpStore.fetch({playerId, service, serviceParams}, force, provider, !playerId || playerId !== currentPlayerId || force); - } + return httpStore.fetch( + { playerId, service, serviceParams }, + force, + provider, + !playerId || playerId !== currentPlayerId || force, + ); + }; - const refresh = async () => fetch(currentServiceParams, currentService, currentPlayerId, true); + const refresh = async () => + fetch(currentServiceParams, currentService, currentPlayerId, true); return { ...httpStore, @@ -151,6 +222,5 @@ export default (playerId = null, service = 'scoresaber', serviceParams = {type: getService: () => currentService, getServiceParams: () => currentServiceParams, getTotalScores: () => totalScores, - } -} - + }; +}; diff --git a/src/stores/http/http-store.js b/src/stores/http/http-store.js index 61b6af4..4333fb6 100644 --- a/src/stores/http/http-store.js +++ b/src/stores/http/http-store.js @@ -1,8 +1,8 @@ -import {writable} from 'svelte/store' -import stringify from 'json-stable-stringify'; -import {SsrNetworkTimeoutError} from '../../network/errors' +import { writable } from "svelte/store"; +import stringify from "json-stable-stringify"; +import { SsrNetworkTimeoutError } from "../../network/errors"; -const hash = obj => stringify(obj); +const hash = (obj) => stringify(obj); export default ( provider, @@ -16,9 +16,12 @@ export default ( onSetPending = null, onError = null, } = {}, - initialStateType = 'initial' + initialStateType = "initial", ) => { - const getFinalParams = fetchParams => ({...defaultFetchParams, ...fetchParams}); + const getFinalParams = (fetchParams) => ({ + ...defaultFetchParams, + ...fetchParams, + }); let stateType = initialStateType; let state = initialState; @@ -27,18 +30,24 @@ export default ( let currentParams = fetchParams; let currentParamsHash = hash(getFinalParams(fetchParams)); - const setProvider = provider => currentProvider = provider; + const setProvider = (provider) => (currentProvider = provider); - const {subscribe: subscribeState, set} = writable(state); - if (onInitialized) onInitialized({state, stateType, fetchParams, defaultFetchParams, set}); + const { subscribe: subscribeState, set } = writable(state); + if (onInitialized) + onInitialized({ state, stateType, fetchParams, defaultFetchParams, set }); - const {subscribe: subscribeIsLoading, set: setIsLoading} = writable(false); - const {subscribe: subscribePending, set: setPending} = writable(null); - const {subscribe: subscribeError, set: setError} = writable(null); + const { subscribe: subscribeIsLoading, set: setIsLoading } = writable(false); + const { subscribe: subscribePending, set: setPending } = writable(null); + const { subscribe: subscribeError, set: setError } = writable(null); let pendingAbortController; - const fetch = async (fetchParams = {}, force = false, provider = currentProvider, fetchCachedFirst = false) => { + const fetch = async ( + fetchParams = {}, + force = false, + provider = currentProvider, + fetchCachedFirst = false, + ) => { const abortController = new AbortController(); try { @@ -52,37 +61,59 @@ export default ( if (fetchCachedFirst) { const beforeState = state; - provider.getCached(finalParams) - .then(cachedState => { - if (cachedState && beforeState === state) { - state = cachedState; - set(onBeforeStateChange ? onBeforeStateChange(cachedState, stateType) : cachedState); - } - }) + provider.getCached(finalParams).then((cachedState) => { + if (cachedState && beforeState === state) { + state = cachedState; + set( + onBeforeStateChange + ? onBeforeStateChange(cachedState, stateType) + : cachedState, + ); + } + }); } setError(null); setIsLoading(true); - setPending(onSetPending ? onSetPending({fetchParams, abortController}) : fetchParams); + setPending( + onSetPending + ? onSetPending({ fetchParams, abortController }) + : fetchParams, + ); pendingAbortController = abortController; - stateType = 'live'; - state = await provider.getProcessed({...finalParams, signal: abortController.signal, force}); + stateType = "live"; + state = await provider.getProcessed({ + ...finalParams, + signal: abortController.signal, + force, + }); currentParams = fetchParams; currentParamsHash = hash(finalParams); - set(onBeforeStateChange ? onBeforeStateChange(state, stateType) : state) + set(onBeforeStateChange ? onBeforeStateChange(state, stateType) : state); - if (onAfterStateChange) onAfterStateChange({state, stateType, fetchParams: currentParams, defaultFetchParams, set}); + if (onAfterStateChange) + onAfterStateChange({ + state, + stateType, + fetchParams: currentParams, + defaultFetchParams, + set, + }); return true; } catch (err) { - if ([err?.name, err?.message].includes('AbortError')) return false; + if ([err?.name, err?.message].includes("AbortError")) return false; try { - if (err instanceof SsrNetworkTimeoutError && abortController && !abortController.aborted) { + if ( + err instanceof SsrNetworkTimeoutError && + abortController && + !abortController.aborted + ) { abortController.abort(); } } catch (e) { @@ -100,19 +131,20 @@ export default ( } return false; - } + }; - if (!initialState && fetchParams) fetch(fetchParams, true, currentProvider, true); + if (!initialState && fetchParams) + fetch(fetchParams, true, currentProvider, true); - const subscribe = fn => { + const subscribe = (fn) => { const stateUnsubscribe = subscribeState(fn); return () => { stateUnsubscribe(); if (currentProvider.destroy) currentProvider.destroy(); - } - } + }; + }; return { subscribe, @@ -122,9 +154,8 @@ export default ( getProvider: () => currentProvider, getParams: () => currentParams, setProvider, - isLoading: {subscribe: subscribeIsLoading}, - pending: {subscribe: subscribePending}, - error: {subscribe: subscribeError}, - } -} - + isLoading: { subscribe: subscribeIsLoading }, + pending: { subscribe: subscribePending }, + error: { subscribe: subscribeError }, + }; +}; diff --git a/src/stores/http/providers/api-player-with-scores.js b/src/stores/http/providers/api-player-with-scores.js index 626c7af..d552728 100644 --- a/src/stores/http/providers/api-player-with-scores.js +++ b/src/stores/http/providers/api-player-with-scores.js @@ -1,8 +1,8 @@ -import createPlayerService from '../../../services/scoresaber/player'; -import createScoresFetcher from './utils/scores-fetch' -import queue from '../../../network/queues/queues' -import {MINUTE, SECOND} from '../../../utils/date' -import {worker} from '../../../utils/worker-wrappers' +import createPlayerService from "../../../services/scoresaber/player"; +import createScoresFetcher from "./utils/scores-fetch"; +import queue from "../../../network/queues/queues"; +import { MINUTE, SECOND } from "../../../utils/date"; +import { worker } from "../../../utils/worker-wrappers"; let playerService = null; let scoresFetcher = null; @@ -14,32 +14,54 @@ export default () => { let firstFetch = true; return { - getProcessed: async ({playerId, priority = queue.PRIORITY.FG_HIGH, service = 'scoresaber', serviceParams = {sort: 'recent', order: 'desc', page: 1}, signal = null, force = false} = {}) => { + getProcessed: async ({ + playerId, + priority = queue.PRIORITY.FG_HIGH, + service = "scoresaber", + serviceParams = { sort: "recent", order: "desc", page: 1 }, + signal = null, + force = false, + } = {}) => { const refreshInterval = firstFetch ? 5 * SECOND : MINUTE; firstFetch = false; - const player = await playerService.fetchPlayerOrGetFromCache(playerId, refreshInterval, priority, signal, force); + const player = await playerService.fetchPlayerOrGetFromCache( + playerId, + refreshInterval, + priority, + signal, + force, + ); - const scores = await scoresFetcher.fetchLiveScores(player, service, serviceParams, {refreshInterval, priority, signal, force}); + const scores = await scoresFetcher.fetchLiveScores( + player, + service, + serviceParams, + { refreshInterval, priority, signal, force }, + ); - return {...player, scores, service, serviceParams} + return { ...player, scores, service, serviceParams }; }, - getCached: async ({playerId, service = 'scoresaber', serviceParams = {sort: 'recent', order: 'desc', page: 1}} = {}) => { + getCached: async ({ + playerId, + service = "scoresaber", + serviceParams = { sort: "recent", order: "desc", page: 1 }, + } = {}) => { const [player, scores] = await Promise.all([ playerService.get(playerId), - scoresFetcher.fetchCachedScores(playerId, service, serviceParams) + scoresFetcher.fetchCachedScores(playerId, service, serviceParams), ]); if (!player || !scores) return null; if (worker) worker.calcPlayerStats(playerId); - return {...player, scores, service, serviceParams} + return { ...player, scores, service, serviceParams }; }, destroy() { // TODO: destroy scoresFetcher & playerService }, - } -} \ No newline at end of file + }; +}; diff --git a/src/stores/http/providers/api-ranking.js b/src/stores/http/providers/api-ranking.js index 0c5d588..2f1ac64 100644 --- a/src/stores/http/providers/api-ranking.js +++ b/src/stores/http/providers/api-ranking.js @@ -1,6 +1,6 @@ -import createRankingService from '../../../services/scoresaber/ranking'; -import queue from '../../../network/queues/queues' -import {addToDate, HOUR} from '../../../utils/date' +import createRankingService from "../../../services/scoresaber/ranking"; +import queue from "../../../network/queues/queues"; +import { addToDate, HOUR } from "../../../utils/date"; const PAGES_REFRESH_INTERVAL = HOUR; @@ -11,23 +11,35 @@ let total = null; export default () => { if (!rankingService) rankingService = createRankingService(); - const getProcessed = async ({type = 'global', page = 1, priority = queue.PRIORITY.FG_HIGH, signal = null, force = false} = {}) => { - if (type === 'global' && (!total || !globalPagesLastRefreshed || addToDate(-PAGES_REFRESH_INTERVAL) > globalPagesLastRefreshed)) { + const getProcessed = async ({ + type = "global", + page = 1, + priority = queue.PRIORITY.FG_HIGH, + signal = null, + force = false, + } = {}) => { + if ( + type === "global" && + (!total || + !globalPagesLastRefreshed || + addToDate(-PAGES_REFRESH_INTERVAL) > globalPagesLastRefreshed) + ) { globalPagesLastRefreshed = new Date(); total = await rankingService.getGlobalCount(priority, signal, force); - } else if (type !== 'global') { + } else if (type !== "global") { total = null; } - const data = type === 'global' - ? await rankingService.getGlobal(page, priority, signal, force) - : await rankingService.getCountry(type, page, priority, signal, force); + const data = + type === "global" + ? await rankingService.getGlobal(page, priority, signal, force) + : await rankingService.getCountry(type, page, priority, signal, force); - return {total, data} - } + return { total, data }; + }; return { getProcessed, - getCached: getProcessed - } -} + getCached: getProcessed, + }; +}; diff --git a/src/stores/http/providers/api-scores.js b/src/stores/http/providers/api-scores.js index 4af8722..821174e 100644 --- a/src/stores/http/providers/api-scores.js +++ b/src/stores/http/providers/api-scores.js @@ -1,8 +1,8 @@ -import createPlayerService from '../../../services/scoresaber/player'; -import createScoresFetcher from './utils/scores-fetch' -import queue from '../../../network/queues/queues' -import {MINUTE} from '../../../utils/date' -import eventBus from '../../../utils/broadcast-channel-pubsub' +import createPlayerService from "../../../services/scoresaber/player"; +import createScoresFetcher from "./utils/scores-fetch"; +import queue from "../../../network/queues/queues"; +import { MINUTE } from "../../../utils/date"; +import eventBus from "../../../utils/broadcast-channel-pubsub"; let playerService = null; let scoresFetcher = null; @@ -13,39 +13,67 @@ export default () => { playerService = createPlayerService(); scoresFetcher = createScoresFetcher(); - const playerProfileChangedUnsubscribe = eventBus.on('player-profile-changed', newPlayer => { - if (!newPlayer || !player || !newPlayer.playerId !== player.playerId) return; + const playerProfileChangedUnsubscribe = eventBus.on( + "player-profile-changed", + (newPlayer) => { + if (!newPlayer || !player || !newPlayer.playerId !== player.playerId) + return; - player = newPlayer; - }); + player = newPlayer; + }, + ); - const playerRecentPlayUpdatedUnsubscribe = eventBus.on('player-recent-play-updated', async ({playerId, recentPlay, recentPlayLastUpdated}) => { - if (!playerId || !player || player.playerId !== playerId) return; + const playerRecentPlayUpdatedUnsubscribe = eventBus.on( + "player-recent-play-updated", + async ({ playerId, recentPlay, recentPlayLastUpdated }) => { + if (!playerId || !player || player.playerId !== playerId) return; - player.recentPlay = recentPlay; - player.recentPlayLastUpdated = recentPlayLastUpdated; - }); + player.recentPlay = recentPlay; + player.recentPlayLastUpdated = recentPlayLastUpdated; + }, + ); return { - async getProcessed({playerId, service = 'scoresaber', serviceParams = {sort: 'recent', order: 'desc', page: 1}, priority = queue.PRIORITY.FG_HIGH, signal = null, force = false} = {}) { + async getProcessed({ + playerId, + service = "scoresaber", + serviceParams = { sort: "recent", order: "desc", page: 1 }, + priority = queue.PRIORITY.FG_HIGH, + signal = null, + force = false, + } = {}) { if (!player || player.playerId !== playerId) - player = await playerService.fetchPlayerOrGetFromCache(playerId, MINUTE, priority, signal); + player = await playerService.fetchPlayerOrGetFromCache( + playerId, + MINUTE, + priority, + signal, + ); - return scoresFetcher.fetchLiveScores(player, service, serviceParams, {refreshInterval: MINUTE, priority, signal, force}); + return scoresFetcher.fetchLiveScores(player, service, serviceParams, { + refreshInterval: MINUTE, + priority, + signal, + force, + }); }, - async getCached({playerId, service = 'scoresaber', serviceParams = {sort: 'recent', order: 'desc', page: 1}} = {}) { + async getCached({ + playerId, + service = "scoresaber", + serviceParams = { sort: "recent", order: "desc", page: 1 }, + } = {}) { return scoresFetcher.fetchCachedScores(playerId, service, serviceParams); }, setPlayer(newPlayer) { - player = newPlayer + player = newPlayer; }, destroy() { playerProfileChangedUnsubscribe(); playerRecentPlayUpdatedUnsubscribe(); // TODO: destroy scoresFetcher & playerService - } - } -} + }, + }; +}; diff --git a/src/stores/http/providers/page-leaderboard.js b/src/stores/http/providers/page-leaderboard.js index ba49b47..025e275 100644 --- a/src/stores/http/providers/page-leaderboard.js +++ b/src/stores/http/providers/page-leaderboard.js @@ -1,21 +1,48 @@ -import createLeaderboardService from '../../../services/scoresaber/leaderboard'; -import queue from '../../../network/queues/queues' +import createLeaderboardService from "../../../services/scoresaber/leaderboard"; +import queue from "../../../network/queues/queues"; let leaderboardService = null; export default () => { if (!leaderboardService) leaderboardService = createLeaderboardService(); - const getProcessed = async ({leaderboardId, type = 'global', page = 1, priority = queue.PRIORITY.FG_HIGH, signal = null, force = false} = {}) => { - switch(type) { - case 'global': return await leaderboardService.fetchPage(leaderboardId, page, priority, signal, force); - case 'accsaber': return await leaderboardService.fetchAccSaberPage(leaderboardId, page, priority, signal, force); - default: return await leaderboardService.getFriendsLeaderboard(leaderboardId, priority, signal, force); + const getProcessed = async ({ + leaderboardId, + type = "global", + page = 1, + priority = queue.PRIORITY.FG_HIGH, + signal = null, + force = false, + } = {}) => { + switch (type) { + case "global": + return await leaderboardService.fetchPage( + leaderboardId, + page, + priority, + signal, + force, + ); + case "accsaber": + return await leaderboardService.fetchAccSaberPage( + leaderboardId, + page, + priority, + signal, + force, + ); + default: + return await leaderboardService.getFriendsLeaderboard( + leaderboardId, + priority, + signal, + force, + ); } - } + }; return { getProcessed, - getCached: getProcessed - } -} + getCached: getProcessed, + }; +}; diff --git a/src/stores/http/providers/utils/scores-fetch.js b/src/stores/http/providers/utils/scores-fetch.js index 0550fd2..257c0a0 100644 --- a/src/stores/http/providers/utils/scores-fetch.js +++ b/src/stores/http/providers/utils/scores-fetch.js @@ -1,6 +1,6 @@ -import createScoresService from '../../../../services/scoresaber/scores' -import createAccSaberService from '../../../../services/accsaber' -import createBeatSaviorService from '../../../../services/beatsavior' +import createScoresService from "../../../../services/scoresaber/scores"; +import createAccSaberService from "../../../../services/accsaber"; +import createBeatSaviorService from "../../../../services/beatsavior"; let scoreFetcher = null; @@ -15,31 +15,54 @@ export default () => { accSaberService = createAccSaberService(); beatSaviorService = createBeatSaviorService(); - const fetchCachedScores = async (playerId, service, serviceParams = {sort: 'recent', order: 'desc', page: 1}, otherParams = {}) => { + const fetchCachedScores = async ( + playerId, + service, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + otherParams = {}, + ) => { switch (service) { - case 'beatsavior': + case "beatsavior": return beatSaviorService.getPlayerScoresPage(playerId, serviceParams); - case 'accsaber': + case "accsaber": return accSaberService.getPlayerScoresPage(playerId, serviceParams); - case 'scoresaber': + case "scoresaber": default: return ssScoresService.getPlayerScoresPage(playerId, serviceParams); } - } + }; - const fetchLiveScores = async (player, service, serviceParams = {sort: 'recent', order: 'desc', page: 1}, otherParams = {}) => { + const fetchLiveScores = async ( + player, + service, + serviceParams = { sort: "recent", order: "desc", page: 1 }, + otherParams = {}, + ) => { switch (service) { - case 'beatsavior': - return beatSaviorService.getPlayerScoresPage(player?.playerId, serviceParams); - case 'accsaber': - return accSaberService.getPlayerScoresPage(player?.playerId, serviceParams); - case 'scoresaber': + case "beatsavior": + return beatSaviorService.getPlayerScoresPage( + player?.playerId, + serviceParams, + ); + case "accsaber": + return accSaberService.getPlayerScoresPage( + player?.playerId, + serviceParams, + ); + case "scoresaber": default: - return ssScoresService.fetchScoresPageOrGetFromCache(player, serviceParams, otherParams?.refreshInterval, otherParams?.priority, otherParams?.signal, otherParams?.force); + return ssScoresService.fetchScoresPageOrGetFromCache( + player, + serviceParams, + otherParams?.refreshInterval, + otherParams?.priority, + otherParams?.signal, + otherParams?.force, + ); } - } + }; - scoreFetcher = {fetchCachedScores, fetchLiveScores} + scoreFetcher = { fetchCachedScores, fetchLiveScores }; return scoreFetcher; -} \ No newline at end of file +}; diff --git a/src/stores/scoresaber/friends.js b/src/stores/scoresaber/friends.js index 600178b..a13cec5 100644 --- a/src/stores/scoresaber/friends.js +++ b/src/stores/scoresaber/friends.js @@ -1,32 +1,32 @@ -import {writable} from 'svelte/store' -import createPlayerStore from './players' -import createPlayerService from '../../services/scoresaber/player' +import { writable } from "svelte/store"; +import createPlayerStore from "./players"; +import createPlayerService from "../../services/scoresaber/player"; export default () => { const playerService = createPlayerService(); - const {subscribe, unsubscribe: stateUnsubscribe, set} = writable([]); + const { subscribe, unsubscribe: stateUnsubscribe, set } = writable([]); const playerStore = createPlayerStore(); - const playerStoreUnsubscribe = playerStore.subscribe(async players => { + const playerStoreUnsubscribe = playerStore.subscribe(async (players) => { const friends = await playerService.getFriends(); set( players - .filter(p => p && p.playerId && friends.includes(p.playerId)) - .sort((a,b) => a.name ? a.name.localeCompare(b.name) : 0) + .filter((p) => p && p.playerId && friends.includes(p.playerId)) + .sort((a, b) => (a.name ? a.name.localeCompare(b.name) : 0)), ); - }) + }); const unsubscribe = () => { stateUnsubscribe(); playerStoreUnsubscribe()(); playerService.destroyService(); - } + }; return { subscribe, unsubscribe, - } + }; }; diff --git a/src/stores/scoresaber/players.js b/src/stores/scoresaber/players.js index 9e4135c..81bb824 100644 --- a/src/stores/scoresaber/players.js +++ b/src/stores/scoresaber/players.js @@ -1,6 +1,6 @@ -import {writable} from 'svelte/store' -import createPlayerService from '../../services/scoresaber/player' -import eventBus from '../../utils/broadcast-channel-pubsub' +import { writable } from "svelte/store"; +import createPlayerService from "../../services/scoresaber/player"; +import eventBus from "../../utils/broadcast-channel-pubsub"; let store = null; let storeSubCount = 0; @@ -11,24 +11,30 @@ export default () => { const playerService = createPlayerService(); let players = []; - const {subscribe: subscribeState, set} = writable(players); + const { subscribe: subscribeState, set } = writable(players); const refreshState = async () => { - players = await playerService.getAll() + players = await playerService.getAll(); - set(players) - } + set(players); + }; const get = () => players; - const playerAddedUnsubscribe = eventBus.on('player-profile-added', refreshState); - const playerRemovedUnsubscribe = eventBus.on('player-profile-removed', refreshState); + const playerAddedUnsubscribe = eventBus.on( + "player-profile-added", + refreshState, + ); + const playerRemovedUnsubscribe = eventBus.on( + "player-profile-removed", + refreshState, + ); - const subscribe = fn => { + const subscribe = (fn) => { const stateUnsubscribe = subscribeState(fn); return () => { - storeSubCount --; + storeSubCount--; if (storeSubCount === 0) { store = null; @@ -39,15 +45,15 @@ export default () => { playerAddedUnsubscribe(); playerRemovedUnsubscribe(); } - } - } + }; + }; - refreshState().then(_ => _); + refreshState().then((_) => _); store = { subscribe, get, - } + }; return store; -} \ No newline at end of file +}; diff --git a/src/stores/scoresaber/rankeds.js b/src/stores/scoresaber/rankeds.js index baea1ae..a5cb5a9 100644 --- a/src/stores/scoresaber/rankeds.js +++ b/src/stores/scoresaber/rankeds.js @@ -1,7 +1,7 @@ -import {writable} from 'svelte/store' -import createRankedsService from '../../services/scoresaber/rankeds' -import {PRIORITY} from '../../network/queues/http-queue' -import eventBus from '../../utils/broadcast-channel-pubsub' +import { writable } from "svelte/store"; +import createRankedsService from "../../services/scoresaber/rankeds"; +import { PRIORITY } from "../../network/queues/http-queue"; +import eventBus from "../../utils/broadcast-channel-pubsub"; let store = null; let storeSubCount = 0; @@ -13,27 +13,33 @@ export default async (refreshOnCreate = false) => { let rankeds = refreshOnCreate ? {} : await rankedsService.get(); - const {subscribe: subscribeState, set} = writable(rankeds); + const { subscribe: subscribeState, set } = writable(rankeds); const get = () => rankeds; - const refresh = async (forceUpdate = false, priority = PRIORITY.BG_NORMAL) => { + const refresh = async ( + forceUpdate = false, + priority = PRIORITY.BG_NORMAL, + ) => { await rankedsService.refresh(forceUpdate, priority); - } + }; if (refreshOnCreate) await refresh(); rankeds = await rankedsService.get(); set(rankeds); - const rankedsChangedUnsubscribe = eventBus.on('rankeds-changed', ({allRankeds}) => { - if (allRankeds && Object.keys(allRankeds).length) set(allRankeds); - }) + const rankedsChangedUnsubscribe = eventBus.on( + "rankeds-changed", + ({ allRankeds }) => { + if (allRankeds && Object.keys(allRankeds).length) set(allRankeds); + }, + ); - const subscribe = fn => { + const subscribe = (fn) => { const stateUnsubscribe = subscribeState(fn); return () => { - storeSubCount --; + storeSubCount--; if (storeSubCount === 0) { store = null; @@ -43,14 +49,14 @@ export default async (refreshOnCreate = false) => { stateUnsubscribe(); rankedsChangedUnsubscribe(); } - } - } + }; + }; store = { subscribe, get, - refresh - } + refresh, + }; return store; -} \ No newline at end of file +}; diff --git a/src/svelte-utils/actions/hoverable.js b/src/svelte-utils/actions/hoverable.js index 4916d9b..88953cd 100644 --- a/src/svelte-utils/actions/hoverable.js +++ b/src/svelte-utils/actions/hoverable.js @@ -1,32 +1,49 @@ export function hoverable(node) { - function handleMouseover(event) { - node.classList.add('hovered'); + function handleMouseover(event) { + node.classList.add("hovered"); - const rect = node.getBoundingClientRect(); + const rect = node.getBoundingClientRect(); - node.dispatchEvent(new CustomEvent('hover', { - detail: { target: event.target, clientX: event.clientX, clientY: event.clientY, pageX: event.pageX, pageY: event.pageY, rect } - })); - } + node.dispatchEvent( + new CustomEvent("hover", { + detail: { + target: event.target, + clientX: event.clientX, + clientY: event.clientY, + pageX: event.pageX, + pageY: event.pageY, + rect, + }, + }), + ); + } - function handleMouseout(event) { - node.classList.remove('hovered'); + function handleMouseout(event) { + node.classList.remove("hovered"); - node.dispatchEvent(new CustomEvent('unhover', { - detail: { target: event.target, clientX: event.clientX, clientY: event.clientY, pageX: event.pageX, pageY: event.pageY } - })); - } + node.dispatchEvent( + new CustomEvent("unhover", { + detail: { + target: event.target, + clientX: event.clientX, + clientY: event.clientY, + pageX: event.pageX, + pageY: event.pageY, + }, + }), + ); + } - node.addEventListener('mouseover', handleMouseover); - node.addEventListener('mouseout', handleMouseout); + node.addEventListener("mouseover", handleMouseover); + node.addEventListener("mouseout", handleMouseout); - node.classList.add('hoverable'); + node.classList.add("hoverable"); - return { - destroy() { - node.removeEventListener('mouseover', handleMouseover); - node.removeEventListener('mouseout', handleMouseout); - node.classList.remove('hoverable'); - } - }; -} \ No newline at end of file + return { + destroy() { + node.removeEventListener("mouseover", handleMouseover); + node.removeEventListener("mouseout", handleMouseout); + node.classList.remove("hoverable"); + }, + }; +} diff --git a/src/svelte-utils/tweened.js b/src/svelte-utils/tweened.js index a5a8bd0..218c8ce 100644 --- a/src/svelte-utils/tweened.js +++ b/src/svelte-utils/tweened.js @@ -1,4 +1,5 @@ -import { tweened } from 'svelte/motion'; -import { cubicOut } from 'svelte/easing'; +import { tweened } from "svelte/motion"; +import { cubicOut } from "svelte/easing"; -export default (value, duration = 500) => tweened(value, {duration, easing: cubicOut}); \ No newline at end of file +export default (value, duration = 500) => + tweened(value, { duration, easing: cubicOut }); diff --git a/src/utils/accsaber/consts.js b/src/utils/accsaber/consts.js index a69e093..07cff6b 100644 --- a/src/utils/accsaber/consts.js +++ b/src/utils/accsaber/consts.js @@ -1,3 +1,3 @@ export const PLAYERS_PER_PAGE = 15; export const PLAYER_SCORES_PER_PAGE = 11; -export const LEADERBOARD_SCORES_PER_PAGE = 10; \ No newline at end of file +export const LEADERBOARD_SCORES_PER_PAGE = 10; diff --git a/src/utils/broadcast-channel-pubsub.js b/src/utils/broadcast-channel-pubsub.js index 346551a..26e9211 100644 --- a/src/utils/broadcast-channel-pubsub.js +++ b/src/utils/broadcast-channel-pubsub.js @@ -1,90 +1,113 @@ -import {BroadcastChannel, createLeaderElection} from 'broadcast-channel' -import {readable} from 'svelte/store' -import log from './logger' -import {uuid} from './uuid' +import { BroadcastChannel, createLeaderElection } from "broadcast-channel"; +import { readable } from "svelte/store"; +import log from "./logger"; +import { uuid } from "./uuid"; let bc; const createGlobalPubSub = () => { - const subscribers = {} + const subscribers = {}; - const isWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; + const isWorker = + typeof WorkerGlobalScope !== "undefined" && + self instanceof WorkerGlobalScope; - const nodeId = uuid(); - log.info(`Create pub/sub channel for node ${nodeId} (${isWorker ? 'worker' : 'browser'})`, 'PubSub') + const nodeId = uuid(); + log.info( + `Create pub/sub channel for node ${nodeId} (${ + isWorker ? "worker" : "browser" + })`, + "PubSub", + ); - bc = new BroadcastChannel('global-pub-sub', {webWorkerSupport: true}); - const elector = createLeaderElection(bc); + bc = new BroadcastChannel("global-pub-sub", { webWorkerSupport: true }); + const elector = createLeaderElection(bc); - let isLeader = false; - const leaderStore = readable(isLeader, set => { - elector.awaitLeadership().then(() => { - isLeader = true; - set(isLeader); + let isLeader = false; + const leaderStore = readable(isLeader, (set) => { + elector.awaitLeadership().then(() => { + isLeader = true; + set(isLeader); - log.info(`Node ${nodeId} is a new leader`, 'PubSub') + log.info(`Node ${nodeId} is a new leader`, "PubSub"); - return () => {} - }); + return () => {}; }); + }); - const exists = eventName => Array.isArray(subscribers[eventName]); + const exists = (eventName) => Array.isArray(subscribers[eventName]); - const notify = (eventName, value, isLocal = true) => { - if (!exists(eventName)) return; + const notify = (eventName, value, isLocal = true) => { + if (!exists(eventName)) return; - subscribers[eventName].forEach(handler => handler(value, isLocal, eventName)); - } + subscribers[eventName].forEach((handler) => + handler(value, isLocal, eventName), + ); + }; - const unsubscribe = (eventName, handler) => { - if (!exists(eventName)) return; + const unsubscribe = (eventName, handler) => { + if (!exists(eventName)) return; - subscribers[eventName] = subscribers[eventName].filter(h => h !== handler); - } + subscribers[eventName] = subscribers[eventName].filter( + (h) => h !== handler, + ); + }; - const publish = (eventName, value) => { - notify(eventName, value); + const publish = (eventName, value) => { + notify(eventName, value); - bc.postMessage({eventName, nodeId, value}) - } + bc.postMessage({ eventName, nodeId, value }); + }; - bc.onmessage = ({eventName, nodeId: eventNodeId, value}) => notify(eventName, value, eventNodeId === nodeId); + bc.onmessage = ({ eventName, nodeId: eventNodeId, value }) => + notify(eventName, value, eventNodeId === nodeId); - const removeNode = async () => { - log.info(`Node ${nodeId} is about to be removed`, 'PubSub'); + const removeNode = async () => { + log.info(`Node ${nodeId} is about to be removed`, "PubSub"); - publish('node-removed', nodeId); - } + publish("node-removed", nodeId); + }; - // add close handler (also prevents back-forward cache) - if (!(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)) { - window.addEventListener('beforeunload', () => removeNode(), {capture: true}); - } + // add close handler (also prevents back-forward cache) + if ( + !( + typeof WorkerGlobalScope !== "undefined" && + self instanceof WorkerGlobalScope + ) + ) { + window.addEventListener("beforeunload", () => removeNode(), { + capture: true, + }); + } - publish('node-added', nodeId) - log.info(`Node ${nodeId} has been created`, 'PubSub') + publish("node-added", nodeId); + log.info(`Node ${nodeId} has been created`, "PubSub"); - return { - on(eventName, handler) { - if (!exists(eventName)) subscribers[eventName] = []; + return { + on(eventName, handler) { + if (!exists(eventName)) subscribers[eventName] = []; - // workaround - have no idea why some handlers are registered multiple times - if (subscribers[eventName].find(h => h === handler)) return; + // workaround - have no idea why some handlers are registered multiple times + if (subscribers[eventName].find((h) => h === handler)) return; - subscribers[eventName].push(handler); + subscribers[eventName].push(handler); - return () => { - unsubscribe(eventName, handler); - } - }, - unsubscribe, - publish, - leaderStore, - isLeader() {return isLeader}, - getNodeId() {return nodeId}, - } -} + return () => { + unsubscribe(eventName, handler); + }; + }, + unsubscribe, + publish, + leaderStore, + isLeader() { + return isLeader; + }, + getNodeId() { + return nodeId; + }, + }; +}; const pubSub = createGlobalPubSub(); -export default pubSub; \ No newline at end of file +export default pubSub; diff --git a/src/utils/browser.js b/src/utils/browser.js index 3b841f5..c70d165 100644 --- a/src/utils/browser.js +++ b/src/utils/browser.js @@ -1,15 +1,15 @@ -import {opt} from './js' +import { opt } from "./js"; export function scrollToTargetAdjusted(target, offset = 0) { if (!target) return; - const elementPosition = opt(target.getBoundingClientRect(), 'top'); + const elementPosition = opt(target.getBoundingClientRect(), "top"); if (!elementPosition) return; - const offsetPosition = elementPosition - offset + window.pageYOffset + const offsetPosition = elementPosition - offset + window.pageYOffset; window.scrollTo({ top: offsetPosition, behavior: "smooth", }); -} \ No newline at end of file +} diff --git a/src/utils/cf-email-decrypt.js b/src/utils/cf-email-decrypt.js index d4d0833..7b21e11 100644 --- a/src/utils/cf-email-decrypt.js +++ b/src/utils/cf-email-decrypt.js @@ -1 +1,76 @@ -export default function (document) {"use strict";function e(e){try{if("undefined"==typeof console)return;"error"in console?console.error(e):console.log(e)}catch(e){}}function t(e){return d.innerHTML='',d.childNodes[0].getAttribute("href")||""}function r(e,t){var r=e.substr(t,2);return parseInt(r,16)}function n(n,c){for(var o="",a=r(n,c),i=c+2;i-1&&(o.href="mailto:"+n(o.href,a+l.length))}catch(i){e(i)}}function o(t){for(var r=t.querySelectorAll(u),c=0;c'), + d.childNodes[0].getAttribute("href") || "" + ); + } + function r(e, t) { + var r = e.substr(t, 2); + return parseInt(r, 16); + } + function n(n, c) { + for (var o = "", a = r(n, c), i = c + 2; i < n.length; i += 2) { + var l = r(n, i) ^ a; + o += String.fromCharCode(l); + } + try { + o = decodeURIComponent(escape(o)); + } catch (u) { + e(u); + } + return t(o); + } + function c(t) { + for (var r = t.querySelectorAll("a"), c = 0; c < r.length; c++) + try { + var o = r[c], + a = o.href.indexOf(l); + a > -1 && (o.href = "mailto:" + n(o.href, a + l.length)); + } catch (i) { + e(i); + } + } + function o(t) { + for (var r = t.querySelectorAll(u), c = 0; c < r.length; c++) + try { + var o = r[c], + a = o.parentNode, + i = o.getAttribute(f); + if (i) { + var l = n(i, 0), + d = document.createTextNode(l); + a.replaceChild(d, o); + } + } catch (h) { + e(h); + } + } + function a(t) { + for (var r = t.querySelectorAll("template"), n = 0; n < r.length; n++) + try { + i(r[n].content); + } catch (c) { + e(c); + } + } + function i(t) { + try { + c(t), o(t), a(t); + } catch (r) { + e(r); + } + } + var l = "/cdn-cgi/l/email-protection#", + u = ".__cf_email__", + f = "data-cfemail", + d = document.createElement("div"); + i(document); +} diff --git a/src/utils/clipboard.js b/src/utils/clipboard.js index 197f608..398615a 100644 --- a/src/utils/clipboard.js +++ b/src/utils/clipboard.js @@ -1,36 +1,36 @@ -import log from './logger'; +import log from "./logger"; function fallbackCopyTextToClipboard(text) { - const textArea = document.createElement("textarea"); - textArea.value = text; + const textArea = document.createElement("textarea"); + textArea.value = text; - // Avoid scrolling to bottom - textArea.style.top = "0"; - textArea.style.left = "0"; - textArea.style.position = "fixed"; + // Avoid scrolling to bottom + textArea.style.top = "0"; + textArea.style.left = "0"; + textArea.style.position = "fixed"; - document.body.appendChild(textArea); - textArea.focus(); - textArea.select(); + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); - try { - document.execCommand('copy'); - } catch (err) { - log.error('Fallback: Oops, unable to copy to clipboard', err); - } + try { + document.execCommand("copy"); + } catch (err) { + log.error("Fallback: Oops, unable to copy to clipboard", err); + } - document.body.removeChild(textArea); + document.body.removeChild(textArea); } export function copyToClipboard(text) { - navigator.permissions.query({name: 'clipboard-write'}) - .then(result => { - if (result.state === 'granted' || result.state === 'prompt') { - navigator.clipboard.writeText(text).then(() => {}); - } else { - fallbackCopyTextToClipboard(text); - } - }) - .catch(() => fallbackCopyTextToClipboard(text)) - ; -} \ No newline at end of file + navigator.permissions + .query({ name: "clipboard-write" }) + .then((result) => { + if (result.state === "granted" || result.state === "prompt") { + navigator.clipboard.writeText(text).then(() => {}); + } else { + fallbackCopyTextToClipboard(text); + } + }) + .catch(() => fallbackCopyTextToClipboard(text)); +} diff --git a/src/utils/date.js b/src/utils/date.js index e5a5a80..82f9d20 100644 --- a/src/utils/date.js +++ b/src/utils/date.js @@ -1,154 +1,190 @@ -import {DateTime} from 'luxon'; -import {isString} from "./js"; -import {getCurrentLocale} from '../stores/config' -import {padNumber} from './format' +import { DateTime } from "luxon"; +import { isString } from "./js"; +import { getCurrentLocale } from "../stores/config"; +import { padNumber } from "./format"; export const SECOND = 1000; export const MINUTE = 60 * SECOND; export const HOUR = 60 * MINUTE; export const DAY = 24 * HOUR; -const getCurrentLang = () => 'en'; +const getCurrentLang = () => "en"; -const SCORESABER_TZ = 'Australia/Brisbane'; -const ACCSABER_TZ = 'Europe/Berlin'; +const SCORESABER_TZ = "Australia/Brisbane"; +const ACCSABER_TZ = "Europe/Berlin"; -export const isValidDate = d =>d instanceof Date && !isNaN(d); +export const isValidDate = (d) => d instanceof Date && !isNaN(d); -export const dateFromString = str => { - // convert SS page date format to ISO - const matches = str && isString(str) ? str.match(/^(\d{4}-\d{1,2}-\d{1,2})\s+(\d{1,2}:\d{1,2}(:\d{1,2})?)\sUTC$/) : null; - if (matches && matches.length >= 3) { - str = matches[1] + 'T' + matches[2] + 'Z'; - } +export const dateFromString = (str) => { + // convert SS page date format to ISO + const matches = + str && isString(str) + ? str.match( + /^(\d{4}-\d{1,2}-\d{1,2})\s+(\d{1,2}:\d{1,2}(:\d{1,2})?)\sUTC$/, + ) + : null; + if (matches && matches.length >= 3) { + str = matches[1] + "T" + matches[2] + "Z"; + } - const date = str ? new Date(Date.parse(str)) : null; + const date = str ? new Date(Date.parse(str)) : null; - return isValidDate(date) ? date : null; + return isValidDate(date) ? date : null; +}; + +export const durationToMillis = (duration) => { + const match = duration.match(/^\s*(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)\s*$/); + if (!match) return null; + + return ( + (match[1] ? parseInt(match[1], 10) * 1000 * 60 * 60 : 0) + + (match[2] ? parseInt(match[2], 10) * 1000 * 60 : 0) + + (match[3] ? parseInt(match[3], 10) * 1000 : 0) + ); +}; + +export const millisToDuration = (millis) => { + const hours = padNumber(Math.floor(millis / (1000 * 60 * 60))); + millis -= hours * 1000 * 60 * 60; + + const minutes = padNumber(Math.floor(millis / (1000 * 60))); + millis -= minutes * 1000 * 60; + + const seconds = padNumber(Math.floor(millis / 1000)); + + return `${hours}h${minutes}m${seconds}s`; +}; + +export const addToDate = (millis, date = new Date()) => + new Date(date.getTime() + millis); +export const daysAgo = (days) => addToDate(-days * DAY); + +export function truncateDate(date, precision = "day") { + const newDate = new Date(date.getTime()); + + // no breaks here! + switch (precision) { + case "year": + newDate.setMonth(0); + case "month": + newDate.setDate(1); + case "day": + newDate.setHours(0); + case "hour": + newDate.setMinutes(0); + case "minute": + newDate.setSeconds(0); + case "second": + newDate.setMilliseconds(0); + } + + return newDate; } -export const durationToMillis = duration => { - const match = duration.match(/^\s*(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)\s*$/); - if (!match) return null; +export const correctOldSsDate = (ssDate) => + DateTime.fromJSDate(ssDate) + .setZone("UTC") + .startOf("day") + .setZone(SCORESABER_TZ, { keepLocalTime: true }) + .toJSDate(); - return (match[1] ? parseInt(match[1], 10) * 1000 * 60 * 60 : 0) + - (match[2] ? parseInt(match[2], 10) * 1000 * 60 : 0) + - (match[3] ? parseInt(match[3], 10) * 1000 : 0); +export const toTimezoneMidnight = (date, timezone) => + DateTime.fromJSDate(date).setZone(timezone).startOf("day").toJSDate(); +export const toSsMidnight = (date) => toTimezoneMidnight(date, SCORESABER_TZ); +export const toAccSaberMidnight = (date) => + toTimezoneMidnight(date, ACCSABER_TZ); +export const fromAccSaberDateString = (dateStr) => + DateTime.fromSQL(dateStr, { zone: ACCSABER_TZ }).toJSDate(); + +export function formatDateWithOptions( + val, + options = { localeMatcher: "best fit" }, + locale = getCurrentLocale(), +) { + if (!isValidDate(val)) return null; + + const rtf = new Intl.DateTimeFormat(locale, options); + + return rtf.format(val); } -export const millisToDuration = millis => { - const hours = padNumber(Math.floor(millis / (1000 * 60 * 60))); - millis -= hours * 1000 * 60 * 60; - - const minutes = padNumber(Math.floor(millis / (1000 * 60))); - millis -= minutes * 1000 * 60; - - const seconds = padNumber(Math.floor(millis / 1000)); - - return `${hours}h${minutes}m${seconds}s`; +export function formatDate( + val, + dateStyle = "short", + timeStyle = "medium", + locale = getCurrentLocale(), +) { + return formatDateWithOptions( + val, + { + localeMatcher: "best fit", + dateStyle, + timeStyle: timeStyle ?? undefined, + }, + locale, + ); } -export const addToDate = (millis, date = new Date()) => new Date(date.getTime() + millis) -export const daysAgo = days => addToDate(- days * DAY); +export function formatDateRelativeInUnits(val, unit = "day") { + const rtf = new Intl.RelativeTimeFormat(getCurrentLang(), { + localeMatcher: "best fit", + numeric: "auto", + style: "long", + }); -export function truncateDate(date, precision = 'day') { - const newDate = new Date(date.getTime()); - - // no breaks here! - switch(precision) { - case 'year': newDate.setMonth(0); - case 'month': newDate.setDate(1); - case 'day': newDate.setHours(0); - case 'hour': newDate.setMinutes(0); - case 'minute': newDate.setSeconds(0); - case 'second': newDate.setMilliseconds(0); - } - - return newDate; + return rtf.format(val, "day"); } -export const correctOldSsDate = ssDate => DateTime.fromJSDate(ssDate).setZone('UTC').startOf('day').setZone(SCORESABER_TZ, {keepLocalTime: true}).toJSDate(); +export function formatDateRelative(val, roundFunc = Math.round, unit = "auto") { + if (!isValidDate(val)) return null; -export const toTimezoneMidnight = (date, timezone) => DateTime.fromJSDate(date).setZone(timezone).startOf('day').toJSDate(); -export const toSsMidnight = date => toTimezoneMidnight(date, SCORESABER_TZ); -export const toAccSaberMidnight = date => toTimezoneMidnight(date, ACCSABER_TZ); -export const fromAccSaberDateString = dateStr => DateTime.fromSQL(dateStr, {zone: ACCSABER_TZ}).toJSDate(); + const rtf = new Intl.RelativeTimeFormat(getCurrentLang(), { + localeMatcher: "best fit", + numeric: "auto", + style: "long", + }); -export function formatDateWithOptions(val, options = {localeMatcher: 'best fit'}, locale = getCurrentLocale()) { - if (!isValidDate(val)) return null; + const diffInSecs = (Date.now() - dateFromString(val)) / 1000; - const rtf = new Intl.DateTimeFormat(locale, options); + switch (unit) { + case "auto": + if (diffInSecs < 60) return rtf.format(-roundFunc(diffInSecs), "second"); + else if (diffInSecs < 60 * 60) + return rtf.format(-roundFunc(diffInSecs / 60), "minute"); + else if (diffInSecs < 60 * 60 * 24) + return rtf.format(-roundFunc(diffInSecs / (60 * 60)), "hour"); + else if (diffInSecs < 60 * 60 * 24 * 30) + return rtf.format(-roundFunc(diffInSecs / (60 * 60 * 24)), "day"); + else if (diffInSecs < 60 * 60 * 24 * 365) + return rtf.format( + -roundFunc(diffInSecs / (60 * 60 * 24 * 30)), + "month", + ); + else + return rtf.format( + -roundFunc(diffInSecs / (60 * 60 * 24 * 365)), + "year", + ); - return rtf.format(val); + default: + let unitDivider = + unit === "second" + ? 1 + : unit === "minute" + ? 60 + : unit === "hour" + ? 60 * 60 + : unit === "day" + ? 60 * 60 * 24 + : unit === "month" + ? 60 * 60 * 24 * 30 + : unit === "year" + ? 60 * 60 * 24 * 365 + : null; + if (!unitDivider) { + unitDivider = 1; + unit = "second"; + } + return rtf.format(-roundFunc(diffInSecs / unitDivider), unit); + } } - -export function formatDate(val, dateStyle = 'short', timeStyle = 'medium', locale = getCurrentLocale()) { - return formatDateWithOptions(val, { - localeMatcher: 'best fit', - dateStyle, - timeStyle: timeStyle ?? undefined, - }, locale); -} - -export function formatDateRelativeInUnits(val, unit = 'day') { - const rtf = new Intl.RelativeTimeFormat(getCurrentLang(), { - localeMatcher: 'best fit', - numeric: 'auto', - style: 'long' - }); - - return rtf.format(val, 'day'); -} - -export function formatDateRelative(val, roundFunc = Math.round, unit = 'auto') { - if (!isValidDate(val)) return null; - - const rtf = new Intl.RelativeTimeFormat(getCurrentLang(), { - localeMatcher: 'best fit', - numeric: 'auto', - style: 'long' - }); - - const diffInSecs = (Date.now() - dateFromString(val)) / 1000; - - switch(unit) { - case 'auto': - if (diffInSecs < 60) - return rtf.format(-roundFunc(diffInSecs), 'second'); - else if (diffInSecs < 60 * 60) - return rtf.format(-roundFunc(diffInSecs / 60), 'minute'); - else if (diffInSecs < 60 * 60 * 24) - return rtf.format(-roundFunc(diffInSecs / (60 * 60)), 'hour'); - else if (diffInSecs < 60 * 60 * 24 * 30) - return rtf.format(-roundFunc(diffInSecs / (60 * 60 * 24)), 'day'); - else if (diffInSecs < 60 * 60 * 24 * 365) - return rtf.format( - -roundFunc(diffInSecs / (60 * 60 * 24 * 30)), - 'month' - ); - else - return rtf.format( - -roundFunc(diffInSecs / (60 * 60 * 24 * 365)), - 'year' - ); - - default: - let unitDivider = - unit === 'second' ? 1 : ( - unit === 'minute' ? 60 : ( - unit === 'hour' ? 60 * 60 : ( - unit === 'day' ? 60 * 60 * 24 : ( - unit === 'month' ? 60 * 60 * 24 * 30 : ( - unit === 'year' ? 60 * 60 * 24 * 365 : null - ) - ) - ) - ) - ); - if (!unitDivider) { - unitDivider = 1; - unit = 'second'; - } - return rtf.format(-roundFunc(diffInSecs / unitDivider), unit); - } -} \ No newline at end of file diff --git a/src/utils/debounce.js b/src/utils/debounce.js index f4213fb..5629d32 100644 --- a/src/utils/debounce.js +++ b/src/utils/debounce.js @@ -1,11 +1,11 @@ export const debounce = (callback, wait) => { let timeout; - return function(...args) { + return function (...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => callback.apply(context, args), wait); - } -} + }; +}; export const throttle = (callback, wait) => { let timeout; @@ -17,12 +17,15 @@ export const throttle = (callback, wait) => { lastFired = Date.now(); } else { clearTimeout(timeout); - timeout = setTimeout(() => { - if ((Date.now() - lastFired) >= wait) { - callback.apply(context, args); - lastFired = Date.now(); - } - }, wait - (Date.now() - lastFired)); + timeout = setTimeout( + () => { + if (Date.now() - lastFired >= wait) { + callback.apply(context, args); + lastFired = Date.now(); + } + }, + wait - (Date.now() - lastFired), + ); } - } -} \ No newline at end of file + }; +}; diff --git a/src/utils/download.js b/src/utils/download.js index 6fb0534..b3caed0 100644 --- a/src/utils/download.js +++ b/src/utils/download.js @@ -1,16 +1,16 @@ export default (data, filename, type) => { - const link = document.createElement("a"); - if (link.download === undefined) return false; + const link = document.createElement("a"); + if (link.download === undefined) return false; - const blob = new Blob([data], {type}); + const blob = new Blob([data], { type }); - link.setAttribute("href", URL.createObjectURL(blob)); - link.setAttribute("download", filename); - link.style.visibility = 'hidden'; + link.setAttribute("href", URL.createObjectURL(blob)); + link.setAttribute("download", filename); + link.style.visibility = "hidden"; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); - return true; -} \ No newline at end of file + return true; +}; diff --git a/src/utils/export-import.js b/src/utils/export-import.js index 2d45241..e0ec281 100644 --- a/src/utils/export-import.js +++ b/src/utils/export-import.js @@ -1,6 +1,6 @@ import eventBus from "../utils/broadcast-channel-pubsub"; -import download from './download'; -import {db} from '../db/db'; +import download from "./download"; +import { db } from "../db/db"; import beatSaviorRepository from "../db/repository/beat-savior"; import beatSaviorPlayersRepository from "../db/repository/beat-savior-players"; import groupsRepository from "../db/repository/groups"; @@ -13,240 +13,317 @@ import scoresRepository from "../db/repository/scores"; import songsBeatMapsRepository from "../db/repository/songs-beatmaps"; import twitchRepository from "../db/repository/twitch"; import accSaberPlayersHistoryRepository from "../db/repository/accsaber-players-history"; -import {dateFromString} from './date' -import log from './logger' -import {opt} from './js' +import { dateFromString } from "./date"; +import log from "./logger"; +import { opt } from "./js"; -const EXPORT_NAME = 'SSR'; +const EXPORT_NAME = "SSR"; const repositories = [ - { - repository: beatSaviorRepository, casts: { - date: ['timeSet'], - } - }, - { - repository: beatSaviorPlayersRepository, casts: { - date: ['lastRefresh'], - }, - }, - {repository: groupsRepository}, - { - repository: keyValueRepository, - excludedKeys: ['twitchToken'], - casts: { - date: ['rankedsLastUpdated', 'accSaberCategoriesLastUpdated', 'accSaberOverallRankingLastUpdated', 'accSaberStandardRankingLastUpdated', 'accSaberTechRankingLastUpdated', 'accSaberTrueRankingLastUpdated'], - }, - }, - { - repository: playersRepository, - casts: { - date: ['profileLastUpdated', 'recentPlay', 'recentPlayLastUpdated', 'scoresLastUpdated'], - }, - }, - { - repository: playersHistoryRepository, - casts: { - date: ['ssDate', 'localDate'], - }, - }, - { - repository: accSaberPlayersHistoryRepository, - casts: { - date: ['accSaberDate', 'lastUpdated'], - }, - }, - { - repository: rankedsRepository, - casts: { - date: ['firstSeen'], - }, - }, - {repository: rankedsChangesRepository}, - { - repository: scoresRepository, - casts: { - date: ['beatSavior.timeSet', 'fetchedAt', 'lastUpdated', 'score.timeSet', 'timeSet', 'history.*.timeSet'], - }, - }, - { - repository: songsBeatMapsRepository, - casts: { - date: ['lastUpdated'] - } - }, - { - repository: twitchRepository, - casts: { - date: ['lastUpdated', 'profileLastUpdated'], - }, - }, + { + repository: beatSaviorRepository, + casts: { + date: ["timeSet"], + }, + }, + { + repository: beatSaviorPlayersRepository, + casts: { + date: ["lastRefresh"], + }, + }, + { repository: groupsRepository }, + { + repository: keyValueRepository, + excludedKeys: ["twitchToken"], + casts: { + date: [ + "rankedsLastUpdated", + "accSaberCategoriesLastUpdated", + "accSaberOverallRankingLastUpdated", + "accSaberStandardRankingLastUpdated", + "accSaberTechRankingLastUpdated", + "accSaberTrueRankingLastUpdated", + ], + }, + }, + { + repository: playersRepository, + casts: { + date: [ + "profileLastUpdated", + "recentPlay", + "recentPlayLastUpdated", + "scoresLastUpdated", + ], + }, + }, + { + repository: playersHistoryRepository, + casts: { + date: ["ssDate", "localDate"], + }, + }, + { + repository: accSaberPlayersHistoryRepository, + casts: { + date: ["accSaberDate", "lastUpdated"], + }, + }, + { + repository: rankedsRepository, + casts: { + date: ["firstSeen"], + }, + }, + { repository: rankedsChangesRepository }, + { + repository: scoresRepository, + casts: { + date: [ + "beatSavior.timeSet", + "fetchedAt", + "lastUpdated", + "score.timeSet", + "timeSet", + "history.*.timeSet", + ], + }, + }, + { + repository: songsBeatMapsRepository, + casts: { + date: ["lastUpdated"], + }, + }, + { + repository: twitchRepository, + casts: { + date: ["lastUpdated", "profileLastUpdated"], + }, + }, ]; const getOrigin = () => { - const url = window ? new URL(window.location.href) : null; - return url ? url.origin : null; -} + const url = window ? new URL(window.location.href) : null; + return url ? url.origin : null; +}; -export const exportJsonData = async (filename = 'ssr-db-' + (new Date()).toISOString().replace(/:/g, '_') + '.json') => { - const inLineKeysRepositories = getInLineKeysRepositories(); - const outOfLineKeysRepositories = getOutOfLineKeysRepositories(); +export const exportJsonData = async ( + filename = "ssr-db-" + new Date().toISOString().replace(/:/g, "_") + ".json", +) => { + const inLineKeysRepositories = getInLineKeysRepositories(); + const outOfLineKeysRepositories = getOutOfLineKeysRepositories(); - const data = (await Promise.all(inLineKeysRepositories.map(r => r.repository).map(async repository => repository().getAll()))) - .reduce((cum, repositoryData, idx) => { - cum.stores[inLineKeysRepositories[idx].repository().getStoreName()] = repositoryData; - return cum; - }, {name: EXPORT_NAME, origin: getOrigin(), version: db.version, exportedOn: new Date(), stores: {}}); + const data = ( + await Promise.all( + inLineKeysRepositories + .map((r) => r.repository) + .map(async (repository) => repository().getAll()), + ) + ).reduce( + (cum, repositoryData, idx) => { + cum.stores[inLineKeysRepositories[idx].repository().getStoreName()] = + repositoryData; + return cum; + }, + { + name: EXPORT_NAME, + origin: getOrigin(), + version: db.version, + exportedOn: new Date(), + stores: {}, + }, + ); - await Promise.all( - outOfLineKeysRepositories.map(async repositoryItem => { - const repository = repositoryItem.repository; - const storeName = repository().getStoreName(); - const repositoryKeys = await repository().getAllKeys(); - const respositoryValues = await repository().getAll(); - data.stores[storeName] = repositoryKeys.reduce((cum, key, idx) => cum.concat([{ - key, - value: opt(repositoryItem, 'excludedKeys', []).includes(key) ? null : respositoryValues[idx], - }]), []); - }), - ); + await Promise.all( + outOfLineKeysRepositories.map(async (repositoryItem) => { + const repository = repositoryItem.repository; + const storeName = repository().getStoreName(); + const repositoryKeys = await repository().getAllKeys(); + const respositoryValues = await repository().getAll(); + data.stores[storeName] = repositoryKeys.reduce( + (cum, key, idx) => + cum.concat([ + { + key, + value: opt(repositoryItem, "excludedKeys", []).includes(key) + ? null + : respositoryValues[idx], + }, + ]), + [], + ); + }), + ); - return download(JSON.stringify(data), filename, 'application/json;charset=utf-8;'); -} + return download( + JSON.stringify(data), + filename, + "application/json;charset=utf-8;", + ); +}; -export const importJsonData = async json => { - const availableStores = repositories.map(item => item.repository().getStoreName()); +export const importJsonData = async (json) => { + const availableStores = repositories.map((item) => + item.repository().getStoreName(), + ); - eventBus.publish('dl-manager-pause-cmd'); + eventBus.publish("dl-manager-pause-cmd"); - await db.runInTransaction(availableStores, async tx => { - for(let repositoryItem of repositories) { - const repository = repositoryItem.repository(); - const isOutOfLineRepository = repository.hasOutOfLineKey(); + await db.runInTransaction(availableStores, async (tx) => { + for (let repositoryItem of repositories) { + const repository = repositoryItem.repository(); + const isOutOfLineRepository = repository.hasOutOfLineKey(); - const storeName = repository.getStoreName(); + const storeName = repository.getStoreName(); - if (!json.stores[storeName]) { - log.warn(`Store ${storeName} does not exists in imported JSON`); - continue; - } + if (!json.stores[storeName]) { + log.warn(`Store ${storeName} does not exists in imported JSON`); + continue; + } - const items = json.stores[storeName].map(value => castRepositoryItem(value, repositoryItem)); + const items = json.stores[storeName].map((value) => + castRepositoryItem(value, repositoryItem), + ); - const store = tx.objectStore(storeName); - await store.clear(); + const store = tx.objectStore(storeName); + await store.clear(); - for(const item of items) { - if (isOutOfLineRepository) { - await store.put(item.value, item.key) - } else { - await store.put(item); - } - } + for (const item of items) { + if (isOutOfLineRepository) { + await store.put(item.value, item.key); + } else { + await store.put(item); + } + } - repository.flushCache(); - } - }); + repository.flushCache(); + } + }); - eventBus.publish('data-imported'); -} + eventBus.publish("data-imported"); +}; -function castObjectKeys(value, testKeys, castType = 'date', isOutOfLineRepository = false) { - const cast = (v, type = 'date') => { - switch(type) { - case 'date':return dateFromString(v) +function castObjectKeys( + value, + testKeys, + castType = "date", + isOutOfLineRepository = false, +) { + const cast = (v, type = "date") => { + switch (type) { + case "date": + return dateFromString(v); - default: return v; - } - } + default: + return v; + } + }; - testKeys.forEach(key => { - const splittedKey = key.split('.'); - const mainKey = splittedKey.shift(); - const keys = (!isOutOfLineRepository ? [mainKey] : []).concat(isOutOfLineRepository && !splittedKey.length ? [''] : splittedKey); + testKeys.forEach((key) => { + const splittedKey = key.split("."); + const mainKey = splittedKey.shift(); + const keys = (!isOutOfLineRepository ? [mainKey] : []).concat( + isOutOfLineRepository && !splittedKey.length ? [""] : splittedKey, + ); - let valuePart = isOutOfLineRepository ? opt(value, 'value') : value; - if (!valuePart) return; + let valuePart = isOutOfLineRepository ? opt(value, "value") : value; + if (!valuePart) return; - if (isOutOfLineRepository && value.key !== mainKey) return; + if (isOutOfLineRepository && value.key !== mainKey) return; - const process = (v, keys) => { - if (!keys || !keys.length) return v; + const process = (v, keys) => { + if (!keys || !keys.length) return v; - const currentKey = keys[0]; + const currentKey = keys[0]; - switch(currentKey) { - case '': return cast(v, castType); + switch (currentKey) { + case "": + return cast(v, castType); - case '*': - if (!Array.isArray(v)) return v; + case "*": + if (!Array.isArray(v)) return v; - return v.map(innerV => keys.length === 1 ? cast(innerV, castType) : process(innerV, keys.slice(1))) + return v.map((innerV) => + keys.length === 1 + ? cast(innerV, castType) + : process(innerV, keys.slice(1)), + ); - default: - if (!v.hasOwnProperty(currentKey)) return v; + default: + if (!v.hasOwnProperty(currentKey)) return v; - v[currentKey] = keys.length === 1 ? cast(v[currentKey], castType) : process(v[currentKey], keys.slice(1)); + v[currentKey] = + keys.length === 1 + ? cast(v[currentKey], castType) + : process(v[currentKey], keys.slice(1)); - return v; - } - } + return v; + } + }; - valuePart = process(valuePart, keys); + valuePart = process(valuePart, keys); - value = isOutOfLineRepository ? {key: value.key, value: valuePart} : valuePart; - }); + value = isOutOfLineRepository + ? { key: value.key, value: valuePart } + : valuePart; + }); - return value; + return value; } const castRepositoryItem = (value, repositoryItem) => { - const isOutOfLineRepository = repositoryItem.repository().hasOutOfLineKey(); + const isOutOfLineRepository = repositoryItem.repository().hasOutOfLineKey(); - Object.entries(opt(repositoryItem, 'casts', {})).forEach(([castType, keys]) => { - value = castObjectKeys(value, keys, castType, isOutOfLineRepository) - }); + Object.entries(opt(repositoryItem, "casts", {})).forEach( + ([castType, keys]) => { + value = castObjectKeys(value, keys, castType, isOutOfLineRepository); + }, + ); - return value; + return value; }; -const getInLineKeysRepositories = () => repositories.filter(r => !r.repository().hasOutOfLineKey()); -const getOutOfLineKeysRepositories = () => repositories.filter(r => r.repository().hasOutOfLineKey()); +const getInLineKeysRepositories = () => + repositories.filter((r) => !r.repository().hasOutOfLineKey()); +const getOutOfLineKeysRepositories = () => + repositories.filter((r) => r.repository().hasOutOfLineKey()); export function importDataHandler(e, onError = null, onImportCompleted = null) { - const file = e.target.files[0]; - if (!file) { - return; - } - if (file.type !== 'application/json') { - if (onError) onError('Select the JSON file containing the data export'); - return; - } + const file = e.target.files[0]; + if (!file) { + return; + } + if (file.type !== "application/json") { + if (onError) onError("Select the JSON file containing the data export"); + return; + } - const reader = new FileReader(); + const reader = new FileReader(); - reader.onload = async function (e) { - try { - const json = JSON.parse(e.target.result); + reader.onload = async function (e) { + try { + const json = JSON.parse(e.target.result); - if (!json || !json.name || !json.version || !json.stores) { - if (onError) onError('File is invalid'); - return; - } + if (!json || !json.name || !json.version || !json.stores) { + if (onError) onError("File is invalid"); + return; + } - if (json.name !== EXPORT_NAME) { - if (onError) onError('File is invalid'); - return; - } + if (json.name !== EXPORT_NAME) { + if (onError) onError("File is invalid"); + return; + } - await importJsonData(json); + await importJsonData(json); - if (onImportCompleted) await onImportCompleted(json); - } catch (e) { - log.error(e); - if (onError) onError('Invalid JSON file'); - } - }; + if (onImportCompleted) await onImportCompleted(json); + } catch (e) { + log.error(e); + if (onError) onError("Invalid JSON file"); + } + }; - reader.readAsText(file); -} \ No newline at end of file + reader.readAsText(file); +} diff --git a/src/utils/format.js b/src/utils/format.js index 7527bc5..59d7132 100644 --- a/src/utils/format.js +++ b/src/utils/format.js @@ -1,30 +1,40 @@ -import {getCurrentLocale} from '../stores/config' +import { getCurrentLocale } from "../stores/config"; -export const substituteVars = (url, vars) => Object.keys(vars).reduce((cum, key) => cum.replace(new RegExp('\\${' + key + '}', 'gi'), vars[key]), url); +export const substituteVars = (url, vars) => + Object.keys(vars).reduce( + (cum, key) => cum.replace(new RegExp("\\${" + key + "}", "gi"), vars[key]), + url, + ); -export function formatNumber(num, digits = 2, addSign = false, notANumber = null) { +export function formatNumber( + num, + digits = 2, + addSign = false, + notANumber = null, +) { if (!Number.isFinite(num)) { return notANumber; } return ( - (addSign && num > 0 ? '+' : '') + + (addSign && num > 0 ? "+" : "") + num.toLocaleString(getCurrentLocale(), { minimumFractionDigits: digits, - maximumFractionDigits: digits + maximumFractionDigits: digits, }) ); } -export const padNumber = (num, pad = 2) => (Array(pad).fill('0').join('') + num).slice(-pad); +export const padNumber = (num, pad = 2) => + (Array(pad).fill("0").join("") + num).slice(-pad); export const round = (val, places = 2) => { if (!Number.isFinite(val)) return null; const mult = Math.pow(10, places); return Math.round((val + Number.EPSILON) * mult) / mult; -} +}; export function roundToPrecision(num, precision = 0.1) { return round(Math.floor(num / precision) * precision); -} \ No newline at end of file +} diff --git a/src/utils/js.js b/src/utils/js.js index 5cab779..0be9e7e 100644 --- a/src/utils/js.js +++ b/src/utils/js.js @@ -1,5 +1,6 @@ export const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); -export const isEmpty = (obj) => !obj || (obj.constructor === Object && Object.keys(obj).length === 0); +export const isEmpty = (obj) => + !obj || (obj.constructor === Object && Object.keys(obj).length === 0); export const convertArrayToObjectByKey = (arr, key, asArray = false) => arr.reduce((cum, item) => { if (asArray && !cum[item[key]]) cum[item[key]] = []; @@ -8,39 +9,56 @@ export const convertArrayToObjectByKey = (arr, key, asArray = false) => else cum[item[key]] = item; return cum; }, {}); -export const arrayDifference = (arr1, arr2) => arr1.filter(x => !arr2.includes(x)); -export const arrayIntersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x)); -export const arrayUnique = arr => [...new Set(arr)]; -export const nullIfUndefined = (val) => (typeof val !== 'undefined' ? val : null); +export const arrayDifference = (arr1, arr2) => + arr1.filter((x) => !arr2.includes(x)); +export const arrayIntersection = (arr1, arr2) => + arr1.filter((x) => arr2.includes(x)); +export const arrayUnique = (arr) => [...new Set(arr)]; +export const nullIfUndefined = (val) => + typeof val !== "undefined" ? val : null; export const defaultIfFalsy = (val, def) => (val ? val : def); export const getFirstRegexpMatch = (regexp, str) => { let _ = regexp.exec(str); return _ ? _[1] : null; }; -export const escapeHtml = unsafe => unsafe - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -export const isDateObject = date => date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date); -export const isPromise = p => p && Object.prototype.toString.call(p) === "[object Promise]"; -export const isString = str => Object.prototype.toString.call(str) === "[object String]"; +export const escapeHtml = (unsafe) => + unsafe + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +export const isDateObject = (date) => + date && + Object.prototype.toString.call(date) === "[object Date]" && + !isNaN(date); +export const isPromise = (p) => + p && Object.prototype.toString.call(p) === "[object Promise]"; +export const isString = (str) => + Object.prototype.toString.call(str) === "[object String]"; -export const opt = (obj, key, defaultValue = undefined) => key.split('.').reduce((o, i) => o && o[i] !== null && o[i] !== undefined ? o[i] : defaultValue, obj); +export const opt = (obj, key, defaultValue = undefined) => + key + .split(".") + .reduce( + (o, i) => + o && o[i] !== null && o[i] !== undefined ? o[i] : defaultValue, + obj, + ); export const optSet = (obj, key, value, createKeys = true) => { - const keys = key.split('.'); + const keys = key.split("."); const last = keys.pop(); if (!last) return false; const startObj = obj || {}; let current = startObj; - for(const i of keys) { + for (const i of keys) { const propertyExists = current.hasOwnProperty(i); if (!propertyExists && !createKeys) return obj; - if (!propertyExists || current[i] === null || current[i] === undefined) current[i] = {}; + if (!propertyExists || current[i] === null || current[i] === undefined) + current[i] = {}; current = current[i]; } @@ -48,4 +66,4 @@ export const optSet = (obj, key, value, createKeys = true) => { current[last] = value; return startObj; -} \ No newline at end of file +}; diff --git a/src/utils/logger.js b/src/utils/logger.js index 2a69059..bf6c525 100644 --- a/src/utils/logger.js +++ b/src/utils/logger.js @@ -1,4 +1,4 @@ -import {arrayUnique} from "./js"; +import { arrayUnique } from "./js"; const LEVELS = { NONE: 0, @@ -6,43 +6,60 @@ const LEVELS = { WARN: 2, INFO: 3, DEBUG: 4, - TRACE: 5 -} + TRACE: 5, +}; let currentLevel = LEVELS.INFO; export let enabledTypes = []; export default { - table: (data, level = LEVELS.TRACE, type = null) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= level - ? console.table(data) - : null, + table: (data, level = LEVELS.TRACE, type = null) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= level + ? console.table(data) + : null, - trace: (message, type = null, ...rest) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= LEVELS.TRACE - ? console.debug(`[SSR${type ? ` / ${type}` : ''}]`, message, ...rest) - : null, + trace: (message, type = null, ...rest) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= LEVELS.TRACE + ? console.debug(`[SSR${type ? ` / ${type}` : ""}]`, message, ...rest) + : null, - debug: (message, type = null, ...rest) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= LEVELS.DEBUG - ? console.debug(`[SSR${type ? ` / ${type}` : ''}]`, message, ...rest) - : null, + debug: (message, type = null, ...rest) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= LEVELS.DEBUG + ? console.debug(`[SSR${type ? ` / ${type}` : ""}]`, message, ...rest) + : null, - info: (message, type = null, ...rest) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= LEVELS.INFO - ? console.info(`[SSR${type ? ` / ${type}` : ''}]`, message, ...rest) - : null, + info: (message, type = null, ...rest) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= LEVELS.INFO + ? console.info(`[SSR${type ? ` / ${type}` : ""}]`, message, ...rest) + : null, - warn: (message, type = null, ...rest) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= LEVELS.WARN - ? console.warn(`[SSR${type ? ` / ${type}` : ''}]`, message, ...rest) - : null, + warn: (message, type = null, ...rest) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= LEVELS.WARN + ? console.warn(`[SSR${type ? ` / ${type}` : ""}]`, message, ...rest) + : null, - error: (message, type = null, ...rest) => (!enabledTypes.length || enabledTypes.includes(type)) && currentLevel >= LEVELS.ERROR - ? console.error(`[SSR${type ? ` / ${type}` : ''}]`, message, ...rest) - : null, + error: (message, type = null, ...rest) => + (!enabledTypes.length || enabledTypes.includes(type)) && + currentLevel >= LEVELS.ERROR + ? console.error(`[SSR${type ? ` / ${type}` : ""}]`, message, ...rest) + : null, ...LEVELS, level: () => currentLevel, - setLevel: level => { - currentLevel = Object.values(LEVELS).find(l => l === level) ? level : currentLevel + setLevel: (level) => { + currentLevel = Object.values(LEVELS).find((l) => l === level) + ? level + : currentLevel; }, - logOnly: types => enabledTypes = arrayUnique(enabledTypes.concat(Array.isArray(types) ? types : [types])), - logAll: () => enabledTypes = [] + logOnly: (types) => + (enabledTypes = arrayUnique( + enabledTypes.concat(Array.isArray(types) ? types : [types]), + )), + logAll: () => (enabledTypes = []), }; diff --git a/src/utils/pending-promises.js b/src/utils/pending-promises.js index 8f55a66..40c11b0 100644 --- a/src/utils/pending-promises.js +++ b/src/utils/pending-promises.js @@ -3,14 +3,13 @@ export default () => { return async (promiseKey, promiseReturningFunc) => { if (!pendingPromises[promiseKey]) { - pendingPromises[promiseKey] = promiseReturningFunc() - .then(res => { - delete pendingPromises[promiseKey]; + pendingPromises[promiseKey] = promiseReturningFunc().then((res) => { + delete pendingPromises[promiseKey]; - return res; - }); + return res; + }); } - return pendingPromises[promiseKey] - } -} \ No newline at end of file + return pendingPromises[promiseKey]; + }; +}; diff --git a/src/utils/promise.js b/src/utils/promise.js index 15f51d8..cc74fd1 100644 --- a/src/utils/promise.js +++ b/src/utils/promise.js @@ -1,12 +1,21 @@ -export const AbortError = (message = "Aborted") => new DOMException(message, "AbortError"); +export const AbortError = (message = "Aborted") => + new DOMException(message, "AbortError"); -export const delay = async (time, val, shouldReject = false, signal = null) => new Promise((resolve, reject) => { - const handle = setTimeout(_ => shouldReject ? reject(val) : resolve(val), time); +export const delay = async (time, val, shouldReject = false, signal = null) => + new Promise((resolve, reject) => { + const handle = setTimeout( + (_) => (shouldReject ? reject(val) : resolve(val)), + time, + ); - if (signal && signal.addEventListener) - signal.addEventListener('abort', () => { - clearTimeout(handle); + if (signal && signal.addEventListener) + signal.addEventListener( + "abort", + () => { + clearTimeout(handle); - reject(AbortError()); - }, {once: true}) -}); \ No newline at end of file + reject(AbortError()); + }, + { once: true }, + ); + }); diff --git a/src/utils/queue.js b/src/utils/queue.js index be08dd4..2484d0d 100644 --- a/src/utils/queue.js +++ b/src/utils/queue.js @@ -1,7 +1,7 @@ -import PQueue from 'p-queue' -import EventEmitter from 'eventemitter3'; -import {TimeoutError} from 'p-timeout' -import {SsrTimeoutError} from '../others/errors' +import PQueue from "p-queue"; +import EventEmitter from "eventemitter3"; +import { TimeoutError } from "p-timeout"; +import { SsrTimeoutError } from "../others/errors"; export const PRIORITY = { HIGHEST: 4, @@ -9,22 +9,22 @@ export const PRIORITY = { NORMAL: 2, LOW: 1, LOWEST: 0, -} +}; const defaultOptions = { concurrency: 4, timeout: 60000, throwOnTimeout: true, -} +}; export default (options = defaultOptions) => { - const queue = new PQueue({...defaultOptions, ...options}); + const queue = new PQueue({ ...defaultOptions, ...options }); const emitter = new EventEmitter(); - const add = async (fn, priority = PRIORITY.HIGHEST) => queue - .add(fn, {priority}) - .catch(err => { - if (err instanceof TimeoutError) throw new SsrTimeoutError(queue.timeout, err.message); + const add = async (fn, priority = PRIORITY.HIGHEST) => + queue.add(fn, { priority }).catch((err) => { + if (err instanceof TimeoutError) + throw new SsrTimeoutError(queue.timeout, err.message); throw err; }); @@ -33,38 +33,50 @@ export default (options = defaultOptions) => { const isPaused = () => queue.isPaused; const clear = () => queue.clear(); const size = () => queue.size; - const sizeByPriority = (priority = PRIORITY.HIGHEST) => queue.sizeBy({priority}); + const sizeByPriority = (priority = PRIORITY.HIGHEST) => + queue.sizeBy({ priority }); const pending = () => queue.pending; const on = (event, fn, context) => emitter.on(event, fn, context); const once = (event, fn, context) => emitter.once(event, fn, context); - const removeListener = (event, fn, context) => emitter.removeListener(event, fn, context); + const removeListener = (event, fn, context) => + emitter.removeListener(event, fn, context); - let windowNum = 0, windowCnt = 0; - queue.on('add', () => { - emitter.emit('change', {size: queue.size, pending: queue.pending}) + let windowNum = 0, + windowCnt = 0; + queue.on("add", () => { + emitter.emit("change", { size: queue.size, pending: queue.pending }); windowCnt++; - if (windowCnt > 0) emitter.emit('progress', {progress: windowNum / windowCnt, num: windowNum, count: windowCnt}); + if (windowCnt > 0) + emitter.emit("progress", { + progress: windowNum / windowCnt, + num: windowNum, + count: windowCnt, + }); }); - queue.on('active', () => { + queue.on("active", () => { // Note: emited when job is taken from queue but not yet added to pending, so we have to increase pending count - emitter.emit('change', {size: queue.size, pending: queue.pending + 1}) + emitter.emit("change", { size: queue.size, pending: queue.pending + 1 }); }); - queue.on('next', () => { - emitter.emit('change', {size: queue.size, pending: queue.pending}); + queue.on("next", () => { + emitter.emit("change", { size: queue.size, pending: queue.pending }); if (windowCnt > 0) { windowNum++; - emitter.emit('progress', {progress: windowNum / windowCnt, num: windowNum, count: windowCnt}); + emitter.emit("progress", { + progress: windowNum / windowCnt, + num: windowNum, + count: windowCnt, + }); } }); - queue.on('idle', () => { - emitter.emit('progress', {progress: 1, num: windowCnt, count: windowCnt}); + queue.on("idle", () => { + emitter.emit("progress", { progress: 1, num: windowCnt, count: windowCnt }); windowNum = 0; windowCnt = 0; @@ -82,6 +94,6 @@ export default (options = defaultOptions) => { on, once, removeListener, - emitter - } -}; \ No newline at end of file + emitter, + }; +}; diff --git a/src/utils/scoresaber/consts.js b/src/utils/scoresaber/consts.js index 4b0157e..dadc8b6 100644 --- a/src/utils/scoresaber/consts.js +++ b/src/utils/scoresaber/consts.js @@ -1,3 +1,3 @@ export const PLAYERS_PER_PAGE = 50; export const PLAYER_SCORES_PER_PAGE = 8; -export const LEADERBOARD_SCORES_PER_PAGE = 12; \ No newline at end of file +export const LEADERBOARD_SCORES_PER_PAGE = 12; diff --git a/src/utils/scoresaber/format.js b/src/utils/scoresaber/format.js index 1c66f68..af0cd53 100644 --- a/src/utils/scoresaber/format.js +++ b/src/utils/scoresaber/format.js @@ -1,12 +1,12 @@ -import {capitalize, opt} from '../js' +import { capitalize, opt } from "../js"; export const diffColors = { - easy: 'MediumSeaGreen', - normal: '#59b0f4', - hard: 'tomato', - expert: '#bf2a42', - expertPlus: '#8f48db', -} + easy: "MediumSeaGreen", + normal: "#59b0f4", + hard: "tomato", + expert: "#bf2a42", + expertPlus: "#8f48db", +}; export function getDiffColor(diffInfo) { return diffColors[diffInfo.diff] ? diffColors[diffInfo.diff] : null; @@ -17,28 +17,64 @@ export function extractDiffAndType(ssDiff) { if (!match) return null; return { - diff: match[1].toLowerCase().replace('plus', 'Plus'), - type: opt(match, '2', 'Standard'), + diff: match[1].toLowerCase().replace("plus", "Plus"), + type: opt(match, "2", "Standard"), }; } export function getHumanDiffInfo(diffInfo) { if (!diffInfo || !diffInfo.diff) return null; - const name = capitalize(diffInfo.diff).replace('ExpertPlus', 'Expert+'); - const typeSuffix = diffInfo.type !== 'Standard' ? '/' + diffInfo.type : ''; + const name = capitalize(diffInfo.diff).replace("ExpertPlus", "Expert+"); + const typeSuffix = diffInfo.type !== "Standard" ? "/" + diffInfo.type : ""; - switch(name) { - case 'Easy': - return {name, type: diffInfo.type, fullName: name + typeSuffix, shortName: 'Es', difficulty: 1, color: getDiffColor(diffInfo)}; - case 'Normal': - return {name, type: diffInfo.type, fullName: name + typeSuffix, shortName: 'N', difficulty: 3, color: getDiffColor(diffInfo)}; - case 'Hard': - return {name, type: diffInfo.type, fullName: name + typeSuffix, shortName: 'H', difficulty: 5, color: getDiffColor(diffInfo)}; - case 'Expert': - return {name, type: diffInfo.type, fullName: name + typeSuffix, shortName: 'Ex', difficulty: 7, color: getDiffColor(diffInfo)}; - case 'Expert+': - return {name, type: diffInfo.type, fullName: name + typeSuffix, shortName: 'E+', difficulty: 9, color: getDiffColor(diffInfo)}; + switch (name) { + case "Easy": + return { + name, + type: diffInfo.type, + fullName: name + typeSuffix, + shortName: "Es", + difficulty: 1, + color: getDiffColor(diffInfo), + }; + case "Normal": + return { + name, + type: diffInfo.type, + fullName: name + typeSuffix, + shortName: "N", + difficulty: 3, + color: getDiffColor(diffInfo), + }; + case "Hard": + return { + name, + type: diffInfo.type, + fullName: name + typeSuffix, + shortName: "H", + difficulty: 5, + color: getDiffColor(diffInfo), + }; + case "Expert": + return { + name, + type: diffInfo.type, + fullName: name + typeSuffix, + shortName: "Ex", + difficulty: 7, + color: getDiffColor(diffInfo), + }; + case "Expert+": + return { + name, + type: diffInfo.type, + fullName: name + typeSuffix, + shortName: "E+", + difficulty: 9, + color: getDiffColor(diffInfo), + }; - default: return null; + default: + return null; } -} \ No newline at end of file +} diff --git a/src/utils/scoresaber/pp.js b/src/utils/scoresaber/pp.js index 4b0a419..d71db93 100644 --- a/src/utils/scoresaber/pp.js +++ b/src/utils/scoresaber/pp.js @@ -1,3 +1,7 @@ export const WEIGHT_COEFFICIENT = 0.965; -export const getTotalPpFromSortedPps = (ppArray, startIdx = 0) => ppArray.reduce((cum, pp, idx) => cum + Math.pow(WEIGHT_COEFFICIENT, idx + startIdx) * pp, 0); \ No newline at end of file +export const getTotalPpFromSortedPps = (ppArray, startIdx = 0) => + ppArray.reduce( + (cum, pp, idx) => cum + Math.pow(WEIGHT_COEFFICIENT, idx + startIdx) * pp, + 0, + ); diff --git a/src/utils/scoresaber/song.js b/src/utils/scoresaber/song.js index eae072c..629415a 100644 --- a/src/utils/scoresaber/song.js +++ b/src/utils/scoresaber/song.js @@ -1,41 +1,97 @@ -import {capitalize} from '../js' +import { capitalize } from "../js"; // rankeds with incorrect maxScore in SS -const FUCKED_UP_RANKEDS = {"1950":798675,"1962":747155,"2720":468395,"2895":651475,"2900":531875,"3231":374555,"4022":262315,"6004":516235,"8270":176755,"9007":476675,"9023":324875,"9025":181355,"9028":141795,"11909":340515,"17020":449995,"18691":237475,"18728":438955,"19580":491395,"21628":357075,"21670":254035,"23871":594435,"29546":227355,"30818":383755,"33282":639515,"40338":311995,"40892":249435,"41481":605475,"45370":539235,"50288":824435,"50328":526355,"51360":946795,"58409":597195,"58412":721395,"59096":424235,"59409":320275,"61728":2001115,"66449":771995,"66930":875035,"66944":599035,"78657":426075,"79636":576035,"84513":487715,"99196":492315}; +const FUCKED_UP_RANKEDS = { + 1950: 798675, + 1962: 747155, + 2720: 468395, + 2895: 651475, + 2900: 531875, + 3231: 374555, + 4022: 262315, + 6004: 516235, + 8270: 176755, + 9007: 476675, + 9023: 324875, + 9025: 181355, + 9028: 141795, + 11909: 340515, + 17020: 449995, + 18691: 237475, + 18728: 438955, + 19580: 491395, + 21628: 357075, + 21670: 254035, + 23871: 594435, + 29546: 227355, + 30818: 383755, + 33282: 639515, + 40338: 311995, + 40892: 249435, + 41481: 605475, + 45370: 539235, + 50288: 824435, + 50328: 526355, + 51360: 946795, + 58409: 597195, + 58412: 721395, + 59096: 424235, + 59409: 320275, + 61728: 2001115, + 66449: 771995, + 66930: 875035, + 66944: 599035, + 78657: 426075, + 79636: 576035, + 84513: 487715, + 99196: 492315, +}; export const getMaxScore = (blocks, maxScorePerBlock = 115) => Math.floor( (blocks >= 14 ? 8 * maxScorePerBlock * (blocks - 13) : 0) + - (blocks >= 6 - ? 4 * maxScorePerBlock * (Math.min(blocks, 13) - 5) - : 0) + - (blocks >= 2 - ? 2 * maxScorePerBlock * (Math.min(blocks, 5) - 1) - : 0) + - Math.min(blocks, 1) * maxScorePerBlock + (blocks >= 6 ? 4 * maxScorePerBlock * (Math.min(blocks, 13) - 5) : 0) + + (blocks >= 2 ? 2 * maxScorePerBlock * (Math.min(blocks, 5) - 1) : 0) + + Math.min(blocks, 1) * maxScorePerBlock, ); export function getFixedLeaderboardMaxScore(leaderboardId, maxScore = null) { - return leaderboardId && FUCKED_UP_RANKEDS[leaderboardId] ? FUCKED_UP_RANKEDS[leaderboardId] : maxScore; + return leaderboardId && FUCKED_UP_RANKEDS[leaderboardId] + ? FUCKED_UP_RANKEDS[leaderboardId] + : maxScore; } -export function getAccFromScore(score, maxSongScore = null, percentageInsteadOfAcc = false) { +export function getAccFromScore( + score, + maxSongScore = null, + percentageInsteadOfAcc = false, +) { if (!score) return null; const leaderboardId = score.leaderboardId; const maxScore = getFixedLeaderboardMaxScore(leaderboardId, maxSongScore); - const scoreMult = !percentageInsteadOfAcc && score.unmodifiedScore && score.score ? score.score / score.unmodifiedScore : 1 + const scoreMult = + !percentageInsteadOfAcc && score.unmodifiedScore && score.score + ? score.score / score.unmodifiedScore + : 1; return maxScore - ? score.score / maxScore / scoreMult * 100 - : (score.maxScore - ? score.score / score.maxScore / scoreMult * 100 - : null) + ? (score.score / maxScore / scoreMult) * 100 + : score.maxScore + ? (score.score / score.maxScore / scoreMult) * 100 + : null; } export function findDiffInfoWithDiffAndType(characteristics, diffAndType) { - if (!characteristics || !Array.isArray(characteristics) || !diffAndType || !diffAndType.type || !diffAndType.diff) return null; + if ( + !characteristics || + !Array.isArray(characteristics) || + !diffAndType || + !diffAndType.type || + !diffAndType.diff + ) + return null; return characteristics.reduce((cum, ch) => { if (ch.name === diffAndType.type) { @@ -47,13 +103,30 @@ export function findDiffInfoWithDiffAndType(characteristics, diffAndType) { } export function findDiffInfoWithDiffAndTypeFromBeatMaps(diffs, diffAndType) { - return !diffs || !Array.isArray(diffs) || !diffAndType || !diffAndType.type || !diffAndType.diff + return !diffs || + !Array.isArray(diffs) || + !diffAndType || + !diffAndType.type || + !diffAndType.diff ? null - : diffs.find(diff => diff.characteristic === diffAndType.type && diff.difficulty === capitalize(diffAndType.diff)); + : diffs.find( + (diff) => + diff.characteristic === diffAndType.type && + diff.difficulty === capitalize(diffAndType.diff), + ); } -export function getMaxScoreFromSongCharacteristics(songCharacteristics, diffInfo, maxScorePerBlock = 115) { - const songDiffInfo = findDiffInfoWithDiffAndType(songCharacteristics, diffInfo); +export function getMaxScoreFromSongCharacteristics( + songCharacteristics, + diffInfo, + maxScorePerBlock = 115, +) { + const songDiffInfo = findDiffInfoWithDiffAndType( + songCharacteristics, + diffInfo, + ); - return songDiffInfo && songDiffInfo.length && songDiffInfo.notes ? getMaxScore(songDiffInfo.notes, maxScorePerBlock) : 0; + return songDiffInfo && songDiffInfo.length && songDiffInfo.notes + ? getMaxScore(songDiffInfo.notes, maxScorePerBlock) + : 0; } diff --git a/src/utils/uuid.js b/src/utils/uuid.js index 92f20e8..b9693fd 100644 --- a/src/utils/uuid.js +++ b/src/utils/uuid.js @@ -1,20 +1,25 @@ // https://gist.github.com/jed/982883#gistcomment-1615714 export const uuid = (a) => { - return a // if the placeholder was passed, return - ? ( // a random number from 0 to 15 - a ^ // unless b is 8, - crypto.getRandomValues(new Uint8Array(1))[0] // in which case - % 16 // a random number from - >> a/4 // 8 to 11 - ).toString(16) // in hexadecimal - : ( // or otherwise a concatenated string: - [1e7] + // 10000000 + - -1e3 + // -1000 + - -4e3 + // -4000 + - -8e3 + // -80000000 + - -1e11 // -100000000000, - ).replace( // replacing - /[018]/g, // zeroes, ones, and eights with - uuid // random hex digits - ) -} \ No newline at end of file + return a // if the placeholder was passed, return + ? // a random number from 0 to 15 + ( + a ^ // unless b is 8, + (crypto.getRandomValues(new Uint8Array(1))[0] % // in which case + 16 >> // a random number from + (a / 4)) + ) // 8 to 11 + .toString(16) // in hexadecimal + : // or otherwise a concatenated string: + ( + [1e7] + // 10000000 + + -1e3 + // -1000 + + -4e3 + // -4000 + + -8e3 + // -80000000 + + -1e11 + ) // -100000000000, + .replace( + // replacing + /[018]/g, // zeroes, ones, and eights with + uuid, // random hex digits + ); +}; diff --git a/src/utils/worker-wrappers.js b/src/utils/worker-wrappers.js index 74b877d..50c7aa6 100644 --- a/src/utils/worker-wrappers.js +++ b/src/utils/worker-wrappers.js @@ -1,13 +1,13 @@ -import * as Comlink from 'comlink' -import log from '../utils/logger' +import * as Comlink from "comlink"; +import log from "../utils/logger"; export let worker = null; export default async () => { - log.info('Initializing workers...', 'Workers') + log.info("Initializing workers...", "Workers"); - worker = Comlink.wrap(new Worker('/build/stats-worker.js?20210825')); + worker = Comlink.wrap(new Worker("/build/stats-worker.js?20210825")); await worker.init(); - log.info('Workers initialized.', 'Workers') -} \ No newline at end of file + log.info("Workers initialized.", "Workers"); +}; diff --git a/src/workers/stats-worker.js b/src/workers/stats-worker.js index 96e7929..71261b6 100644 --- a/src/workers/stats-worker.js +++ b/src/workers/stats-worker.js @@ -1,16 +1,19 @@ -import {expose} from 'comlink' -import initDb from '../db/db' -import scoresRepository from '../db/repository/scores' -import rankedsRepository from '../db/repository/rankeds' -import eventBus from '../utils/broadcast-channel-pubsub' -import {convertArrayToObjectByKey} from '../utils/js' -import {diffColors} from '../utils/scoresaber/format' -import {getAccFromScore} from '../utils/scoresaber/song' -import {getTotalPpFromSortedPps, WEIGHT_COEFFICIENT} from '../utils/scoresaber/pp' -import makePendingPromisePool from '../utils/pending-promises' -import produce, {setAutoFreeze} from 'immer' -import beatmapsEnhancer from '../stores/http/enhancers/common/beatmaps' -import accEnhancer from '../stores/http/enhancers/scores/acc' +import { expose } from "comlink"; +import initDb from "../db/db"; +import scoresRepository from "../db/repository/scores"; +import rankedsRepository from "../db/repository/rankeds"; +import eventBus from "../utils/broadcast-channel-pubsub"; +import { convertArrayToObjectByKey } from "../utils/js"; +import { diffColors } from "../utils/scoresaber/format"; +import { getAccFromScore } from "../utils/scoresaber/song"; +import { + getTotalPpFromSortedPps, + WEIGHT_COEFFICIENT, +} from "../utils/scoresaber/pp"; +import makePendingPromisePool from "../utils/pending-promises"; +import produce, { setAutoFreeze } from "immer"; +import beatmapsEnhancer from "../stores/http/enhancers/common/beatmaps"; +import accEnhancer from "../stores/http/enhancers/scores/acc"; let db = null; @@ -18,14 +21,18 @@ let rankeds = null; const resolvePromiseOrWaitForPending = makePendingPromisePool(); -const getPlayerScores = async playerId => scoresRepository().getAllFromIndex('scores-playerId', playerId, true); +const getPlayerScores = async (playerId) => + scoresRepository().getAllFromIndex("scores-playerId", playerId, true); const getRankedsFromDb = async (refreshCache = false) => { - const dbRankeds = await rankedsRepository().getAll(refreshCache) + const dbRankeds = await rankedsRepository().getAll(refreshCache); - return dbRankeds ? convertArrayToObjectByKey(dbRankeds, 'leaderboardId') : {} -} + return dbRankeds ? convertArrayToObjectByKey(dbRankeds, "leaderboardId") : {}; +}; -const getRankeds = async (refreshCache = false) => resolvePromiseOrWaitForPending(`rankeds/${refreshCache}`, () => getRankedsFromDb()) +const getRankeds = async (refreshCache = false) => + resolvePromiseOrWaitForPending(`rankeds/${refreshCache}`, () => + getRankedsFromDb(), + ); async function init() { if (db) return; @@ -34,16 +41,16 @@ async function init() { // setup immer.js // WORKAROUND for immer.js esm (see https://github.com/immerjs/immer/issues/557) - self.process = {env: {NODE_ENV: "production"}}; + self.process = { env: { NODE_ENV: "production" } }; setAutoFreeze(false); rankeds = getRankeds(); - eventBus.on('rankeds-changed', () => rankeds = getRankeds(true)); + eventBus.on("rankeds-changed", () => (rankeds = getRankeds(true))); } const getRankedScores = async (playerId, withStars = false) => { - const scores = await getPlayerScores(playerId) + const scores = await getPlayerScores(playerId); if (!scores || !scores.length) return null; @@ -53,86 +60,134 @@ const getRankedScores = async (playerId, withStars = false) => { } return withStars - ? (await Promise.all(scores - .filter(score => score?.score?.pp) - .map(async score => { - score = await produce(await produce(score, draft => beatmapsEnhancer(draft, true)), draft => accEnhancer(draft)) + ? ( + await Promise.all( + scores + .filter((score) => score?.score?.pp) + .map(async (score) => { + score = await produce( + await produce(score, (draft) => beatmapsEnhancer(draft, true)), + (draft) => accEnhancer(draft), + ); - return { - ...score, - stars: allRankeds[score?.leaderboardId]?.stars ?? null, - } - })) - ) - .filter(s => s.stars) - : scores.filter(score => score?.score?.pp); -} + return { + ...score, + stars: allRankeds[score?.leaderboardId]?.stars ?? null, + }; + }), + ) + ).filter((s) => s.stars) + : scores.filter((score) => score?.score?.pp); +}; -const getPlayerRankedScoresWithStars = async playerId => getRankedScores(playerId, true) +const getPlayerRankedScoresWithStars = async (playerId) => + getRankedScores(playerId, true); -const calcPlayerStats = async playerId => { +const calcPlayerStats = async (playerId) => { await init(); const rankedScores = await getRankedScores(playerId); if (!rankedScores) return null; const stats = rankedScores - .filter(score => (score?.score?.score && score?.score?.maxScore) || score?.score?.acc) - .reduce((cum, s) => { - const leaderboardId = s?.leaderboard?.leaderboardId; - const pp = s?.score?.pp; - const score = s?.score?.unmodifiedScore ?? s?.score?.score ?? 0; - const accFromScore = getAccFromScore({...s.score, leaderboardId}); - const scoreAcc = s?.score?.acc; + .filter( + (score) => + (score?.score?.score && score?.score?.maxScore) || score?.score?.acc, + ) + .reduce( + (cum, s) => { + const leaderboardId = s?.leaderboard?.leaderboardId; + const pp = s?.score?.pp; + const score = s?.score?.unmodifiedScore ?? s?.score?.score ?? 0; + const accFromScore = getAccFromScore({ ...s.score, leaderboardId }); + const scoreAcc = s?.score?.acc; - if (!accFromScore && !scoreAcc) return cum; + if (!accFromScore && !scoreAcc) return cum; - let acc = accFromScore ? accFromScore : scoreAcc; - if (!acc || isNaN(acc)) return cum; + let acc = accFromScore ? accFromScore : scoreAcc; + if (!acc || isNaN(acc)) return cum; - s.score.acc = acc; - cum.totalScore += score; - cum.totalAcc += acc; + s.score.acc = acc; + cum.totalScore += score; + cum.totalAcc += acc; - if (cum.topAcc < acc) cum.topAcc = acc; - if (cum.topPp < pp) cum.topPp = pp; + if (cum.topAcc < acc) cum.topAcc = acc; + if (cum.topPp < pp) cum.topPp = pp; - cum.badges.forEach(badge => { - if ((!badge.min || badge.min <= acc) && (!badge.max || badge.max > acc)) badge.value++; - }) + cum.badges.forEach((badge) => { + if ( + (!badge.min || badge.min <= acc) && + (!badge.max || badge.max > acc) + ) + badge.value++; + }); - return cum; - }, { - playerId, - badges: [ - {label: 'SS+', min: 95, max: null, value: 0, bgColor: diffColors.expertPlus}, - {label: 'SS', min: 90, max: 95, value: 0, bgColor: diffColors.expert}, - {label: 'S+', min: 85, max: 90, value: 0, bgColor: diffColors.hard}, - {label: 'S', min: 80, max: 85, value: 0, bgColor: diffColors.normal}, - {label: 'A', min: null, max: 80, value: 0, bgColor: diffColors.easy}, - ], - topAcc: 0, - topPp: 0, - totalAcc: 0, - totalScore: 0, - avgAcc: 0, - playCount: rankedScores.length, - medianAcc: 0, - stdDeviation: 0, - }) + return cum; + }, + { + playerId, + badges: [ + { + label: "SS+", + min: 95, + max: null, + value: 0, + bgColor: diffColors.expertPlus, + }, + { + label: "SS", + min: 90, + max: 95, + value: 0, + bgColor: diffColors.expert, + }, + { label: "S+", min: 85, max: 90, value: 0, bgColor: diffColors.hard }, + { + label: "S", + min: 80, + max: 85, + value: 0, + bgColor: diffColors.normal, + }, + { + label: "A", + min: null, + max: 80, + value: 0, + bgColor: diffColors.easy, + }, + ], + topAcc: 0, + topPp: 0, + totalAcc: 0, + totalScore: 0, + avgAcc: 0, + playCount: rankedScores.length, + medianAcc: 0, + stdDeviation: 0, + }, + ); - stats.medianAcc = rankedScores.length > 1 - ? (rankedScores.sort((a, b) => a.score.acc - b.score.acc))[Math.ceil(rankedScores.length / 2)].score.acc - : stats.totalAcc; + stats.medianAcc = + rankedScores.length > 1 + ? rankedScores.sort((a, b) => a.score.acc - b.score.acc)[ + Math.ceil(rankedScores.length / 2) + ].score.acc + : stats.totalAcc; stats.avgAcc = stats.totalAcc / rankedScores.length; - stats.stdDeviation = Math.sqrt(rankedScores.reduce((sum, s) => sum + Math.pow(stats.avgAcc - s.score.acc, 2), 0) / rankedScores.length); + stats.stdDeviation = Math.sqrt( + rankedScores.reduce( + (sum, s) => sum + Math.pow(stats.avgAcc - s.score.acc, 2), + 0, + ) / rankedScores.length, + ); delete stats.totalAcc; - eventBus.publish('player-stats-calculated', stats); + eventBus.publish("player-stats-calculated", stats); return stats; -} +}; const calcPpBoundary = async (playerId, expectedPp = 1) => { const rankedScores = await getRankedScores(playerId); @@ -144,10 +199,12 @@ const calcPpBoundary = async (playerId, expectedPp = 1) => { // 0.965^idx * rawPpToFind = expected + oldBottomPp - newBottomPp; // rawPpToFind = (expected + oldBottomPp - newBottomPp) / 0.965^idx; - return (expected + oldBottomPp - newBottomPp) / Math.pow(WEIGHT_COEFFICIENT, idx); - } + return ( + (expected + oldBottomPp - newBottomPp) / Math.pow(WEIGHT_COEFFICIENT, idx) + ); + }; - const rankedScorePps = rankedScores.map(s => s.pp).sort((a, b) => b - a); + const rankedScorePps = rankedScores.map((s) => s.pp).sort((a, b) => b - a); let idx = rankedScorePps.length - 1; @@ -160,9 +217,17 @@ const calcPpBoundary = async (playerId, expectedPp = 1) => { const diff = modifiedBottomPp - bottomPp; if (diff > expectedPp) { - const ppBoundary = calcRawPpAtIdx(rankedScorePps.slice(idx + 1), idx + 1, expectedPp); + const ppBoundary = calcRawPpAtIdx( + rankedScorePps.slice(idx + 1), + idx + 1, + expectedPp, + ); - eventBus.publish('player-pp-boundary-calculated', {playerId, expectedPp, ppBoundary}); + eventBus.publish("player-pp-boundary-calculated", { + playerId, + expectedPp, + ppBoundary, + }); return ppBoundary; } @@ -172,16 +237,20 @@ const calcPpBoundary = async (playerId, expectedPp = 1) => { const ppBoundary = calcRawPpAtIdx(rankedScorePps, 0, expectedPp); - eventBus.publish('player-pp-boundary-calculated', {playerId, expectedPp, ppBoundary}); + eventBus.publish("player-pp-boundary-calculated", { + playerId, + expectedPp, + ppBoundary, + }); return ppBoundary; -} +}; const worker = { init, calcPlayerStats, calcPpBoundary, - getPlayerRankedScoresWithStars -} + getPlayerRankedScoresWithStars, +}; -expose(worker); \ No newline at end of file +expose(worker); diff --git a/tsconfig.json b/tsconfig.json index b082e96..5431248 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,4 +3,4 @@ "include": ["src/**/*"], "exclude": ["node_modules/*", "__sapper__/*", "public/*"] -} \ No newline at end of file +} diff --git a/yarn.lock b/yarn.lock index 69f4be5..061d1a5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -693,6 +693,11 @@ picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.2: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== +prettier@3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.0.3.tgz#432a51f7ba422d1469096c0fdc28e235db8f9643" + integrity sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg== + randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"