Compare commits

..

1 Commits

Author SHA1 Message Date
Crylia 9210f0ed84 Initial commit 2025-10-20 01:01:50 +02:00
73 changed files with 230 additions and 26104 deletions
-40
View File
@@ -1,40 +0,0 @@
name: Build and Push Docker Images
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to local registry
if: ${{ secrets.REGISTRY_USER != '' }}
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login 192.168.0.26:5008 -u ${{ secrets.REGISTRY_USER }} --password-stdin || true
- name: Build and Push Client
run: |
echo "🚀 Building Client..."
docker buildx build --load -t crylia/japanese-srs-trainer-wanikani-client:latest -f client/Dockerfile client
docker tag crylia/japanese-srs-trainer-wanikani-client:latest 192.168.0.26:5008/japanese-srs-trainer-wanikani-client:latest
docker push 192.168.0.26:5008/japanese-srs-trainer-wanikani-client:latest
- name: Build and Push Server
run: |
echo "🚀 Building Server..."
docker buildx build \
--build-arg ACCESS_TOKEN_SECRET=${{ secrets.ACCESS_TOKEN_SECRET }} \
--build-arg REFRESH_TOKEN_SECRET=${{ secrets.REFRESH_TOKEN_SECRET }} \
--load -t crylia/japanese-srs-trainer-wanikani-server:latest -f server/Dockerfile server
docker tag crylia/japanese-srs-trainer-wanikani-server:latest 192.168.0.26:5008/japanese-srs-trainer-wanikani-server:latest
docker push 192.168.0.26:5008/japanese-srs-trainer-wanikani-server:latest
-40
View File
@@ -1,40 +0,0 @@
# Node modules
node_modules/
**/node_modules/
# Vite / Vue build output
dist/
build/
.vite/
# Logs
npm-debug.log*
yarn-debug.log*
pnpm-debug.log*
# Environment files
.env
.env.local
.env.*.local
# TypeScript
*.tsbuildinfo
# VSCode
.vscode/
# JetBrains
.idea/
# System
.DS_Store
Thumbs.db
# Lint / Typegen
*.d.ts
*.eslintcache
# Ignore temporary files
*.tmp
*.temp
-1
View File
@@ -1 +0,0 @@
{}
+224 -666
View File
@@ -1,674 +1,232 @@
GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007 Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble 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.
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 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 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 your programs, too.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast, 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.
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 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.
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 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 know their rights.
any other work released this way by its authors. You can apply it to
your programs, too. 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.
When we speak of free software, we are referring to freedom, not 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.
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for 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 pattern of such abuse occurs in the area of products for individuals to 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 stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
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 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 patents cannot be used to render the program non-free.
free programs, and that you know you can do these things.
The precise terms and conditions for copying, distribution and modification follow.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have TERMS AND CONDITIONS
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others. 0. Definitions.
For example, if you distribute copies of such a program, whether “This License” refers to version 3 of the GNU General Public License.
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 “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
or can get the source code. And you must show them these terms so they
know their rights. “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.
Developers that use the GNU GPL protect your rights with two steps: 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 earlier work or a work “based on” the earlier work.
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it. A “covered work” means either the unmodified Program or a work based on the Program.
For the developers' and authors' protection, the GPL clearly explains 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, distribution (with or without modification), making available to the public, and in some countries other activities as well.
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as 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.
changed, so that their problems will not be attributed erroneously to
authors of previous versions. 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 the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
Some devices are designed to deny users access to install or run 1. Source Code.
modified versions of the software inside them, although the manufacturer 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.
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic 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.
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we 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 “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.
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we 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 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 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.
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
Finally, every program is threatened constantly by software patents. The Corresponding Source for a work in source code form is that same work.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to 2. Basic Permissions.
avoid the special danger that patents applied to a free program could 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 covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free. 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 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 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.
The precise terms and conditions for copying, distribution and Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
modification follow.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
TERMS AND CONDITIONS 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.
0. Definitions. 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 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.
"This License" refers to version 3 of the GNU General Public License. 4. Conveying Verbatim Copies.
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 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.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks. 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.
"The Program" refers to any copyrightable work licensed under this 5. Conveying Modified Source Versions.
License. Each licensee is addressed as "you". "Licensees" and 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:
"recipients" may be individuals or organizations.
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
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 b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work. c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
A "covered work" means either the unmodified Program or a work based d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
on the Program.
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 in an aggregate does not cause this License to apply to the other parts of the aggregate.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for 6. Conveying Non-Source Forms.
infringement under applicable copyright law, except executing it on a 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:
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
public, and in some countries other activities as well.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
a computer network, with no transfer of a copy, is not conveying.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the 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.
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If 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 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 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.
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion. “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 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.
1. Source Code. 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 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 "source code" for a work means the preferred form of the work 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 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.
for making modifications to it. "Object code" means any non-source
form of a work. 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.
A "Standard Interface" means an interface that either is an official 7. Additional Terms.
standard defined by a recognized standards body, or, in the case of “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 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.
interfaces specified for a particular programming language, one that
is widely used among developers working in that language. 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 additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
The "System Libraries" of an executable work include anything, other 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:
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 a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
produce the work, or an object code interpreter used to run it.
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's 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 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.
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but 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.
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for 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.
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, 8. Termination.
such as by intimate data communication or control flow between those 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).
subprograms and other parts of the work.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding 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.
Source.
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 reinstated, you do not qualify to receive new licenses for the same material under section 10.
The Corresponding Source for a work in source code form is that
same work. 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 occurring solely as a consequence of using peer-to-peer transmission 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 covered work, you indicate your acceptance of this License to do so.
2. Basic Permissions.
10. Automatic Licensing of Downstream Recipients.
All rights granted under this License are granted for the term of 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 for enforcing compliance by third parties with this License.
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited 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 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 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.
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its 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.
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law. 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 work thus licensed is called the contributor's “contributor version”.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains 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 purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you 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.
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do 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 party means to make such an agreement or commitment not to enforce a patent against the party.
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction 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, 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 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.
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you. 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 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.
Conveying under any other circumstances is permitted solely under 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 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 the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily 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.
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary. 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.
3. Protecting Users' Legal Rights From Anti-Circumvention Law. 12. No Surrender of Others' Freedom.
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 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 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.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article 13. Use with the GNU Affero General Public License.
11 of the WIPO copyright treaty adopted on 20 December 1996, or 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 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.
similar laws prohibiting or restricting circumvention of such
measures. 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 be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention 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 GNU General Public License, you may choose any version ever published by the Free Software Foundation.
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or 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.
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of 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.
technological measures.
15. Disclaimer of Warranty.
4. Conveying Verbatim Copies. 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 ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
You may convey verbatim copies of the Program's source code as you 16. Limitation of Liability.
receive it, in any medium, provided that you conspicuously and 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 USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 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.
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any 17. Interpretation of Sections 15 and 16.
non-permissive terms added in accord with section 7 apply to the code; 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 Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program. END OF TERMS AND CONDITIONS
You may charge any price or no price for each copy that you convey, How to Apply These Terms to Your New Programs
and you may offer support or warranty protection for a fee.
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.
5. Conveying Modified Source Versions.
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.
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 japanese-srs-trainer-wanikani
terms of section 4, provided that you also meet all of these conditions: Copyright (C) 2025 Crylia
a) The work must carry prominent notices stating that you modified This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
it, and giving a relevant date.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
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
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
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
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:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
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
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
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
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
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,
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
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
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
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
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
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,
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.
"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
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
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
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
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
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
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
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
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
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
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
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
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
licenses of parties who have received copies or rights from you under
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.
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,
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
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
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
for enforcing compliance by third parties with this License.
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
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
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
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.
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
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
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
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
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
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,
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,
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
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
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
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
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
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
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
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
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.
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
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
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.
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
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.
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
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
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
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
author or copyright holder as a result of your choosing to follow a
later version.
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
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
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
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
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
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.
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
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
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 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail. 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:
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> japanese-srs-trainer-wanikani Copyright (C) 2025 Crylia
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate The hypothetical commands `show w' and `show c' should show the appropriate 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”.
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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program 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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+5
View File
@@ -0,0 +1,5 @@
# japanese-srs-trainer-wanikani
An srs card trainer using the wanikani api to train kanji hand writing and translating in both directions.
-4
View File
@@ -1,4 +0,0 @@
> 1%
last 2 versions
not dead
not ie 11
-27
View File
@@ -1,27 +0,0 @@
# Node modules
node_modules
**/node_modules
# Git
.git
.gitignore
# Logs
*.log
# Local dev / editor
.vscode
.idea
# Build output
dist
build
.vite
# TypeScript build info
*.tsbuildinfo
# Environment files (if you want them injected via Docker ENV)
.env
.env.local
.env.*.local
-6
View File
@@ -1,6 +0,0 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
-3
View File
@@ -1,3 +0,0 @@
node_modules/
dist/
public/
-85
View File
@@ -1,85 +0,0 @@
{
"globals": {
"Component": true,
"ComponentPublicInstance": true,
"ComputedRef": true,
"DirectiveBinding": true,
"EffectScope": true,
"ExtractDefaultPropTypes": true,
"ExtractPropTypes": true,
"ExtractPublicPropTypes": true,
"InjectionKey": true,
"MaybeRef": true,
"MaybeRefOrGetter": true,
"PropType": true,
"Ref": true,
"ShallowRef": true,
"Slot": true,
"Slots": true,
"VNode": true,
"WritableComputedRef": true,
"computed": true,
"createApp": true,
"customRef": true,
"defineAsyncComponent": true,
"defineComponent": true,
"defineStore": true,
"effectScope": true,
"getCurrentInstance": true,
"getCurrentScope": true,
"getCurrentWatcher": true,
"h": true,
"inject": true,
"isProxy": true,
"isReactive": true,
"isReadonly": true,
"isRef": true,
"isShallow": true,
"markRaw": true,
"nextTick": true,
"onActivated": true,
"onBeforeMount": true,
"onBeforeRouteLeave": true,
"onBeforeRouteUpdate": true,
"onBeforeUnmount": true,
"onBeforeUpdate": true,
"onDeactivated": true,
"onErrorCaptured": true,
"onMounted": true,
"onRenderTracked": true,
"onRenderTriggered": true,
"onScopeDispose": true,
"onServerPrefetch": true,
"onUnmounted": true,
"onUpdated": true,
"onWatcherCleanup": true,
"provide": true,
"reactive": true,
"readonly": true,
"ref": true,
"resolveComponent": true,
"shallowReactive": true,
"shallowReadonly": true,
"shallowRef": true,
"storeToRefs": true,
"toRaw": true,
"toRef": true,
"toRefs": true,
"toValue": true,
"triggerRef": true,
"unref": true,
"useAttrs": true,
"useCssModule": true,
"useCssVars": true,
"useId": true,
"useModel": true,
"useRoute": true,
"useRouter": true,
"useSlots": true,
"useTemplateRef": true,
"watch": true,
"watchEffect": true,
"watchPostEffect": true,
"watchSyncEffect": true
}
}
-22
View File
@@ -1,22 +0,0 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
-15
View File
@@ -1,15 +0,0 @@
{
"hash": "92874bb6",
"configHash": "ae1864eb",
"lockfileHash": "a03ea363",
"browserHash": "03c64258",
"optimized": {
"vue": {
"src": "../../node_modules/.pnpm/vue@3.5.22_typescript@5.9.3/node_modules/vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "6b167e91",
"needsInterop": false
}
},
"chunks": {}
}
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
-15
View File
@@ -1,15 +0,0 @@
FROM node:24-alpine
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /app
COPY pnpm-lock.yaml package*.json ./
RUN pnpm i
COPY . .
EXPOSE 5173
CMD [ "pnpm", "run", "dev", "--", "--host", "0.0.0.0" ]
-81
View File
@@ -1,81 +0,0 @@
# Vuetify (Default)
This is the official scaffolding tool for Vuetify, designed to give you a head start in building your new Vuetify application. It sets up a base template with all the necessary configurations and standard directory structure, enabling you to begin development without the hassle of setting up the project from scratch.
## ❗️ Important Links
- 📄 [Docs](https://vuetifyjs.com/)
- 🚨 [Issues](https://issues.vuetifyjs.com/)
- 🏬 [Store](https://store.vuetifyjs.com/)
- 🎮 [Playground](https://play.vuetifyjs.com/)
- 💬 [Discord](https://community.vuetifyjs.com)
## 💿 Install
Set up your project using your preferred package manager. Use the corresponding command to install the dependencies:
| Package Manager | Command |
|---------------------------------------------------------------|----------------|
| [yarn](https://yarnpkg.com/getting-started) | `yarn install` |
| [npm](https://docs.npmjs.com/cli/v7/commands/npm-install) | `npm install` |
| [pnpm](https://pnpm.io/installation) | `pnpm install` |
| [bun](https://bun.sh/#getting-started) | `bun install` |
After completing the installation, your environment is ready for Vuetify development.
## ✨ Features
- 🖼️ **Optimized Front-End Stack**: Leverage the latest Vue 3 and Vuetify 3 for a modern, reactive UI development experience. [Vue 3](https://v3.vuejs.org/) | [Vuetify 3](https://vuetifyjs.com/en/)
- 🗃️ **State Management**: Integrated with [Pinia](https://pinia.vuejs.org/), the intuitive, modular state management solution for Vue.
- 🚦 **Routing and Layouts**: Utilizes Vue Router for SPA navigation and vite-plugin-vue-layouts-next for organizing Vue file layouts. [Vue Router](https://router.vuejs.org/) | [vite-plugin-vue-layouts-next](https://github.com/loicduong/vite-plugin-vue-layouts-next)
- 💻 **Enhanced Development Experience**: Benefit from TypeScript's static type checking and the ESLint plugin suite for Vue, ensuring code quality and consistency. [TypeScript](https://www.typescriptlang.org/) | [ESLint Plugin Vue](https://eslint.vuejs.org/)
-**Next-Gen Tooling**: Powered by Vite, experience fast cold starts and instant HMR (Hot Module Replacement). [Vite](https://vitejs.dev/)
- 🧩 **Automated Component Importing**: Streamline your workflow with unplugin-vue-components, automatically importing components as you use them. [unplugin-vue-components](https://github.com/antfu/unplugin-vue-components)
- 🛠️ **Strongly-Typed Vue**: Use vue-tsc for type-checking your Vue components, and enjoy a robust development experience. [vue-tsc](https://github.com/johnsoncodehk/volar/tree/master/packages/vue-tsc)
These features are curated to provide a seamless development experience from setup to deployment, ensuring that your Vuetify application is both powerful and maintainable.
## 💡 Usage
This section covers how to start the development server and build your project for production.
### Starting the Development Server
To start the development server with hot-reload, run the following command. The server will be accessible at [http://localhost:3000](http://localhost:3000):
```bash
yarn dev
```
(Repeat for npm, pnpm, and bun with respective commands.)
> Add NODE_OPTIONS='--no-warnings' to suppress the JSON import warnings that happen as part of the Vuetify import mapping. If you are on Node [v21.3.0](https://nodejs.org/en/blog/release/v21.3.0) or higher, you can change this to NODE_OPTIONS='--disable-warning=5401'. If you don't mind the warning, you can remove this from your package.json dev script.
### Building for Production
To build your project for production, use:
```bash
yarn build
```
(Repeat for npm, pnpm, and bun with respective commands.)
Once the build process is completed, your application will be ready for deployment in a production environment.
## 💪 Support Vuetify Development
This project is built with [Vuetify](https://vuetifyjs.com/en/), a UI Library with a comprehensive collection of Vue components. Vuetify is an MIT licensed Open Source project that has been made possible due to the generous contributions by our [sponsors and backers](https://vuetifyjs.com/introduction/sponsors-and-backers/). If you are interested in supporting this project, please consider:
- [Requesting Enterprise Support](https://support.vuetifyjs.com/)
- [Sponsoring John on Github](https://github.com/users/johnleider/sponsorship)
- [Sponsoring Kael on Github](https://github.com/users/kaelwd/sponsorship)
- [Supporting the team on Open Collective](https://opencollective.com/vuetify)
- [Becoming a sponsor on Patreon](https://www.patreon.com/vuetify)
- [Becoming a subscriber on Tidelift](https://tidelift.com/subscription/npm/vuetify)
- [Making a one-time donation with Paypal](https://paypal.me/vuetify)
## 📑 License
[MIT](http://opensource.org/licenses/MIT)
Copyright (c) 2016-present Vuetify, LLC
-3
View File
@@ -1,3 +0,0 @@
/// <reference types="vite/client" />
/// <reference types="unplugin-vue-router/client" />
/// <reference types="vite-plugin-vue-layouts-next/client" />
-13
View File
@@ -1,13 +0,0 @@
import vuetify from 'eslint-config-vuetify'
export default [
vuetify(),
{
ignores: [
'node_modules/**',
'dist/**',
'public/**',
'*.min.js',
],
},
]
-19
View File
@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Japanese SRS Trainer</title>
</head>
<body>
<div id="app"></div>
<script src="/kanji-canvas.min.js"></script>
<script src="/ref-patterns.js"></script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
View File
-45
View File
@@ -1,45 +0,0 @@
{
"name": "client",
"private": true,
"type": "module",
"version": "0.0.0",
"scripts": {
"dev": "vite --host",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build --force",
"lint": "eslint . --fix"
},
"dependencies": {
"@fontsource/roboto": "5.2.7",
"@mdi/font": "7.4.47",
"axios": "^1.12.2",
"pinia": "^3.0.3",
"pug": "^3.0.3",
"vue": "^3.5.21",
"vue-pug": "^1.0.2",
"vue-router": "^4.5.1",
"vuetify": "^3.10.1",
"wanakana": "^5.3.1"
},
"devDependencies": {
"@tsconfig/node22": "^22.0.0",
"@types/node": "^22.9.0",
"@vitejs/plugin-vue": "^6.0.1",
"@vue/tsconfig": "^0.8.1",
"eslint": "^9.35.0",
"eslint-config-vuetify": "^4.2.0",
"npm-run-all2": "^8.0.4",
"sass-embedded": "^1.92.1",
"typescript": "~5.9.2",
"unplugin-auto-import": "^20.1.0",
"unplugin-fonts": "^1.4.0",
"unplugin-vue-components": "^29.0.0",
"unplugin-vue-router": "^0.15.0",
"vite": "^7.1.5",
"vite-plugin-vue-layouts-next": "^1.0.0",
"vite-plugin-vuetify": "^2.1.2",
"vue-tsc": "^3.0.7"
}
}
-4268
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-5
View File
@@ -1,5 +0,0 @@
<template>
<v-app>
<router-view />
</v-app>
</template>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

-6
View File
@@ -1,6 +0,0 @@
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M261.126 140.65L164.624 307.732L256.001 466L377.028 256.5L498.001 47H315.192L261.126 140.65Z" fill="#1697F6"/>
<path d="M135.027 256.5L141.365 267.518L231.64 111.178L268.731 47H256H14L135.027 256.5Z" fill="#AEDDFF"/>
<path d="M315.191 47C360.935 197.446 256 466 256 466L164.624 307.732L315.191 47Z" fill="#1867C0"/>
<path d="M268.731 47C76.0026 47 141.366 267.518 141.366 267.518L268.731 47Z" fill="#7BC6FF"/>
</svg>

Before

Width:  |  Height:  |  Size: 526 B

-151
View File
@@ -1,151 +0,0 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const EffectScope: typeof import('vue')['EffectScope']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const effectScope: typeof import('vue')['effectScope']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const getCurrentWatcher: typeof import('vue')['getCurrentWatcher']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const isShallow: typeof import('vue')['isShallow']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeRouteLeave: typeof import('vue-router')['onBeforeRouteLeave']
const onBeforeRouteUpdate: typeof import('vue-router')['onBeforeRouteUpdate']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const reactive: typeof import('vue')['reactive']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const storeToRefs: typeof import('pinia')['storeToRefs']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useId: typeof import('vue')['useId']
const useModel: typeof import('vue')['useModel']
const useRoute: typeof import('vue-router')['useRoute']
const useRouter: typeof import('vue-router')['useRouter']
const useSlots: typeof import('vue')['useSlots']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly computed: UnwrapRef<typeof import('vue')['computed']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly defineStore: UnwrapRef<typeof import('pinia')['defineStore']>
readonly effectScope: UnwrapRef<typeof import('vue')['effectScope']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly getCurrentWatcher: UnwrapRef<typeof import('vue')['getCurrentWatcher']>
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
readonly isReadonly: UnwrapRef<typeof import('vue')['isReadonly']>
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly isShallow: UnwrapRef<typeof import('vue')['isShallow']>
readonly markRaw: UnwrapRef<typeof import('vue')['markRaw']>
readonly nextTick: UnwrapRef<typeof import('vue')['nextTick']>
readonly onActivated: UnwrapRef<typeof import('vue')['onActivated']>
readonly onBeforeMount: UnwrapRef<typeof import('vue')['onBeforeMount']>
readonly onBeforeRouteLeave: UnwrapRef<typeof import('vue-router')['onBeforeRouteLeave']>
readonly onBeforeRouteUpdate: UnwrapRef<typeof import('vue-router')['onBeforeRouteUpdate']>
readonly onBeforeUnmount: UnwrapRef<typeof import('vue')['onBeforeUnmount']>
readonly onBeforeUpdate: UnwrapRef<typeof import('vue')['onBeforeUpdate']>
readonly onDeactivated: UnwrapRef<typeof import('vue')['onDeactivated']>
readonly onErrorCaptured: UnwrapRef<typeof import('vue')['onErrorCaptured']>
readonly onMounted: UnwrapRef<typeof import('vue')['onMounted']>
readonly onRenderTracked: UnwrapRef<typeof import('vue')['onRenderTracked']>
readonly onRenderTriggered: UnwrapRef<typeof import('vue')['onRenderTriggered']>
readonly onScopeDispose: UnwrapRef<typeof import('vue')['onScopeDispose']>
readonly onServerPrefetch: UnwrapRef<typeof import('vue')['onServerPrefetch']>
readonly onUnmounted: UnwrapRef<typeof import('vue')['onUnmounted']>
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly onWatcherCleanup: UnwrapRef<typeof import('vue')['onWatcherCleanup']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
readonly readonly: UnwrapRef<typeof import('vue')['readonly']>
readonly ref: UnwrapRef<typeof import('vue')['ref']>
readonly resolveComponent: UnwrapRef<typeof import('vue')['resolveComponent']>
readonly shallowReactive: UnwrapRef<typeof import('vue')['shallowReactive']>
readonly shallowReadonly: UnwrapRef<typeof import('vue')['shallowReadonly']>
readonly shallowRef: UnwrapRef<typeof import('vue')['shallowRef']>
readonly storeToRefs: UnwrapRef<typeof import('pinia')['storeToRefs']>
readonly toRaw: UnwrapRef<typeof import('vue')['toRaw']>
readonly toRef: UnwrapRef<typeof import('vue')['toRef']>
readonly toRefs: UnwrapRef<typeof import('vue')['toRefs']>
readonly toValue: UnwrapRef<typeof import('vue')['toValue']>
readonly triggerRef: UnwrapRef<typeof import('vue')['triggerRef']>
readonly unref: UnwrapRef<typeof import('vue')['unref']>
readonly useAttrs: UnwrapRef<typeof import('vue')['useAttrs']>
readonly useCssModule: UnwrapRef<typeof import('vue')['useCssModule']>
readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
readonly useId: UnwrapRef<typeof import('vue')['useId']>
readonly useModel: UnwrapRef<typeof import('vue')['useModel']>
readonly useRoute: UnwrapRef<typeof import('vue-router')['useRoute']>
readonly useRouter: UnwrapRef<typeof import('vue-router')['useRouter']>
readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
readonly useTemplateRef: UnwrapRef<typeof import('vue')['useTemplateRef']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
readonly watchPostEffect: UnwrapRef<typeof import('vue')['watchPostEffect']>
readonly watchSyncEffect: UnwrapRef<typeof import('vue')['watchSyncEffect']>
}
}
-14
View File
@@ -1,14 +0,0 @@
/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
// biome-ignore lint: disable
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
}
-145
View File
@@ -1,145 +0,0 @@
import axios from 'axios'
type SubjectType = 'kanji' | 'vocab' | 'both'
type LearningDirection = 'jp->en' | 'en->jp'
type WritingMode = 'kana' | 'kanji'
interface SubjectOptions {
subject: SubjectType
direction?: LearningDirection
writingMode?: WritingMode
mode?: 'meaning' | 'reading'
writingPractice: boolean
}
interface ReviewItem {
type: 'kanji' | 'vocab'
subject: string
answers: string[]
pronunciation_audios?: string[],
mode: string,
}
let currentReviewItem: any = {}
let currentSubjectOptions: SubjectOptions
/**
* Handles logic for when a subject answer is correct.
*
* @param id - The unique identifier of the subject item.
* @param subjectOptions - Configuration describing what kind of subject
* and learning mode is being used (kanji, vocab, etc.).
* @returns void
*/
const correct = async () => (
await axios.post('/api/v1/review/correct', {
itemId: currentReviewItem.id,
currentSubjectOptions,
}, {
headers: {
'Content-Type': 'application/json',
},
})
)
/**
* Handles logic for when a subject answer is incorrect
*
* @param id - The unique identifier of the subject item.
* @param subjectOptions - Configuration describing what kind of subject
* and learning mode is being used (kanji, vocab, etc.).
* @returns void
*/
const incorrect = async () => {
await axios.post('/api/v1/review/incorrect', {
itemId: currentReviewItem.id,
currentSubjectOptions,
}, {
headers: {
'Content-Type': 'application/json',
},
})
}
/**
* Fetches the next subject from the server
*
* @param subjectOptions - Configuration describing what kind of subject
* and learning mode is being used (kanji, vocab, etc.).
*
* @returns
*/
const nextSubject = async (subjectOptions: SubjectOptions): Promise<ReviewItem | null> => {
const res = await axios.post('/api/v1/review/', { subjectOptions }, {
headers: { 'Content-Type': 'application/json' },
})
const item = res.data
if (!item || item.message === 'No reviews due') return null
const mode: 'writing_practice' | 'jp_en_meaning' | 'jp_en_reading' | 'en_jp_writing' = item._selectedMode
currentReviewItem = item
currentSubjectOptions = { ...subjectOptions, mode }
let subjectText = ''
let answers: string[] = []
let pronunciation_audios: string[] | undefined = item.pronunciation_audios
if (mode === 'writing_practice') {
subjectText = item.meanings?.filter(m => m.primary).map(m => m.meaning).join(', ') || ''
answers = [item.characters]
} else if (mode === 'jp_en_meaning') {
subjectText = item.characters
answers = item.meanings?.filter(m => m.accepted_answer).map(m => m.meaning) || []
} else if (mode === 'jp_en_reading') {
subjectText = item.characters
answers = item.readings?.filter(r => r.accepted_answer).map(r => r.reading) || []
if (answers.length === 0)
answers = [item.characters]
} else if (mode === 'en_jp_writing') {
subjectText = item.meanings?.filter(m => m.primary).map(m => m.meaning).join(', ') || ''
if (subjectOptions.writingMode === 'kanji') {
answers = [item.characters]
} else if (subjectOptions.writingMode === 'kana') {
answers = item.readings?.filter(r => r.accepted_answer).map(r => r.reading) || []
} else if (answers.length === 0)
answers = [item.characters]
}
return {
type: item.type,
subject: subjectText,
answers,
pronunciation_audios,
mode,
}
}
const getStatistics = async () => {
const res = await axios.get('/api/v1/review/stats', {
headers: {
'Content-Type': 'application/json',
},
})
return res.data
}
const getSubjectStatistics = async (id: string) => {
const res = await axios.get(`/api/v1/review/stats/${id}`, {
headers: {
'Content-Type': 'application/json',
},
})
return res.data
}
export {
correct,
incorrect,
nextSubject,
getStatistics,
getSubjectStatistics,
}
-7
View File
@@ -1,7 +0,0 @@
export { }
declare global {
interface Window {
KanjiCanvas: any
}
}
-5
View File
@@ -1,5 +0,0 @@
<template>
<v-main>
<router-view />
</v-main>
</template>
-23
View File
@@ -1,23 +0,0 @@
/**
* main.ts
*
* Bootstraps Vuetify and other plugins then mounts the App`
*/
// Composables
import { createApp } from 'vue'
// Plugins
import { registerPlugins } from '@/plugins'
// Components
import App from './App.vue'
// Styles
import 'unfonts.css'
const app = createApp(App)
registerPlugins(app)
app.mount('#app')
-308
View File
@@ -1,308 +0,0 @@
<template lang="pug">
v-container.fill-height.d-flex.justify-center.align-center
v-card.pa-12.rounded-lg.elevation-12
template(v-if="!allDone")
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary Full Trainer
v-sheet.d-flex.justify-center.align-center.rounded-lg.py-8.px-4.elevation-12(
:style="{ backgroundColor: subjectColor, fontSize: '5rem', fontWeight: 'bold', whiteSpace: 'nowrap' }"
)
span {{ character }}
v-card-text.text-center.my-4.rounded-lg(
:style="{ backgroundColor: subjectColor + '20', fontSize: '1.1rem', fontWeight: '500', color: subjectColor }"
)
| {{ inputMode === 'kanji' ? 'Kanji' : inputMode === 'writing' ? 'Writing' : inputMode }}
transition(name="alert-grow")
v-alert.mb-4(
v-if="resultMessage"
:type="isCorrect ? 'success' : 'error'"
border="top"
variant="outlined"
density="compact"
) {{ resultMessage }}
v-row.align-center
v-col(cols="9")
input#answer-input.customInput(
ref="answerInput"
placeholder="Type your answer"
:disabled="isDisabled"
)
v-col(cols="3")
v-btn(
color="primary"
block
@click="submitAnswer"
) Enter
v-row.justify-space-between
v-col(cols="4")
v-btn(
color="error"
variant="flat"
block
@click="quitSession"
) Quit
v-col(cols="4")
v-btn(
color="secondary"
variant="flat"
block
@click="createReview"
) Skip
v-col(cols="4")
v-btn(
color="success"
variant="flat"
block
@click="submitAnswer"
) Resolve
template(v-else)
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary 🎉 Congratulations!
v-card-text.text-center
| You have completed all reviews for today!
v-row.justify-center.mt-6
v-col(cols="6")
v-btn(
color="primary"
block
@click="quitSession"
) Back to Home
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import * as wanakana from 'wanakana'
import { nextSubject, correct, incorrect } from '../composables/srs.scoring.ts'
const route = useRoute()
const router = useRouter()
const answerInput = ref<HTMLInputElement | null>(null)
const character = ref<string>('')
const isCorrect = ref<boolean>(false)
const isDisabled = ref<boolean>(false)
const isWanakanaBound = ref<boolean>(false)
const inputMode = ref<'meaning' | 'writing' | 'kanji'>('meaning')
const resultMessage = ref<string>('')
const subject = ref<any>(null)
const allDone = ref(false)
const subjectColor = computed(() => {
if (!subject.value) return 'var(--color-all)'
switch (subject.value.type) {
case 'kanji':
return 'var(--color-kanji)'
case 'vocab':
return 'var(--color-vocab)'
default:
return 'var(--color-all)'
}
})
const options = computed(() => JSON.parse(route.query.options as string))
const optionsCalculated = ref({
subject: options.value.type === 'writing' ? 'kanji' : options.value.type === 'all' ? ['kanji', 'vocab'] : options.value.type,
mode: options.value.writing && options.value.meaning ? ['reading', 'meaning'] : options.value.writing ? 'reading' : options.value.meaning ? 'meaning' : 'reading',
writingPractice: options.value.type === 'writing',
direction: options.value.direction,
writingMode: options.value.kanji ? 'kanji' : 'kana',
})
async function createReview() {
const next = await nextSubject(optionsCalculated.value)
if (!next) {
allDone.value = true
character.value = ''
resultMessage.value = '✅ All done!'
return
}
allDone.value = false
subject.value = next
if (optionsCalculated.value.direction === 'en->jp' && optionsCalculated.value.writingMode === 'kanji')
inputMode.value = 'kanji'
else if (subject.value.mode === 'jp_en_reading' || optionsCalculated.value.direction === 'en->jp')
inputMode.value = 'writing'
else
inputMode.value = 'meaning'
character.value = subject.value.subject
isDisabled.value = false
resultMessage.value = ''
isCorrect.value = false
nextTickWrapper()
}
async function submitAnswer() {
if (!answerInput.value || !subject) return
if (isDisabled.value) {
createReview()
return
}
const userAnswer = answerInput.value.value.trim()
isCorrect.value = subject.value.answers.some(a => a.trim().toLowerCase() === userAnswer)
resultMessage.value = isCorrect.value ? 'Correct: ' : 'Wrong: '
resultMessage.value += subject.value.answers.join(', ')
if (isCorrect.value) {
await correct()
} else {
await incorrect()
}
answerInput.value.value = ''
isDisabled.value = true
}
function quitSession() {
router.push('/')
}
function handleGlobalKey(event: KeyboardEvent) {
switch (event.key) {
case 'Enter':
!isDisabled.value ? submitAnswer() : createReview()
break
}
}
function bindWanakana(input: HTMLInputElement | null) {
if (!input || isWanakanaBound.value) return
wanakana.bind(input, { IMEMode: true })
isWanakanaBound.value = true
}
function unbindWanakana(input: HTMLInputElement | null) {
if (!input || !isWanakanaBound.value) return
wanakana.unbind(input)
isWanakanaBound.value = false
}
function nextTickWrapper() {
nextTick(() => {
if (!answerInput.value) return
inputMode.value === 'writing' || inputMode.value === 'kanji'
? bindWanakana(answerInput.value)
: unbindWanakana(answerInput.value)
answerInput.value.focus()
})
}
onMounted(async () => {
createReview()
window.addEventListener('keydown', handleGlobalKey)
nextTickWrapper()
})
onBeforeUnmount(() => window.removeEventListener('keydown', handleGlobalKey))
</script>
<style lang="scss" scoped>
$dark-background: #121212;
$dark-surface: #1e1e1e;
$dark-text: #ffffff;
$dark-hint: #ffffff99;
$error-color: #cf6679;
$dark-border: #ffffff14;
$accent-color: hsl(320, 100%, 50%);
@mixin vuetify-dark-input-base {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 100%;
padding: 14px 16px;
min-height: 56px;
background-color: $dark-surface;
border: 1px solid $dark-border;
border-radius: 4px;
color: $dark-text;
font-size: 16px;
line-height: 1.5;
transition: background-color 0.2s, border-color 0.2s, box-shadow 0.2s;
&::placeholder {
color: $dark-hint;
transition: color 0.2s;
}
}
.alert-grow-enter-active,
.alert-grow-leave-active {
transition: all 0.3s ease-in-out;
overflow: hidden;
}
.alert-grow-enter-from,
.alert-grow-leave-to {
opacity: 0;
max-height: 0;
margin-bottom: 0 !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
.alert-grow-enter-to,
.alert-grow-leave-from {
opacity: 1;
max-height: 100px;
}
.customInput {
@include vuetify-dark-input-base;
&:hover {
background-color: lighten($dark-surface, 3%);
border-color: lighten($dark-border, 5%);
}
&:focus {
outline: none;
border-color: $accent-color;
box-shadow: 0 0 0 1px $accent-color;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
background-color: $dark-surface;
border-color: $dark-border;
}
&:read-only {
opacity: 0.8;
background-color: $dark-surface;
cursor: default;
border-color: $dark-border;
}
&.is-error {
border-color: $error-color !important;
box-shadow: 0 0 0 1px $error-color !important;
}
}
v-sheet,
v-card-text {
transition: background-color 0.4s ease, color 0.4s ease;
}
</style>
-250
View File
@@ -1,250 +0,0 @@
<template lang="pug">
v-container.fill-height.d-flex.justify-center.align-center.position-relative
v-btn.position-absolute.top-0.right-0.ma-4(
color="error"
variant="outlined"
@click="logoutHandler"
) Logout
v-card.pa-8.pb-6(
elevation="12"
rounded="xl"
max-width="650px"
width="100%"
)
v-card-title.text-center.text-h4.font-weight-bold.mb-4
span.text-primary SRS Trainer
v-card-text
v-row
v-col(cols="12" sm="3")
v-btn.py-6(
color="var(--color-all)"
variant="flat"
block
:disabled="!hasSelectedOptions"
@click="_startTraining('all')"
)
span.font-weight-bold All
v-col(cols="12" sm="3")
v-btn.py-6(
color="var(--color-kanji)"
variant="flat"
block
:disabled="!hasSelectedOptions"
@click="_startTraining('kanji')"
)
span.font-weight-bold Kanji
v-col(cols="12" sm="3")
v-btn.py-6(
color="var(--color-vocab)"
variant="flat"
block
:disabled="!hasSelectedOptions"
@click="_startTraining('vocab')"
)
span.font-weight-bold Vocabulary
v-col(cols="12" sm="3")
v-btn.py-6(
color="var(--color-writing)"
variant="flat"
block
:disabled="!hasSelectedOptions"
@click="_startTraining('writing')"
)
span.font-weight-bold Writing
v-row.d-flex.align-center.mb-6
v-col(cols="12" sm="6")
.text-subtitle-1.text-secondary.mb-2 Choose Direction
v-radio-group(v-model="direction" row hide-details)
v-radio(label="Japanese → English" value="jp->en" color="primary")
v-radio(label="English → Japanese" value="en->jp" color="primary")
v-radio(label="Both at random" value="both" color="primary")
v-col(cols="12" sm="6")
v-row.g-3
v-col(cols="6")
v-card.elevation-3.rounded-lg.text-center.pa-4.d-flex.flex-column.align-center.justify-center(
color="var(--color-kanji)"
variant="outlined"
height="100px"
)
v-icon.size-36.mb-2 mdi-book-open-variant
.text-subtitle-2 Kanji
.text-h6.font-weight-bold {{stats.kanjiCount}}
v-col(cols="6")
v-card.elevation-3.rounded-lg.text-center.pa-4.d-flex.flex-column.align-center.justify-center(
color="var(--color-vocab)"
variant="outlined"
height="100px"
)
v-icon.size-36.mb-2 mdi-translate
.text-subtitle-3 Vocabulary
.text-h6.font-weight-bold {{stats.vocabCount}}
v-row
v-col(cols="12")
.text-subtitle-1.text-secondary.mb-2 Training Options
v-row(row wrap)
v-col(cols="12" sm="4")
v-tooltip(text="Asked for writing. JP->EN only (本: ほん)")
template(#activator="{ props }")
v-checkbox(
v-bind="props"
v-model="options.writing"
label="Writing"
color="primary"
hide-details
)
v-col(cols="12" sm="4")
v-tooltip(text="Asked for english meaning. JP->EN only (本: Book)")
template(#activator="{ props }")
v-checkbox(
v-bind="props"
v-model="options.meaning"
label="Meaning"
color="primary"
hide-details
)
v-col(cols="12" sm="4")
v-tooltip(text="If Kanji should be written instead of kana. EN->JP only (Book: 本)")
template(#activator="{ props }")
v-checkbox(
v-bind="props"
v-model="options.kanji"
label="Write Kanji"
color="primary"
hide-details
)
v-row.d-flex.ga-4.align-center
v-col.flex-grow-1.py-0
v-text-field(
v-model="apiKey"
variant="outlined"
label="API Key"
type="password"
@keyup.enter="saveApiKey"
@click:clear="deleteApiKey"
hide-details
clearable
)
v-col.flex-shrink-0.py-0(cols="auto")
v-btn(
color="primary"
class="align-self-stretch"
variant="flat"
@click="syncWanikani"
) Sync
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
const router = useRouter()
const auth = useAuthStore()
const apiKey = ref<string>('')
const direction = ref<'en->jp' | 'jp->en' | 'both'>('jp->en')
const stats = ref<{ kanjiCount: number, vocabCount: number }>({
kanjiCount: 0,
vocabCount: 0,
})
const options = ref({
writing: true,
meaning: false,
kanji: false,
})
const hasSelectedOptions = computed(() => {
return options.value.writing || options.value.meaning
})
async function logoutHandler() {
await auth.logout()
router.push('/login')
}
function _startTraining(type: 'kanji' | 'vocab' | 'all' | 'writing') {
router.push({
path: type === 'writing' ? '/writing' : 'trainer',
query: {
direction: direction.value,
options: JSON.stringify({
direction: direction.value,
type: type,
writing: options.value.writing,
meaning: options.value.meaning,
kanji: options.value.kanji,
}),
}
})
}
async function getApiKey(): Promise<void> {
try {
const res = await fetch('/api/v1/key')
if (!res.ok) throw new Error('Failed to fetch API key')
const data: { apiKey?: string } = await res.json()
if (data.apiKey) apiKey.value = data.apiKey
} catch (error) {
console.error('Error fetching API key:', error)
}
}
async function saveApiKey(): Promise<void> {
if (!apiKey.value.trim()) return
try {
const res = await fetch('/api/v1/key', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: apiKey.value }),
})
if (!res.ok) throw new Error('Failed to update API key')
} catch (error) {
console.error('Error saving API key:', error)
}
}
async function deleteApiKey() {
try {
const res = await fetch('/api/v1/key', {
method: 'DELETE',
})
if (!res.ok) throw new Error('Failed to delete API key')
apiKey.value = ''
} catch (error) {
console.error('Error deleting API key:', error)
}
}
async function syncWanikani() {
try {
await fetch('/api/v1/wanikani/sync')
await updateStats()
} catch (error) {
console.error('Error syncing Wanikani data:', error)
}
}
import { getStatistics } from '@/composables/srs.scoring'
async function updateStats() {
const statsTemp = await getStatistics()
console.log(statsTemp)
if (!stats) return
stats.value.kanjiCount = statsTemp.totalKanji || 0
stats.value.vocabCount = statsTemp.totalVocab || 0
}
onMounted(async () => {
getApiKey()
await updateStats()
})
</script>
-62
View File
@@ -1,62 +0,0 @@
<template lang="pug">
v-container.fill-height.d-flex.justify-center.align-center
v-card.elevation-12.rounded-lg.pa-8(style="max-width: 400px; width: 100%;")
v-card-title.text-h4.text-center.font-weight-bold.mb-6 Login
v-card-text
v-form
v-text-field(
label="Username"
prepend-inner-icon="mdi-account"
v-model="username"
outlined
dense
required
)
v-text-field(
label="Password"
prepend-inner-icon="mdi-lock"
type="password"
v-model="password"
outlined
dense
required
)
v-checkbox(
label="Remember me"
class="my-4"
v-model="rememberMe"
)
v-btn(
color="primary"
large
block
@click="loginHandler"
) Login
v-card-actions.justify-center
span.text-caption Don't have an account?
v-btn.text.small( color="primary") Sign Up
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
const router = useRouter()
const auth = useAuthStore()
const username = ref('')
const password = ref('')
const rememberMe = ref(false)
async function loginHandler() {
const success = await auth.login(username.value, password.value, rememberMe.value)
if (success) router.push('/')
else console.error(auth.error)
}
onMounted(() => {
auth.fetchUser()
})
</script>
-312
View File
@@ -1,312 +0,0 @@
<template lang="pug">
v-container.fill-height.d-flex.justify-center.align-center
v-card.pa-12.rounded-lg.elevation-12
template(v-if="!allDone")
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary {{ trainerTitle }}
v-sheet.d-flex.justify-center.align-center.rounded-lg.py-8.px-4.elevation-12(
:style="{ backgroundColor: subjectColor, fontSize: '5rem', fontWeight: 'bold', whiteSpace: 'nowrap' }"
)
span {{ character }}
v-card-text.text-center.my-4.rounded-lg(
:style="{ backgroundColor: subjectColor + '20', fontSize: '1.1rem', fontWeight: '500', color: subjectColor }"
)
| {{ inputMode.charAt(0).toUpperCase() + inputMode.slice(1) }}
transition(name="alert-grow")
v-alert.mb-4(
v-if="resultMessage"
:type="isCorrect ? 'success' : 'error'"
border="top"
variant="outlined"
density="compact"
) {{ resultMessage }}
v-row.align-center
v-col(cols="9")
input#answer-input.customInput(
ref="answerInput"
placeholder="Type your answer"
:disabled="isDisabled"
)
v-col(cols="3")
v-btn(
color="primary"
block
@click="submitAnswer"
) Enter
v-row.justify-space-between
v-col(cols="4")
v-btn(
color="error"
variant="flat"
block
@click="quitSession"
) Quit
v-col(cols="4")
v-btn(
color="secondary"
variant="flat"
block
@click="createReview"
) Skip
v-col(cols="4")
v-btn(
color="success"
variant="flat"
block
@click="submitAnswer"
) Resolve
template(v-else)
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary 🎉 Congratulations!
v-card-text.text-center
| You have completed all reviews for today!
v-row.justify-center.mt-6
v-col(cols="6")
v-btn(
color="primary"
block
@click="quitSession"
) Back to Home
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import * as wanakana from 'wanakana'
import { nextSubject, correct, incorrect } from '../composables/srs.scoring.ts'
const route = useRoute()
const router = useRouter()
const answerInput = ref<HTMLInputElement | null>(null)
const character = ref<string>('')
const isCorrect = ref<boolean>(false)
const isDisabled = ref<boolean>(false)
const isWanakanaBound = ref<boolean>(false)
const inputMode = ref<'meaning' | 'writing' | 'kanji'>('meaning')
const resultMessage = ref<string>('')
const subject = ref<any>(null)
const allDone = ref(false)
const options = computed(() => JSON.parse(route.query.options as string))
const optionsCalculated = ref({
subject: options.value.type === 'writing' ? 'kanji' : options.value.type === 'all' ? ['kanji', 'vocab'] : options.value.type,
mode: options.value.writing && options.value.meaning ? ['reading', 'meaning'] : options.value.writing ? 'reading' : options.value.meaning ? 'meaning' : 'reading',
writingPractice: options.value.type === 'writing',
direction: options.value.direction,
writingMode: options.value.kanji ? 'kanji' : 'kana',
})
const trainerTitle = computed(() => {
if (!subject.value) return 'Trainer'
switch (subject.value.type) {
case 'kanji':
return 'Kanji Trainer'
case 'vocab':
return 'Vocabulary Trainer'
default:
return 'Full Trainer'
}
})
const subjectColor = computed(() => {
if (!subject.value) return 'var(--color-all)'
switch (subject.value.type) {
case 'kanji':
return 'var(--color-kanji)'
case 'vocab':
return 'var(--color-vocab)'
default:
return 'var(--color-all)'
}
})
async function createReview() {
const next = await nextSubject(optionsCalculated.value)
if (!next) {
allDone.value = true
character.value = ''
resultMessage.value = '✅ All done!'
return
}
allDone.value = false
subject.value = next
if (optionsCalculated.value.direction === 'en->jp' && optionsCalculated.value.writingMode === 'kanji')
inputMode.value = 'kanji'
else if (subject.value.mode === 'jp_en_reading' || subject.value.mode === 'en_jp_writing')
inputMode.value = 'writing'
else
inputMode.value = 'meaning'
character.value = subject.value.subject
isDisabled.value = false
resultMessage.value = ''
isCorrect.value = false
nextTickWrapper()
}
async function submitAnswer() {
if (!answerInput.value || !subject.value) return
if (isDisabled.value) {
createReview()
return
}
const userAnswer = answerInput.value.value.trim()
isCorrect.value = subject.value.answers.some(a => a.trim().toLowerCase() === userAnswer)
resultMessage.value = isCorrect.value ? 'Correct: ' : 'Wrong: '
resultMessage.value += subject.value.answers.join(', ')
if (isCorrect.value) {
await correct()
} else {
await incorrect()
}
answerInput.value.value = ''
isDisabled.value = true
}
function quitSession() {
router.push('/')
}
function handleGlobalKey(event: KeyboardEvent) {
if (event.key === 'Enter') {
!isDisabled.value ? submitAnswer() : createReview()
}
}
function bindWanakana(input: HTMLInputElement | null) {
if (!input || isWanakanaBound.value) return
wanakana.bind(input, { IMEMode: true })
isWanakanaBound.value = true
}
function unbindWanakana(input: HTMLInputElement | null) {
if (!input || !isWanakanaBound.value) return
wanakana.unbind(input)
isWanakanaBound.value = false
}
function nextTickWrapper() {
nextTick(() => {
if (!answerInput.value) return
if (inputMode.value === 'writing' || inputMode.value === 'kanji') bindWanakana(answerInput.value)
else unbindWanakana(answerInput.value)
answerInput.value.focus()
})
}
onMounted(() => {
createReview()
window.addEventListener('keydown', handleGlobalKey)
nextTickWrapper()
})
onBeforeUnmount(() => window.removeEventListener('keydown', handleGlobalKey))
</script>
<style lang="scss" scoped>
$dark-background: #121212;
$dark-surface: #1e1e1e;
$dark-text: #ffffff;
$dark-hint: #ffffff99;
$error-color: #cf6679;
$dark-border: #ffffff14;
$accent-color: hsl(320, 100%, 50%);
@mixin vuetify-dark-input-base {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 100%;
padding: 14px 16px;
min-height: 56px;
background-color: $dark-surface;
border: 1px solid $dark-border;
border-radius: 4px;
color: $dark-text;
font-size: 16px;
line-height: 1.5;
transition: background-color 0.2s, border-color 0.2s, box-shadow 0.2s;
&::placeholder {
color: $dark-hint;
transition: color 0.2s;
}
}
.alert-grow-enter-active,
.alert-grow-leave-active {
transition: all 0.3s ease-in-out;
overflow: hidden;
}
.alert-grow-enter-from,
.alert-grow-leave-to {
opacity: 0;
max-height: 0;
margin-bottom: 0 !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
.alert-grow-enter-to,
.alert-grow-leave-from {
opacity: 1;
max-height: 100px;
}
.customInput {
@include vuetify-dark-input-base;
&:hover {
background-color: lighten($dark-surface, 3%);
border-color: lighten($dark-border, 5%);
}
&:focus {
outline: none;
border-color: $accent-color;
box-shadow: 0 0 0 1px $accent-color;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
background-color: $dark-surface;
border-color: $dark-border;
}
&:read-only {
opacity: 0.8;
background-color: $dark-surface;
cursor: default;
border-color: $dark-border;
}
&.is-error {
border-color: $error-color !important;
box-shadow: 0 0 0 1px $error-color !important;
}
}
</style>
-181
View File
@@ -1,181 +0,0 @@
<template lang="pug">
v-container.fill-height.d-flex.justify-center.align-center
v-card.pa-12.rounded-lg.elevation-12
template(v-if="!allDone")
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary Handwriting Trainer
v-row.justify-center.mb-6
v-col(cols="12" class="text-center")
.text-h4.text-white.font-weight-bold
| Draw the kanji for: {{ subject?.subject || '?' }}
v-row.justify-center
v-sheet.elevation-8.justify-center(
rounded="xl"
width="280px"
height="280px"
)
canvas#kanjiCanvas(
width="280"
height="280"
:style="{borderRadius: '12px', backgroundColor: '#313131'}"
)
v-row.justify-center.my-6
v-col(cols="12" class="text-center")
.text-h5.text-white Select the kanji you drew:
v-btn-group
v-btn(
v-for="kanji in candidates"
:key="kanji"
color="var(--color-writing)"
class="mx-1 my-1"
@click="selectCandidate(kanji)"
) {{ kanji || '-' }}
transition(name="alert-grow")
v-alert.mb-4(
v-if="resultMessage"
:type="isCorrect ? 'success' : 'error'"
border="top"
variant="outlined"
density="compact"
) {{ resultMessage }}
v-row.justify-center
v-col(cols="auto" class="mx-1")
v-btn(color="error" variant="flat" block @click="quitSession") Quit
v-col(cols="auto" class="mx-1")
v-btn(color="secondary" variant="flat" block :disabled="isDisabled" @click="skipItem") Skip
v-col(cols="auto" class="mx-1")
v-btn(color="primary" variant="flat" block :disabled="isDisabled" @click="recognizeKanji") Recognize
v-col(cols="auto" class="mx-1")
v-btn(color="success" variant="flat" block :disabled="isDisabled" @click="clearCanvas") Clear
v-col(cols="auto" class="mx-1")
v-btn(color="info" variant="flat" block :disabled="!isDisabled" @click="nextItem") Next
template(v-else)
v-card-title.text-center.text-h2.font-weight-bold.mb-4
span.text-primary 🎉 Congratulations!
v-card-text.text-center
| You have completed all handwriting reviews for today!
v-row.justify-center.mt-6
v-col(cols="6")
v-btn(
color="primary"
block
@click="quitSession"
) Back to Home
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { nextSubject, correct, incorrect } from '../composables/srs.scoring.ts'
const router = useRouter()
const canvasId = 'kanjiCanvas'
const subject = ref<any>(null)
const candidates = ref<string[]>([])
const recognizedKanji = ref('')
const isCorrect = ref(false)
const resultMessage = ref('')
const isDisabled = ref(false)
const allDone = ref(false)
async function createReview() {
const options = {
subject: ['kanji'],
mode: ['meaning'], // request the meaning since we draw the kanji
direction: 'en->jp',
writingPractice: true,
}
const next = await nextSubject(options)
if (!next) {
allDone.value = true
resultMessage.value = '✅ All handwriting reviews done!'
return
}
subject.value = next
candidates.value = []
recognizedKanji.value = ''
isDisabled.value = false
resultMessage.value = ''
clearCanvas()
}
function initCanvas() {
if (window.KanjiCanvas) {
window.KanjiCanvas.init(canvasId, { strokeColor: 'white' })
} else console.error('KanjiCanvas library is not loaded.')
}
function recognizeKanji() {
if (!window.KanjiCanvas || !subject.value) return
const result = window.KanjiCanvas.recognize(canvasId).trim().split(/\s+/)
candidates.value = result.slice(0, 5)
recognizedKanji.value = candidates.value.join(', ')
}
async function selectCandidate(kanji: string) {
if (!subject.value) return
isCorrect.value = kanji === subject.value.answers[0]
resultMessage.value = isCorrect.value ? 'Correct!' : `Wrong! Answer: ${subject.value.answers[0]}`
isDisabled.value = true
if (isCorrect.value) await correct()
else await incorrect()
}
function clearCanvas() {
if (window.KanjiCanvas) {
window.KanjiCanvas.erase(canvasId)
recognizedKanji.value = ''
candidates.value = []
}
}
function quitSession() { router.push('/') }
function skipItem() { createReview() }
function nextItem() { createReview() }
onMounted(async () => {
initCanvas()
createReview()
})
onBeforeUnmount(() => {
if (window.KanjiCanvas) window.KanjiCanvas.erase(canvasId)
})
</script>
<style lang="scss" scoped>
.text-white {
color: #fff;
}
.alert-grow-enter-active,
.alert-grow-leave-active {
transition: all 0.3s ease-in-out;
overflow: hidden;
}
.alert-grow-enter-from,
.alert-grow-leave-to {
opacity: 0;
max-height: 0;
margin-bottom: 0 !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
.alert-grow-enter-to,
.alert-grow-leave-from {
opacity: 1;
max-height: 100px;
}
</style>
-20
View File
@@ -1,20 +0,0 @@
/**
* plugins/index.ts
*
* Automatically included in `./src/main.ts`
*/
// Plugins
import vuetify from './vuetify'
import pinia from '../stores'
import router from '../router'
// Types
import type { App } from 'vue'
export function registerPlugins (app: App) {
app
.use(vuetify)
.use(router)
.use(pinia)
}
-19
View File
@@ -1,19 +0,0 @@
/**
* plugins/vuetify.ts
*
* Framework documentation: https://vuetifyjs.com`
*/
// Styles
import '@mdi/font/css/materialdesignicons.css'
import 'vuetify/styles'
// Composables
import { createVuetify } from 'vuetify'
// https://vuetifyjs.com/en/introduction/why-vuetify/#feature-guides
export default createVuetify({
theme: {
defaultTheme: 'system',
},
})
-57
View File
@@ -1,57 +0,0 @@
/**
* router/index.ts
*
* Automatic routes for `./src/pages/*.vue`
*/
// Composables
import { createRouter, createWebHistory } from 'vue-router'
import { setupLayouts } from 'virtual:generated-layouts'
import { routes } from 'vue-router/auto-routes'
import { useAuthStore } from '../stores/auth.ts'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: setupLayouts(routes),
})
// Workaround for https://github.com/vitejs/vite/issues/11804
router.onError((err, to) => {
if (err?.message?.includes?.('Failed to fetch dynamically imported module')) {
if (localStorage.getItem('vuetify:dynamic-reload')) {
console.error('Dynamic import error, reloading page did not fix it', err)
} else {
console.log('Reloading page to fix dynamic import error')
localStorage.setItem('vuetify:dynamic-reload', 'true')
location.assign(to.fullPath)
}
} else {
console.error(err)
}
})
router.isReady().then(() => {
localStorage.removeItem('vuetify:dynamic-reload')
})
let hasFetchedUser = false
router.beforeEach(async (to) => {
const auth = useAuthStore()
if (to.path === '/login') return true
if (!hasFetchedUser && !auth.user && !auth.loading) {
hasFetchedUser = true
await auth.fetchUser()
}
if (!auth.isAuthenticated) {
return { path: '/login', query: { redirect: to.fullPath } }
}
return true
})
export default router
-8
View File
@@ -1,8 +0,0 @@
// Utilities
import { defineStore } from 'pinia'
export const useAppStore = defineStore('app', {
state: () => ({
//
}),
})
-168
View File
@@ -1,168 +0,0 @@
import { defineStore } from 'pinia'
import { ref, computed, onMounted, watch } from 'vue'
interface User {
id: number
username: string
email?: string
}
export const useAuthStore = defineStore('auth', () => {
const user = ref<User | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
let refreshInterval: ReturnType<typeof setInterval> | null = null
/**
* Fetch the current logged-in user from the server.
* Tries refresh if access token expired.
*/
async function fetchUser() {
try {
loading.value = true
const res = await fetch('/api/v1/user/info', {
method: 'GET',
credentials: 'include',
})
if (res.ok) {
const data = await res.json()
user.value = data.user
error.value = null
startAutoRefresh()
return true
}
if (res.status === 401) {
const refreshed = await refreshToken()
if (refreshed) return await fetchUser()
user.value = null
} else {
throw new Error('Failed to fetch user')
}
} catch (err: any) {
console.warn('fetchUser failed:', err)
error.value = err.message
user.value = null
} finally {
loading.value = false
}
}
/**
* Perform login and set cookies.
*/
async function login(username: string, password: string, remember: boolean) {
try {
loading.value = true
error.value = null
const res = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ username, password, remember }),
})
if (!res.ok) throw new Error('Invalid credentials')
const data = await res.json()
if (data.ok && data.user) {
user.value = data.user
startAutoRefresh()
return true
}
throw new Error('Login failed')
} catch (err: any) {
error.value = err.message
return false
} finally {
loading.value = false
}
}
/**
* Refresh the access token using refresh cookie.
*/
async function refreshToken() {
if (!document.cookie.includes('refresh_token')) return false
try {
const res = await fetch('/api/v1/auth/refresh', {
method: 'POST',
credentials: 'include',
})
if (res.ok) {
console.info('[Auth] Token refreshed')
return true
}
console.warn('[Auth] Token refresh failed with status', res.status)
return false
} catch (err) {
console.error('[Auth] Refresh error', err)
return false
}
}
/**
* Automatically refresh tokens before expiry.
*/
function startAutoRefresh() {
if (refreshInterval) clearInterval(refreshInterval)
refreshInterval = setInterval(async () => {
if (!user.value) return
const success = await refreshToken()
if (!success) {
console.warn('[Auth] Auto-refresh failed, trying fetchUser')
const ok = await fetchUser()
if (!ok) {
console.warn('[Auth] Session expired, logging out')
await logout()
}
}
}, 7.5 * 60 * 1000)
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible' && user.value) {
const success = await refreshToken()
if (!success) await logout()
}
})
}
/**
* Stop the refresh timer and logout from backend.
*/
async function logout() {
try {
await fetch('/api/v1/auth/logout', {
method: 'POST',
credentials: 'include',
})
} catch (err) {
console.warn('Logout error:', err)
} finally {
user.value = null
if (refreshInterval) clearInterval(refreshInterval)
refreshInterval = null
}
}
const isAuthenticated = computed(() => !!user.value)
return {
user,
loading,
error,
isAuthenticated,
login,
logout,
fetchUser,
refreshToken,
}
})
-4
View File
@@ -1,4 +0,0 @@
// Utilities
import { createPinia } from 'pinia'
export default createPinia()
-16
View File
@@ -1,16 +0,0 @@
/**
* src/styles/settings.scss
*
* Configures SASS variables and Vuetify overwrites
*/
@use 'vuetify/settings' with (
$color-pack: false
);
:root {
--color-all: hsl(360, 100%, 50%);
--color-kanji: hsl(320, 100%, 50%);
--color-vocab: hsl(280, 100%, 50%);
--color-writing: hsl(220, 100%, 50%);
}
-71
View File
@@ -1,71 +0,0 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-router. ‼️ DO NOT MODIFY THIS FILE ‼️
// It's recommended to commit this file.
// Make sure to add this file to your tsconfig.json file as an "includes" or "files" entry.
declare module 'vue-router/auto-routes' {
import type {
RouteRecordInfo,
ParamValue,
ParamValueOneOrMore,
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'vue-router'
/**
* Route name map generated by unplugin-vue-router
*/
export interface RouteNamedMap {
'/': RouteRecordInfo<'/', '/', Record<never, never>, Record<never, never>>,
'/all': RouteRecordInfo<'/all', '/all', Record<never, never>, Record<never, never>>,
'/login': RouteRecordInfo<'/login', '/login', Record<never, never>, Record<never, never>>,
'/trainer': RouteRecordInfo<'/trainer', '/trainer', Record<never, never>, Record<never, never>>,
'/writing': RouteRecordInfo<'/writing', '/writing', Record<never, never>, Record<never, never>>,
}
/**
* Route file to route info map by unplugin-vue-router.
* Used by the volar plugin to automatically type useRoute()
*
* Each key is a file path relative to the project root with 2 properties:
* - routes: union of route names of the possible routes when in this page (passed to useRoute<...>())
* - views: names of nested views (can be passed to <RouterView name="...">)
*
* @internal
*/
export interface _RouteFileInfoMap {
'src/pages/index.vue': {
routes: '/'
views: never
}
'src/pages/all.vue': {
routes: '/all'
views: never
}
'src/pages/login.vue': {
routes: '/login'
views: never
}
'src/pages/trainer.vue': {
routes: '/trainer'
views: never
}
'src/pages/writing.vue': {
routes: '/writing'
views: never
}
}
/**
* Get a union of possible route names in a certain route component file.
* Used by the volar plugin to automatically type useRoute()
*
* @internal
*/
export type _RouteNamesForFilePath<FilePath extends string> =
_RouteFileInfoMap extends Record<FilePath, infer Info>
? Info['routes']
: keyof RouteNamedMap
}
-21
View File
@@ -1,21 +0,0 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": [
"env.d.ts",
"src/**/*",
"src/**/*.vue"
],
"exclude": [
"src/**/__tests__/*"
],
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}
-19
View File
@@ -1,19 +0,0 @@
{
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*"
],
"compilerOptions": {
"composite": true,
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}
-98
View File
@@ -1,98 +0,0 @@
import { fileURLToPath, URL } from 'node:url'
import Vue from '@vitejs/plugin-vue'
// Plugins
import AutoImport from 'unplugin-auto-import/vite'
import Fonts from 'unplugin-fonts/vite'
import Components from 'unplugin-vue-components/vite'
import { VueRouterAutoImports } from 'unplugin-vue-router'
import VueRouter from 'unplugin-vue-router/vite'
// Utilities
import { defineConfig } from 'vite'
import Layouts from 'vite-plugin-vue-layouts-next'
import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
VueRouter({
dts: 'src/typed-router.d.ts',
}),
// https://github.com/posva/vite-plugin-vue-layouts
Layouts(),
AutoImport({
imports: [
'vue',
VueRouterAutoImports,
{
pinia: ['defineStore', 'storeToRefs'],
},
],
dts: 'src/auto-imports.d.ts',
eslintrc: {
enabled: true,
},
vueTemplate: true,
}),
Components({
dts: 'src/components.d.ts',
}),
Vue({
template: { transformAssetUrls },
}),
// https://github.com/vuetifyjs/vuetify-loader/tree/master/packages/vite-plugin#readme
Vuetify({
autoImport: true,
styles: {
configFile: 'src/styles/settings.scss',
},
}),
Fonts({
fontsource: {
families: [
{
name: 'Roboto',
weights: [100, 300, 400, 500, 700, 900],
styles: ['normal', 'italic'],
},
],
},
}),
],
optimizeDeps: {
exclude: [
'vuetify',
'vue-router',
'unplugin-vue-router/runtime',
'unplugin-vue-router/data-loaders',
'unplugin-vue-router/data-loaders/basic',
],
},
define: { 'process.env': {} },
resolve: {
alias: {
'@': fileURLToPath(new URL('src', import.meta.url)),
},
extensions: [
'.js',
'.json',
'.jsx',
'.mjs',
'.ts',
'.tsx',
'.vue',
],
},
server: {
proxy: {
'/api': {
target: process.env.NODE_ENV === 'DEV'
? 'http://srs-server:3000'
: 'http://192.168.0.26:3000',
changeOrigin: true,
secure: false,
},
},
allowedHosts: ['srs.crylia.de', 'localhost']
},
})
-58
View File
@@ -1,58 +0,0 @@
services:
server:
build:
context: ./server
dockerfile: Dockerfile
container_name: srs-server
restart: unless-stopped
ports:
- "3000:3000"
volumes:
- ./server:/app
- /app/node_modules
environment:
- NODE_ENV=DEV
- PORT=3000
command: pnpm run dev
networks:
- srs-app-net
env_file:
- .env
client:
build:
context: ./client
dockerfile: Dockerfile
container_name: srs-client
restart: unless-stopped
ports:
- "5173:5173"
volumes:
- ./client:/app
- /app/node_modules
environment:
- NODE_ENV=DEV
- VITE_APP_URL=http://srs-server:3000
command: pnpm run dev
depends_on:
- server
networks:
- srs-app-net
mongo:
image: mongo:8
container_name: srs-mongo
restart: unless-stopped
ports:
- "27017:27017"
volumes:
- mongo_data:/data/db
networks:
- srs-app-net
volumes:
mongo_data:
networks:
srs-app-net:
driver: bridge
-27
View File
@@ -1,27 +0,0 @@
# Node modules
node_modules
**/node_modules
# Git
.git
.gitignore
# Logs
*.log
# Local dev / editor
.vscode
.idea
# Build output
dist
build
.vite
# TypeScript build info
*.tsbuildinfo
# Environment files (if you want them injected via Docker ENV)
.env
.env.local
.env.*.local
-15
View File
@@ -1,15 +0,0 @@
FROM node:24-alpine
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /app
COPY pnpm-lock.yaml package*.json ./
RUN pnpm i
RUN pnpm add -D nodemon
COPY . .
EXPOSE 3000
CMD [ "pnpm", "run", "dev" ]
-37
View File
@@ -1,37 +0,0 @@
{
"name": "srs-server",
"type": "module",
"scripts": {
"dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
"start": "node --loader ts-node/esm src/index.ts"
},
"dependencies": {
"@fastify/cors": "^11.1.0",
"@fastify/static": "^8.2.0",
"@types/cookie-parser": "^1.4.9",
"@types/jsonwebtoken": "^9.0.10",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"express-rate-limit": "^8.1.0",
"fastify": "^5.6.1",
"helmet": "^8.1.0",
"jsonwebtoken": "^9.0.2",
"ldapts": "^8.0.9",
"mongodb": "^6.20.0",
"mongoose": "^8.19.1",
"node": "^24.10.0",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.3",
"@types/node": "^24.7.2",
"eslint": "^9.37.0",
"nodemon": "^3.1.10",
"pnpm": "^10.18.2",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
}
}
-2694
View File
File diff suppressed because it is too large Load Diff
-136
View File
@@ -1,136 +0,0 @@
import express, { type Router, type Request, type Response } from 'express'
import jwt from 'jsonwebtoken'
import { UserModel } from '../../../models/user.model.ts'
import ldapAuth from './ldap.ts'
const router = express.Router()
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET!
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET!
function createAccessToken(user: any) {
return jwt.sign(
{ sub: user._id, role: user.role },
ACCESS_TOKEN_SECRET,
{ expiresIn: '7d' },
)
}
function createRefreshToken(user: any) {
return jwt.sign(
{ sub: user._id },
REFRESH_TOKEN_SECRET,
{ expiresIn: '7d' },
)
}
router.post('/login', async (req: Request, res: Response) => {
const { username, password, remember } = req.body
if (!username || !password) return res.status(400).json({ error: 'Missing credentials' })
try {
const ldapUser = await ldapAuth({ username, password })
if (!ldapUser.auth) return res.status(401).json({ error: 'Invalid credentials' })
let user = await UserModel.findOne({ username: ldapUser.user.cn })
if (!user) {
user = await UserModel.create({
username: ldapUser.user.cn,
email: ldapUser.user.dn,
refreshToken: '',
})
}
const accessToken = createAccessToken(user)
const refreshToken = createRefreshToken(user)
user.refreshToken = refreshToken
await user.save()
res.cookie('access_token', accessToken, {
httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV !== 'dev', maxAge: 7 * 24 * 60 * 60 * 1000,
})
const refreshMaxAge = remember
? 365 * 24 * 60 * 60 * 1000
: 7 * 24 * 60 * 60 * 1000
res.cookie('refreshToken', refreshToken, {
httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV !== 'dev', maxAge: refreshMaxAge,
})
res.json({
ok: true,
user: {
username: ldapUser.user.cn,
email: ldapUser.user.dn
},
})
} catch (err) {
console.error(err)
res.status(401).json({ error: 'Invalid credentials' })
}
})
router.post('/refresh', async (req: Request, res: Response) => {
const token = req.cookies.refreshToken
if (!token) return res.status(401).json({ error: 'No refresh token' })
try {
const payload = jwt.verify(token, REFRESH_TOKEN_SECRET) as any
const user = await UserModel.findById(payload.id)
if (!user || user.refreshToken !== token)
return res.status(403).json({ error: 'Invalid refresh token' })
const newAccessToken = createAccessToken(user)
const newRefreshToken = createRefreshToken(user)
user.refreshToken = newRefreshToken
await user.save()
const existingRefreshCookie = req.cookies.refreshToken
const decodedOld = jwt.decode(existingRefreshCookie) as any
const remainingDays = (decodedOld.exp * 1000 - Date.now()) / (1000 * 60 * 60 * 24)
const refreshMaxAge = remainingDays > 7 ? 365 * 24 * 60 * 60 * 1000 : 7 * 24 * 60 * 60 * 1000
res.cookie('access_token', newAccessToken, {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV !== 'dev',
maxAge: 15 * 60 * 1000,
})
res.cookie('refreshToken', newRefreshToken, {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV !== 'dev',
maxAge: refreshMaxAge,
})
return res.json({ ok: true })
} catch (error) {
return res.status(401).json({ error: 'Invalid refresh token' })
}
})
router.post('/logout', async (req: Request, res: Response) => {
const token = req.cookies.refreshToken
if (token) {
try {
const payload = jwt.verify(token, REFRESH_TOKEN_SECRET)
const user = await UserModel.findById(payload.sub)
if (user) {
user.refreshToken = ''
await user.save()
}
} catch { }
}
res.clearCookie('access_token')
res.clearCookie('refreshToken')
res.json({ loggedOut: true })
})
export default router as Router
-31
View File
@@ -1,31 +0,0 @@
import { Client } from 'ldapts'
const LDAP_URL = 'ldap://192.168.0.26:389';
const BASE_DN = 'DC=ldap,DC=goauthentik,DC=io';
async function ldapAuth(userOptions: any) {
const { username, password } = userOptions;
if (!username || !password) return { auth: false }
const client = new Client({ url: LDAP_URL });
try {
const userDN = `cn=${username},ou=users,${BASE_DN}`;
await client.bind(userDN, password);
const { searchEntries } = await client.search(BASE_DN, {
scope: 'sub',
filter: `(cn=${username})`,
attributes: ['cn', 'mail'],
});
return { auth: true, user: searchEntries[0] }
} catch (err) {
return { auth: false }
} finally {
await client.unbind().catch(() => { })
}
}
export default ldapAuth
-63
View File
@@ -1,63 +0,0 @@
import express, { type Router, type Response } from 'express'
import { ApiKeyModel } from '../../../models/apikey.model.ts'
import { verifyAccessToken, type AuthRequest } from '../../../middleware/auth.ts'
const router = express.Router()
router.use(verifyAccessToken)
router.get('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
const doc = await ApiKeyModel.findOne({ userId: userId })
const apiKey = doc?.apiKey || ''
res.json({ apiKey })
} catch (error) {
console.error('Error fetching API key:', error)
res.status(500).json({ error: 'Failed to fetch API key' })
}
})
router.post('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const { apiKey } = req.body
if (!apiKey || !apiKey.trim()) {
return res.status(400).json({ error: 'Invalid API key' })
}
console.log(req.body)
const userId = req.userId
await ApiKeyModel.updateOne(
{},
{ $set: { userId: userId, apiKey: apiKey, lastUsed: new Date() } },
{ upsert: true },
)
res.json({ success: true })
} catch (error) {
console.error('Error saving API key:', error)
res.status(500).json({ error: 'Failed to save API key' })
}
})
router.delete('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
const result = await ApiKeyModel.deleteOne({ userId: userId })
if (result.deletedCount === 0) {
console.log('No API key found to delete.')
return res.status(204).end()
}
console.log('API key document deleted.')
res.json({ success: true, message: 'API key deleted' })
} catch (error) {
console.error('Error deleting API key:', error)
res.status(500).json({ error: 'Failed to delete API key' })
}
})
export default router as Router
-269
View File
@@ -1,269 +0,0 @@
import express, { type Router, type Response } from 'express'
import { ReviewItemModel, type ReviewItemType } from '../../../models/reviewitem.model.ts'
import { verifyAccessToken, type AuthRequest } from '../../../middleware/auth.ts'
const router = express.Router()
router.use(verifyAccessToken)
router.post('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
if (!userId) return res.status(401).json({ error: 'Unauthorized' })
const { subjectOptions } = req.body
if (!subjectOptions) return res.status(400).json({ error: 'Missing subject options' })
let typeFilter: ReviewItemType[] = ['kanji', 'vocab']
if (subjectOptions.subject) {
typeFilter = Array.isArray(subjectOptions.subject)
? subjectOptions.subject
: [subjectOptions.subject]
}
const possibleModes: { key: string; type: string }[] = []
if (subjectOptions.writingPractice) {
possibleModes.push({ key: 'writing_practice', type: 'writing_practice' })
}
const directions = Array.isArray(subjectOptions.direction)
? subjectOptions.direction
: subjectOptions.direction === 'both'
? ['jp->en', 'en->jp']
: [subjectOptions.direction]
for (const dir of directions) {
if (dir === 'jp->en') {
const modes = Array.isArray(subjectOptions.mode)
? subjectOptions.mode
: [subjectOptions.mode]
if (modes.includes('meaning')) {
possibleModes.push({ key: 'jp_en_meaning', type: 'jp_en_meaning' })
}
if (modes.includes('reading')) {
possibleModes.push({ key: 'jp_en_reading', type: 'jp_en_reading' })
}
}
if (dir === 'en->jp') {
const modes = Array.isArray(subjectOptions.mode)
? subjectOptions.mode
: [subjectOptions.mode]
if (!subjectOptions.meaning && (modes.includes('reading'))) {
possibleModes.push({ key: 'en_jp_writing', type: 'en_jp_writing' })
}
}
}
if (possibleModes.length === 0) return res.status(200).json({ message: 'No reviews due' })
const now = new Date()
const dueConditions = possibleModes.map(m => ({ [`srs.${m.key}.next_review`]: { $lte: now } }))
const dueItems = await ReviewItemModel.find({
userId,
type: { $in: typeFilter },
$or: dueConditions,
})
if (!dueItems || dueItems.length === 0) return res.status(200).json({ message: 'No reviews due' })
const nextItem = dueItems[Math.floor(Math.random() * dueItems.length)]
const dueModesForItem = possibleModes.filter(
m => nextItem.srs[m.key].next_review <= now
)
if (dueModesForItem.length === 0) {
return res.status(200).json({ message: 'No reviews due for this item' })
}
const selectedMode = dueModesForItem[Math.floor(Math.random() * dueModesForItem.length)].type
res.status(200).json({
...nextItem.toObject(),
_selectedMode: selectedMode,
})
} catch (error) {
console.error('Error fetching next review item:', error)
res.status(500).json({ error: 'Failed to fetch next review item' })
}
})
router.post('/correct', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
if (!userId) return res.status(401).json({ error: 'Unauthorized' })
const { itemId } = req.body
if (!itemId) return res.status(400).json({ error: 'Missing itemId' })
const item = await ReviewItemModel.findOne({ id: itemId, userId })
if (!item) return res.status(404).json({ error: 'Item not found' })
let key: string
if (req.body.currentSubjectOptions.writingPractice) {
key = 'srs.writing_practice'
} else if (req.body.currentSubjectOptions.direction === 'jp->en') {
key = req.body.currentSubjectOptions.mode === 'jp_en_reading' ? 'srs.jp_en_reading' : 'srs.jp_en_meaning'
} else {
key = 'srs.en_jp_writing'
}
const now = new Date()
item.set(`${key}.streak`, (item.get(`${key}.streak`) ?? 0) + 1)
item.set(`${key}.ease_factor`, Math.min(3.0, (item.get(`${key}.ease_factor`) ?? 2.5) + 0.1))
item.set(`${key}.interval`, Math.round((item.get(`${key}.interval`) ?? 1) * (item.get(`${key}.ease_factor`) ?? 2.5)))
item.set(`${key}.last_review`, now)
item.set(`${key}.next_review`, new Date(now.getTime() + (item.get(`${key}.interval`) ?? 1) * 3600 * 1000))
await item.save()
res.status(200).json({ message: 'Item marked as correct' })
} catch (error) {
console.error('Error marking item correct:', error)
res.status(500).json({ error: 'Failed to update item' })
}
})
router.post('/incorrect', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
if (!userId) return res.status(401).json({ error: 'Unauthorized' })
const { itemId } = req.body
if (!itemId) return res.status(400).json({ error: 'Missing itemId' })
const item = await ReviewItemModel.findOne({ id: itemId, userId })
if (!item) return res.status(404).json({ error: 'Item not found' })
let key: string
if (req.body.currentSubjectOptions.writingPractice) {
key = 'srs.writing_practice'
} else if (req.body.currentSubjectOptions.direction === 'jp->en') {
key = req.body.currentSubjectOptions.mode === 'reading' ? 'srs.jp_en_reading' : 'srs.jp_en_meaning'
} else {
key = 'srs.en_jp_writing'
}
const now = new Date()
item.set(`${key}.streak`, 0)
item.set(`${key}.ease_factor`, Math.max(1.3, (item.get(`${key}.ease_factor`) ?? 2.5) - 0.2))
item.set(`${key}.interval`, 1)
item.set(`${key}.last_review`, now)
item.set(`${key}.next_review`, new Date(now.getTime() + 60 * 60 * 1000)) // 1h cooldown for wrong answers
await item.save()
res.status(200).json({ message: 'Item marked as incorrect' })
} catch (error) {
console.error('Error marking item incorrect:', error)
res.status(500).json({ error: 'Failed to update item' })
}
})
router.get('/stats', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
if (!userId) return res.status(401).json({ error: 'Unauthorized' })
const now = new Date()
// Total counts
const totalKanji = await ReviewItemModel.countDocuments({ userId, type: 'kanji' })
const totalVocab = await ReviewItemModel.countDocuments({ userId, type: 'vocab' })
// Any of the SRS fields that are due
const dueConditions = [
{ 'srs.jp_en_meaning.next_review': { $lte: now } },
{ 'srs.jp_en_reading.next_review': { $lte: now } },
{ 'srs.en_jp_writing.next_review': { $lte: now } },
{ 'srs.writing_practice.next_review': { $lte: now } },
]
const dueItems = await ReviewItemModel.countDocuments({
userId,
$or: dueConditions,
})
// Waiting items = have next_review set to the future in any field
const waitingConditions = [
{ 'srs.jp_en_meaning.next_review': { $gt: now } },
{ 'srs.jp_en_reading.next_review': { $gt: now } },
{ 'srs.en_jp_writing.next_review': { $gt: now } },
{ 'srs.writing_practice.next_review': { $gt: now } },
]
const waitingItems = await ReviewItemModel.countDocuments({
userId,
$or: waitingConditions,
})
// Average SRS score per type (optional — kept from original)
const kanjiAgg = await ReviewItemModel.aggregate([
{ $match: { userId, type: 'kanji' } },
{ $group: { _id: null, avgScore: { $avg: '$srs_score' } } },
])
const vocabAgg = await ReviewItemModel.aggregate([
{ $match: { userId, type: 'vocab' } },
{ $group: { _id: null, avgScore: { $avg: '$srs_score' } } },
])
res.status(200).json({
totalKanji,
totalVocab,
dueItems,
waitingItems,
avgKanjiScore: kanjiAgg[0]?.avgScore ?? 0,
avgVocabScore: vocabAgg[0]?.avgScore ?? 0,
})
} catch (error) {
console.error('Error fetching stats:', error)
res.status(500).json({ error: 'Failed to fetch stats' })
}
})
router.get('/:itemId', verifyAccessToken, async (req: AuthRequest, res: Response) => {
try {
const userId = req.userId
if (!userId) return res.status(401).json({ error: 'Unauthorized' })
const { itemId } = req.params
if (!itemId) return res.status(400).json({ error: 'Missing itemId' })
const item = await ReviewItemModel.findOne({ _id: itemId, userId })
if (!item) return res.status(404).json({ error: 'Item not found' })
const now = new Date()
const due = item.srs_next_review && item.srs_next_review <= now
res.status(200).json({
itemId: item._id,
type: item.type,
characters: item.characters,
meanings: item.meanings,
readings: item.readings,
auxiliary_meanings: item.auxiliary_meanings,
pronunciation_audios: item.pronunciation_audios ?? [],
level: item.level,
slug: item.slug,
srs_score: item.srs_score ?? 0,
srs_streak: item.srs_streak ?? 0,
srs_ease_factor: item.srs_ease_factor ?? 2.5,
srs_last_review: item.srs_last_review,
srs_next_review: item.srs_next_review,
srs_interval: item.srs_interval ?? 1,
isDue: due,
})
} catch (error) {
console.error('Error fetching item stats:', error)
res.status(500).json({ error: 'Failed to fetch item stats' })
}
})
export default router as Router
-22
View File
@@ -1,22 +0,0 @@
import express, { type Router } from 'express'
import { UserModel } from '../../../models/user.model.ts'
import { verifyAccessToken, type AuthRequest } from '../../../middleware/auth.ts'
const router = express.Router()
router.get('/info', verifyAccessToken, async (req: AuthRequest, res) => {
try {
if (!req.userId) return res.status(401).json({ ok: false, message: 'Unauthorized' })
const user = await UserModel.findById(req.userId).select('-refreshToken -__v -createdAt -updatedAt')
if (!user) return res.status(404).json({ ok: false, message: 'User not found' })
return res.json({ ok: true, user })
} catch (err) {
console.error(err)
return res.status(500).json({ ok: false, message: 'Server error' })
}
})
export default router as Router
-27
View File
@@ -1,27 +0,0 @@
import express, { type Router, type Response } from 'express'
import { ApiKeyModel } from '../../../models/apikey.model.ts'
import { syncWanikaniData } from '../../../services/wanikaniService.ts'
import { verifyAccessToken, type AuthRequest } from '../../../middleware/auth.ts'
const router = express.Router()
router.get('/sync', verifyAccessToken, async (req: AuthRequest, res: Response) => {
if (!req.userId) return res.status(401).json({ error: 'Unauthorized' })
try {
const apiKeyDoc = await ApiKeyModel.findOne({ userId: req.userId })
const apiKey = apiKeyDoc?.apiKey
if (!apiKey || apiKey.trim() === '') {
return res.status(401).json({ error: 'API Key not configured. Please sync your key first.' })
}
await syncWanikaniData(apiKey, req.userId)
res.json({ success: true })
} catch (err) {
console.error(err)
res.status(500).json({ error: 'Failed to sync WaniKani data' })
}
})
export default router as Router
-8
View File
@@ -1,8 +0,0 @@
import mongoose from 'mongoose'
export async function connectMongo() {
const url = process.env.NODE_ENV === 'DEV' ? 'mongodb://mongo:27017/srs' : 'mongodb://192.168.0.26:27017/srs'
if (mongoose.connection.readyState === 1) return
await mongoose.connect(url)
console.log('✅ Connected to MongoDB at', url)
}
-67
View File
@@ -1,67 +0,0 @@
import dotenv from 'dotenv'
dotenv.config()
import express from 'express'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import helmet from 'helmet'
import rateLimit from 'express-rate-limit'
import { connectMongo } from './db/connect.ts'
import keyRouter from './api/v1/key/index.ts'
import syncRouter from './api/v1/wanikani/sync.ts'
import authRouter from './api/v1/auth/index.ts'
import userRoutes from './api/v1/user/index.ts'
import subjectRoutes from './api/v1/subject/index.ts'
import { verifyAccessToken } from './middleware/auth.ts'
const allowedOrigins = [
'http://localhost:5173',
'https://srs.crylia.de',
]
const app = express()
app.use(cors({
origin: (origin, callback) => {
if (!origin) return callback(null, true)
if (allowedOrigins.includes(origin)) return callback(null, true)
callback(new Error('Not allowed by CORS'))
},
credentials: true,
}))
app.use(express.json())
app.use(cookieParser())
if (process.env.NODE_ENV === 'production') {
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
connectSrc: ["'self'", "https://srs.crylia.de"],
},
},
crossOriginEmbedderPolicy: true,
crossOriginResourcePolicy: { policy: "same-origin" },
})
)
} else {
app.use(
helmet({
contentSecurityPolicy: false,
})
)
}
app.use('/api/v1/key', verifyAccessToken, keyRouter)
app.use('/api/v1/user', verifyAccessToken, userRoutes)
app.use('/api/v1/wanikani', verifyAccessToken, syncRouter)
app.use('/api/v1/auth', authRouter)
app.use('/api/v1/review', verifyAccessToken, subjectRoutes)
const PORT = process.env.PORT || 3000
connectMongo().then(() => {
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
})
-21
View File
@@ -1,21 +0,0 @@
import { type Request, type Response, type NextFunction } from 'express'
import jwt from 'jsonwebtoken'
export interface AuthRequest extends Request {
userId?: string
}
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET!
export function verifyAccessToken(req: AuthRequest, res: Response, next: NextFunction) {
const token = req.cookies.access_token
if (!token) return res.status(401).json({ ok: false, message: 'No token provided' })
try {
const payload = jwt.verify(token, ACCESS_TOKEN_SECRET!)
req.userId = (payload as any).sub
next()
} catch {
return res.status(401).json({ ok: false, message: 'Invalid token' })
}
}
-8
View File
@@ -1,8 +0,0 @@
import mongoose from 'mongoose'
const ApiKeySchema = new mongoose.Schema({
userId: { type: String, required: true },
apiKey: { type: String, required: true },
})
export const ApiKeyModel = mongoose.model('ApiKey', ApiKeySchema)
-9
View File
@@ -1,9 +0,0 @@
import mongoose from 'mongoose'
const AssignmentSchema = new mongoose.Schema({
userId: { type: String, required: true },
subject_type: String,
subject_ids: [Number],
})
export const AssignmentModel = mongoose.model('Assignment', AssignmentSchema)
-51
View File
@@ -1,51 +0,0 @@
import mongoose from 'mongoose'
export type ReviewItemType = 'kanji' | 'vocab'
const ReviewItemSchema = new mongoose.Schema({
userId: { type: String, required: true },
type: { type: String, enum: ['kanji', 'vocab'], required: true },
id: { type: Number, required: true },
characters: String,
meanings: Array,
readings: { type: Array, default: [] },
auxiliary_meanings: Array,
level: Number,
slug: String,
pronunciation_audios: { type: Array, default: [] },
srs: {
jp_en_meaning: {
streak: { type: Number, default: 0 },
ease_factor: { type: Number, default: 2.5 },
interval: { type: Number, default: 1 },
next_review: { type: Date, default: () => new Date() },
last_review: { type: Date, default: null },
},
jp_en_reading: {
streak: { type: Number, default: 0 },
ease_factor: { type: Number, default: 2.5 },
interval: { type: Number, default: 1 },
next_review: { type: Date, default: () => new Date() },
last_review: { type: Date, default: null },
},
en_jp_writing: {
streak: { type: Number, default: 0 },
ease_factor: { type: Number, default: 2.5 },
interval: { type: Number, default: 1 },
next_review: { type: Date, default: () => new Date() },
last_review: { type: Date, default: null },
},
writing_practice: {
streak: { type: Number, default: 0 },
ease_factor: { type: Number, default: 2.5 },
interval: { type: Number, default: 1 },
next_review: { type: Date, default: () => new Date() },
last_review: { type: Date, default: null },
},
},
})
export const ReviewItemModel = mongoose.model('ReviewItem', ReviewItemSchema)
-9
View File
@@ -1,9 +0,0 @@
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
email: { type: String, unique: true },
refreshToken: String,
}, { timestamps: true })
export const UserModel = mongoose.model('User', UserSchema)
-168
View File
@@ -1,168 +0,0 @@
import { ApiKeyModel } from '../models/apikey.model.ts'
import { AssignmentModel } from '../models/assignments.model.ts'
import { ReviewItemModel } from '../models/reviewitem.model.ts'
import type { KanjiItem, VocabularyItem } from '../types/wanikani.ts'
const WANIKANI_API_BASE = 'https://api.wanikani.com/v2'
export interface WaniKaniSubject {
id: number
object: string
data: {
characters: string
meanings: { meaning: string; primary: boolean; accepted_answers: boolean }[]
readings: { type: string; primary: boolean; accepted_answer: boolean; reading: string }[]
auxiliary_meanings: { meaning: string; type: string }[]
pronunciation_audios?: {
url: string
content_type: string
metadata: { gender: string; pronunciation: string }[]
}[]
level: number
slug: string
unlocked_at?: string
subject_type: 'kanji' | 'vocabulary' | 'kana_vocabulary'
}
}
const fetchAllPages = async (
url: string,
headers: Record<string, string>,
): Promise<WaniKaniSubject[]> => {
let results: WaniKaniSubject[] = []
let nextUrl: string | null = url
while (nextUrl) {
const res = await fetch(nextUrl, { headers })
if (!res.ok) throw new Error(`Failed fetching ${url}: ${res.statusText}`)
const json = (await res.json()) as { data: WaniKaniSubject[]; pages: { next_url: string | null } }
results = results.concat(json.data)
nextUrl = json.pages.next_url
}
return results
}
const fetchSubjects = async (
ids: number[],
headers: Record<string, string>,
): Promise<WaniKaniSubject[]> => {
const chunkSize = 1000
let results: WaniKaniSubject[] = []
for (let i = 0; i < ids.length; i += chunkSize) {
const chunk = ids.slice(i, i + chunkSize)
const res = await fetch(`${WANIKANI_API_BASE}/subjects?ids=${chunk.join(',')}`, { headers })
if (!res.ok) throw new Error(`Failed fetching subjects: ${res.statusText}`)
const json = (await res.json()) as { data: WaniKaniSubject[] }
results = results.concat(json.data)
}
return results
}
const mapToReviewItem = (item: WaniKaniSubject, userId: string) => {
let type: 'kanji' | 'vocab'
const subjectType = item.data.subject_type || item.object
if (subjectType === 'kanji') type = 'kanji'
else if (['vocabulary', 'kana_vocabulary'].includes(subjectType)) type = 'vocab'
else throw new Error(`Unknown WaniKani subject type: ${subjectType}`)
return {
id: item.id,
userId,
type,
characters: item.data.characters,
meanings: item.data.meanings,
readings: item.data.readings ?? [],
auxiliary_meanings: item.data.auxiliary_meanings ?? [],
pronunciation_audios: item.data.pronunciation_audios ?? [],
level: item.data.level,
slug: item.data.slug,
srs: {
jp_en_meaning: {
streak: 0,
ease_factor: 2.5,
interval: 1,
next_review: new Date(),
last_review: null,
},
jp_en_reading: {
streak: 0,
ease_factor: 2.5,
interval: 1,
next_review: new Date(),
last_review: null,
},
en_jp_writing: {
streak: 0,
ease_factor: 2.5,
interval: 1,
next_review: new Date(),
last_review: null,
},
writing_practice: {
streak: 0,
ease_factor: 2.5,
interval: 1,
next_review: new Date(),
last_review: null,
},
},
}
}
export const syncWanikaniData = async (apiKey: string, userId: string): Promise<void> => {
const headers = { Authorization: `Bearer ${apiKey}` }
try {
await ApiKeyModel.updateOne(
{},
{ $set: { userId: userId, apiKey: apiKey, lastUsed: new Date() } },
{ upsert: true },
)
const assignments = await fetchAllPages(`${WANIKANI_API_BASE}/assignments`, headers)
const unlockedKanjiIds: number[] = []
const unlockedVocabIds: number[] = []
for (const a of assignments) {
const assignmentData = a.data as any
if (!assignmentData.unlocked_at) continue
if (assignmentData.subject_type === 'kanji') unlockedKanjiIds.push(assignmentData.subject_id)
else if (['vocabulary', 'kana_vocabulary'].includes(assignmentData.subject_type)) unlockedVocabIds.push(assignmentData.subject_id)
}
await AssignmentModel.updateOne(
{ userId, subject_type: 'kanji' },
{ $set: { subject_ids: unlockedKanjiIds } },
{ upsert: true },
)
await AssignmentModel.updateOne(
{ userId, subject_type: 'vocab' },
{ $set: { subject_ids: unlockedVocabIds } },
{ upsert: true },
)
// Fetch and insert new review items
const kanjiSubjects = await fetchSubjects(unlockedKanjiIds, headers)
const vocabSubjects = await fetchSubjects(unlockedVocabIds, headers)
const allSlugs = new Set((await ReviewItemModel.find({ userId }, { slug: 1 })).map(r => r.slug))
const newItems = [...kanjiSubjects, ...vocabSubjects]
.filter(s => !allSlugs.has(s.data.slug))
.map(s => mapToReviewItem(s, userId))
if (newItems.length > 0) await ReviewItemModel.insertMany(newItems)
console.log('✅ WaniKani sync complete')
} catch (err) {
console.error('❌ Error syncing WaniKani data:', err)
throw err
}
}
-60
View File
@@ -1,60 +0,0 @@
export interface KanjiItem {
userId: string
characters: string
meanings: {
meaning: string,
primary: boolean,
accepted_answers: boolean
}[]
readings: {
type: string
primary: boolean
accepted_answer: boolean
reading: string
}[]
auxiliary_meanings: {
meaning: string
type: string
}[]
level: number
slug: string
srs_score: number
}
export interface VocabularyItem {
userId: string
characters: string
meanings: {
meaning: string
primary: boolean
accepted_answers: boolean
}[]
readings: {
type: string
primary: boolean
accepted_answer: boolean
reading: string
}[]
auxiliary_meanings: {
meaning: string
type: string
}[]
pronunciation_audios: {
url: string
content_type: string
metadata: {
gender: string
pronunciation: string
}[]
}[]
level: number
slug: string
srs_score: number
}
export interface Assignment {
userId: string
unlocked_at?: Date
subject_ids: number[]
subject_type: string
}
-46
View File
@@ -1,46 +0,0 @@
{
// Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": {
// File Layout
"rootDir": "./src",
"outDir": "./dist",
// Environment Settings
// See also https://aka.ms/tsconfig/module
"module": "nodenext",
"target": "esnext",
"types": [],
// For nodejs:
// "lib": ["esnext"],
// "types": ["node"],
// and npm install -D @types/node
// Other Outputs
"sourceMap": true,
"declaration": true,
"declarationMap": true,
// Stricter Typechecking Options
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
// Style Options
// "noImplicitReturns": true,
// "noImplicitOverride": true,
// "noUnusedLocals": true,
// "noUnusedParameters": true,
// "noFallthroughCasesInSwitch": true,
// "noPropertyAccessFromIndexSignature": true,
// Recommended Options
"strict": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true,
"noEmit": true,
"allowImportingTsExtensions": true,
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}