Compare commits

..

50 Commits

Author SHA1 Message Date
dade012888 Merge pull request 'hotfix/payload-banner' (#28) from hotfix/payload-banner into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #28
2026-03-25 17:57:49 +07:00
4001aec6ef ♻️ refactor: refine payload before sending to frontend
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 47s
2026-03-25 17:55:48 +07:00
dd70f9f9d4 ♻️ refactor: restructure banner select payload 2026-03-25 17:49:16 +07:00
26909154ab Merge pull request 'prune-banner' (#27) from prune-banner into main
All checks were successful
Sync to GitHub / sync (push) Successful in 9s
Reviewed-on: #27
2026-03-25 12:52:55 +07:00
7f6b1373f4 💥 breaking: update endpoint to support new banner schema
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 1m42s
2026-03-25 12:39:23 +07:00
794a130562 feat: add cache flush module 2026-03-25 11:37:06 +07:00
6599fa8f79 🗃️ db: reset prisma migrations for updated banner structure 2026-03-17 16:41:29 +07:00
27b66e6d34 🗃️ db: update schema to match new banner logic 2026-03-16 22:45:13 +07:00
1c097aac69 Merge pull request 'refactor' (#26) from refactor into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #26
2026-03-11 10:12:24 +07:00
b5a0c2eda6 🚨 fix: resolve linting type error
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 33s
2026-03-11 10:11:09 +07:00
864a919680 📝 docs: complete documentation for auth module
Some checks failed
Integration Tests / integration-tests (pull_request) Failing after 42s
2026-03-11 10:07:33 +07:00
da74f5e3e1 📦 chore: snapshot commit before major changes 2026-03-11 09:24:25 +07:00
dc350d006b 📝 docs: add schema documentation to OAuth provider routes 2026-03-10 12:00:00 +07:00
97dc26ed82 👔 feat: add schema for token verification module 2026-03-09 12:00:00 +07:00
d767a0434c Merge pull request 'refactor' (#25) from refactor into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #25
2026-03-08 15:02:28 +07:00
43af43b0a3 📝 docs: finish controller documentation for internal module
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 51s
2026-03-08 14:59:27 +07:00
232ea986cb 🚨 fix: resolve linting type error 2026-03-08 14:53:26 +07:00
595a79de34 ♻️ refactor: add schema to all controllers in internal module 2026-03-08 14:50:54 +07:00
9f47f8f298 ♻️ refactor: align update-thumbnail and bulk-insert-video with latest Elysia standards 2026-03-08 07:31:38 +07:00
5a4e4d04a4 ♻️ refactor: align bulk-insert implementation with latest Elysia standards 2026-03-07 14:57:16 +07:00
0b786206e4 💥 breaking: upgrade Elysia to v1.4 and update codebase accordingly 2026-03-07 13:41:13 +07:00
c992314cf1 Merge pull request 'docs' (#24) from docs into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #24
2026-03-07 08:54:33 +07:00
d61b4f1d55 🚨 fix: resolve linting type error
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 32s
2026-03-07 08:53:45 +07:00
5d0d933758 📝 docs: add API endpoints and license documentation
Some checks failed
Integration Tests / integration-tests (pull_request) Failing after 51s
2026-03-07 08:50:39 +07:00
cb2c51f161 ⚗️ experiment: try OpenAPI metadata configuration 2026-03-06 23:06:48 +07:00
9a554bb2ec 📝 docs: add OpenAPI for API documentation 2026-03-06 21:56:50 +07:00
0383150109 🎨 style: fix documentation layout issues 2026-03-05 21:54:37 +07:00
37c6e30f7a 📝 docs: add project structure and getting started guide 2026-03-05 21:51:14 +07:00
4cb9b911a8 📝 docs: add architecture documentation 2026-03-05 18:43:47 +07:00
cb2475cff1 📝 docs: add overview section to README 2026-03-05 17:48:35 +07:00
b593299f60 Merge pull request ' perf: cache banners with Redis' (#23) from perf into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #23
2026-03-05 16:46:15 +07:00
afcd2348e0 perf: cache banners with Redis
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 1m3s
2026-03-05 16:42:08 +07:00
ebc143dc74 Merge pull request 'fix/hero-banner' (#22) from fix/hero-banner into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #22
2026-03-03 21:59:03 +07:00
5a7f9bbebe perf: use Redis for faster system preference check
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 52s
2026-03-03 21:49:32 +07:00
02ad14d382 feat: add helper to detect system preference 2026-03-03 21:47:07 +07:00
a6b2c77bd1 👔 feat: add option to disable banner 2026-03-03 21:25:59 +07:00
d858e54fe8 feat: add tags to banner 2026-03-03 16:56:58 +07:00
ae0830cbe7 Merge pull request 'feat/hero-banner' (#21) from feat/hero-banner into main
All checks were successful
Sync to GitHub / sync (push) Successful in 13s
Reviewed-on: #21
2026-03-02 23:24:20 +07:00
01ad69a4b0 👔 feat: add banner priority ordering logic
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 1m48s
2026-03-02 23:07:30 +07:00
6ffa087e91 feat: add endpoint to get active banners 2026-03-02 22:32:05 +07:00
960493f414 feat: add internal endpoint to create banner 2026-03-02 22:09:33 +07:00
90655dcf92 🚚 chore: rename hero banner table in schema 2026-03-01 12:28:16 +07:00
815e24158a 🗃️ db: update hero banner schema 2026-03-01 12:22:23 +07:00
3a4bcfd360 Merge pull request 'fix/thumbnail-code' (#20) from fix/thumbnail-code into main
All checks were successful
Sync to GitHub / sync (push) Successful in 8s
Reviewed-on: #20
2026-02-22 11:10:08 +07:00
a4d24c785c 🔧 chore: fix build error
All checks were successful
Integration Tests / integration-tests (pull_request) Successful in 30s
2026-02-22 11:04:52 +07:00
482103c78a 🚨 fix: resolve linting type error
Some checks failed
Integration Tests / integration-tests (pull_request) Failing after 29s
2026-02-22 11:00:50 +07:00
21a06f3b9e 👔 feat: add bulk thumbnail update logic
Some checks failed
Integration Tests / integration-tests (pull_request) Failing after 42s
2026-02-22 10:55:02 +07:00
2a3467a737 👔 feat: add logic to replace placeholder with thumbnail code 2026-02-21 20:52:10 +07:00
46d7dc8da8 feat: add service to fetch all videos from videoService 2026-02-21 20:46:25 +07:00
1038ad068f 🗑️ chore: remove repository from service 2026-02-21 19:53:17 +07:00
76 changed files with 2816 additions and 666 deletions

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"parser": "typescript",
"printWidth": 120
}

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 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.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
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.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
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.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
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.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
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.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
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.
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.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
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.
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.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
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:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
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".
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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

201
README.md
View File

@ -1,15 +1,204 @@
# Elysia with Bun runtime
<div align="center">
<img src="https://i.ibb.co.com/HfrLhRDc/Group-15.png" width="360" />
<h4>A simple anime streaming platform with community feature integration</h4>
</div>
## Overview
Syzne TV was born from a simple frustration: watching anime online shouldnt feel like fighting through layers of intrusive ads and popups. Many platforms today prioritize aggressive monetization over user experience, and somewhere along the way, the joy of watching got lost.
## Tech Stack
- **Runtime**: Bun (v1.3)
- **Framework**: Elysia (latest)
- **Database**: PostgreSQL 18
- **ORM**: Prisma (v7.0)
- **Caching**: Redis (v8.4)
- **Authentication**: JWT
- **Monitoring**: Sentry
## Getting Started
To get started with this template, simply paste this command into your terminal:
> ⚠️ Docker support is planned but not fully implemented yet.
> Full containerized deployment will be finalized once the backend reaches production readiness.
> For now, please follow the manual setup below.
#### 1⃣ Clone the repository
```bash
bun create elysia ./elysia-example
git clone https://github.com/rafiarrafif/SyzneTV-backend.git
cd SyzneTV-backend
```
## Development
To start the development server run:
#### 2⃣ Prepare Environment Variables
Copy the example environment file:
```bash
cp .env.example .env
```
Then configure .env properly:
- Database credentials
- Redis configuration
- SMTP configuration
- Admin account credentials
- Any other required environment variables
> ⚠️ Make sure all required variables are filled correctly.
> The application will fail to start if any critical configuration is missing.
#### 3⃣ Install Dependencies
```bash
bun install
```
#### 4⃣ Run Database Migrations
```bash
bunx prisma deploy
```
#### 5⃣ Seed Initial Data
```bash
bun run prisma:seed
```
#### 6⃣ Run the Application
**Development Mode**
```bash
bun run dev
```
Open http://localhost:3000/ with your browser to see the result.
**Production Mode**
Build the application:
```bash
bun run build
```
Make the binary executable:
```bash
chmod +x ./dist/server
```
Run the server:
```bash
./dist/server
```
## Project Structure
```
root/
├── prisma/
│ ├── dbml/ # DBML schema generated from Prisma
│ ├── migrations/ # Database migration history
│ └── seed/ # Database seeding scripts
│ └── (run with: bun run prisma:seed)
├── scripts/ # Automation & maintenance scripts (⚠️ do not modify unless necessary)
└── src/
├── config/ # Non-secret system configuration
│ # ⚠️ Never store secrets here — use .env instead
├── constants/ # Editable system keys (e.g., cookie names, Redis keys)
├── helpers/ # Reusable helper functions (cross-module usage)
├── middleware/ # All application middlewares
├── modules/ # Domain-based modules (auth, user, media, etc.)
├── utils/ # External service utilities
│ # (database, bucket storage, SMTP, etc.)
├── route.ts # Root route aggregator (registers all modules)
└── index.ts # Application entry point
```
This structure keeps the core system separated from domain logic, automation tools, and infrastructure-related utilities. Making the project easier to scale, debug, and maintain over time.
## Architecture Overview
Syzne TV uses a modular architecture to keep the codebase clean, scalable, and easy to maintain.
Each feature is separated by domain (e.g., `auth`, `user`, `media`) and stored inside:
```
./src/modules
```
Every module follows the same internal structure:
```
module-name/
├── controllers/
├── services/
├── repositories/
├── validations/
├── types.ts
└── index.ts
```
#### Folder Responsibilities
- **Controllers**: Handle incoming HTTP requests and responses. Every file must end with: `*.controller.ts`
- **Services**: Contain the core business logic. Every file must end with: `*.service.ts`
- **Repositories**: Interact with the database using Prisma. Every file must end with: `*.repository.ts`
- **Validations**: Define request validation schemas using Zod. Every file must end with: `*.schema.ts`
- **types.ts**: Contains module-specific TypeScript types.
- **index.ts**: Defines the module routes and route prefix (e.g., `/auth`).
> **IMPORTANT** Whenever you create a new module and configure its routes, you must run:
```bash
bun run route:sync
```
This command registers the module route into the root route automatically. This structure ensures consistency across the project and makes it easier to scale without turning the codebase into a mess.
## API Endpoints
Due to the large number of routes and their complexity, listing every endpoint directly in this README would quickly become messy and hard to maintain.
Instead, we provides an OpenAPI-based documentation page that can be accessed at:
```
/openapi
```
#### Accessing the OpenAPI Documentation
Before accessing the documentation, you need to temporarily disable the application protector.
Open your .env file and change:
```env
ENABLED_APP_TOKEN=false
```
After that, start the server and open the /openapi route in your browser.
#### Current Status
The OpenAPI documentation is still in an early stage and may look a bit rough at the moment. It will be improved and structured more clearly as the project evolves.
For now, it serves as a reference for exploring available routes and understanding how the API is structured.
## License
This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0).
You are free to use, modify, and distribute this project under the terms of the license. However, if you run a modified version of this software as a service, you must also make the source code available under the same license.
For the full license text, please see the [LICENSE](LICENSE) file in this repository.

430
bun.lock

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
{
"name": "mvp.nounoz.com_v2",
"name": "backend-syzne-tv",
"version": "1.0.50",
"license": "AGPL-3.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "bun build ./src/index.ts --compile --target bun --minify-whitespace --minify-syntax --minify-identifiers --outfile dist/server",
@ -19,6 +20,7 @@
"env:publish": "bun run ./scripts/create-example-env.ts"
},
"dependencies": {
"@elysiajs/openapi": "^1.4.14",
"@prisma/adapter-pg": "^7.2.0",
"@prisma/client": "^7.2.0",
"@sentry/node": "^10.10.0",
@ -29,7 +31,7 @@
"aws-sdk": "^2.1692.0",
"bcrypt": "^5.1.1",
"cookie": "^1.1.1",
"elysia": "latest",
"elysia": "^1.4.27",
"ioredis": "^5.6.1",
"joi": "^17.13.3",
"jsonwebtoken": "^9.0.2",
@ -49,6 +51,7 @@
"cz-emoji": "^1.3.2-canary.2",
"eslint": "^9.29.0",
"globals": "^16.2.0",
"prettier": "^3.8.1",
"prisma": "^7.2.0",
"prisma-dbml-generator": "^0.12.0",
"typescript-eslint": "^8.34.1"

View File

@ -28,6 +28,7 @@ Table medias {
deletedAt DateTime
createdAt DateTime [default: `now()`, not null]
updatedAt DateTime [default: `now()`, not null]
bannerPromotion hero_banner [not null]
logs media_logs [not null]
episodes episodes [not null]
collections collections [not null]
@ -257,6 +258,7 @@ Table users {
create_languages languages [not null]
user_create_email email_system_accounts [not null]
user_emails email_system_histories [not null]
user_hero_banner hero_banner [not null]
sys_notifications system_notifications [not null]
sys_logs system_logs [not null]
}
@ -492,9 +494,23 @@ Table email_system_histories {
updatedAt DateTime [default: `now()`, not null]
}
Table hero_banner {
id String [pk]
orderPriority Int [unique]
mediaId String [not null]
media medias [not null]
imageUrl String
startDate DateTime [not null]
endDate DateTime [not null]
createdAt DateTime [default: `now()`, not null]
updatedAt DateTime [default: `now()`, not null]
creatorId String [not null]
createdBy users [not null]
}
Table system_preferences {
id String [pk]
key String [not null]
key String [unique, not null]
value String [not null]
description String [not null]
deletedAt DateTime
@ -761,6 +777,10 @@ Ref: email_system_accounts.createdBy > users.id
Ref: email_system_histories.userRelated > users.id
Ref: hero_banner.mediaId > medias.id
Ref: hero_banner.creatorId > users.id
Ref: system_notifications.createdBy > users.id
Ref: system_logs.relatedUser > users.id

View File

@ -206,7 +206,8 @@ CREATE TABLE "videos" (
"id" UUID NOT NULL,
"episodeId" UUID NOT NULL,
"serviceId" UUID NOT NULL,
"code" VARCHAR(255) NOT NULL,
"videoCode" VARCHAR(255) NOT NULL,
"thumbnailCode" TEXT,
"pendingUpload" BOOLEAN NOT NULL DEFAULT true,
"uploadedBy" UUID NOT NULL,
"deletedAt" TIMESTAMP(3),
@ -497,6 +498,26 @@ CREATE TABLE "email_system_histories" (
CONSTRAINT "email_system_histories_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "hero_banner" (
"id" UUID NOT NULL,
"orderPriority" INTEGER,
"isClickable" BOOLEAN NOT NULL DEFAULT false,
"title" VARCHAR(225),
"tags" TEXT[],
"description" TEXT,
"buttonContent" VARCHAR(100),
"buttonLink" TEXT,
"imageUrl" TEXT,
"startDate" TIMESTAMP(3) NOT NULL,
"endDate" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"creatorId" UUID NOT NULL,
CONSTRAINT "hero_banner_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "system_preferences" (
"id" UUID NOT NULL,
@ -629,7 +650,7 @@ CREATE UNIQUE INDEX "lang_va_char_language_vaId_charId_key" ON "lang_va_char"("l
CREATE UNIQUE INDEX "episodes_mediaId_episode_key" ON "episodes"("mediaId", "episode");
-- CreateIndex
CREATE UNIQUE INDEX "videos_serviceId_code_key" ON "videos"("serviceId", "code");
CREATE UNIQUE INDEX "videos_serviceId_videoCode_key" ON "videos"("serviceId", "videoCode");
-- CreateIndex
CREATE UNIQUE INDEX "video_services_name_key" ON "video_services"("name");
@ -664,6 +685,12 @@ CREATE UNIQUE INDEX "email_system_accounts_email_key" ON "email_system_accounts"
-- CreateIndex
CREATE UNIQUE INDEX "email_system_accounts_username_key" ON "email_system_accounts"("username");
-- CreateIndex
CREATE UNIQUE INDEX "hero_banner_orderPriority_key" ON "hero_banner"("orderPriority");
-- CreateIndex
CREATE UNIQUE INDEX "system_preferences_key_key" ON "system_preferences"("key");
-- CreateIndex
CREATE INDEX "_MediaStudios_B_index" ON "_MediaStudios"("B");
@ -820,6 +847,9 @@ ALTER TABLE "email_system_accounts" ADD CONSTRAINT "email_system_accounts_create
-- AddForeignKey
ALTER TABLE "email_system_histories" ADD CONSTRAINT "email_system_histories_userRelated_fkey" FOREIGN KEY ("userRelated") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "hero_banner" ADD CONSTRAINT "hero_banner_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "system_notifications" ADD CONSTRAINT "system_notifications_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -1,17 +0,0 @@
/*
Warnings:
- You are about to drop the column `code` on the `videos` table. All the data in the column will be lost.
- A unique constraint covering the columns `[serviceId,videoCode]` on the table `videos` will be added. If there are existing duplicate values, this will fail.
- Added the required column `videoCode` to the `videos` table without a default value. This is not possible if the table is not empty.
*/
-- DropIndex
DROP INDEX "videos_serviceId_code_key";
-- AlterTable
ALTER TABLE "videos" RENAME COLUMN "code" TO "videoCode";
-- CreateIndex
DROP INDEX IF EXISTS "videos_serviceId_code_key";
CREATE UNIQUE INDEX "videos_serviceId_videoCode_key" ON "videos"("serviceId", "videoCode");

View File

@ -1,2 +0,0 @@
-- AlterTable
ALTER TABLE "videos" ADD COLUMN "thumbnailCode" TEXT;

View File

@ -0,0 +1,23 @@
/*
Warnings:
- You are about to drop the column `buttonContent` on the `hero_banner` table. All the data in the column will be lost.
- You are about to drop the column `buttonLink` on the `hero_banner` table. All the data in the column will be lost.
- You are about to drop the column `description` on the `hero_banner` table. All the data in the column will be lost.
- You are about to drop the column `isClickable` on the `hero_banner` table. All the data in the column will be lost.
- You are about to drop the column `tags` on the `hero_banner` table. All the data in the column will be lost.
- You are about to drop the column `title` on the `hero_banner` table. All the data in the column will be lost.
- Added the required column `mediaId` to the `hero_banner` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "hero_banner" DROP COLUMN "buttonContent",
DROP COLUMN "buttonLink",
DROP COLUMN "description",
DROP COLUMN "isClickable",
DROP COLUMN "tags",
DROP COLUMN "title",
ADD COLUMN "mediaId" UUID NOT NULL;
-- AddForeignKey
ALTER TABLE "hero_banner" ADD CONSTRAINT "hero_banner_mediaId_fkey" FOREIGN KEY ("mediaId") REFERENCES "medias"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -49,6 +49,7 @@ model Media {
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
bannerPromotion HeroBanner[] @relation("MediaBannerPromotion")
logs MediaLog[] @relation("MediaLogs")
episodes Episode[] @relation("MediaEpisodes")
collections Collection[] @relation("MediaCollections")
@ -296,6 +297,7 @@ model User {
create_languages Language[] @relation("UserCreateLanguages")
user_create_email EmailSystemAccount[] @relation("UserCreateSystemAccount")
user_emails EmailSystemHistory[] @relation("UserEmails")
user_hero_banner HeroBanner[] @relation("UserHeroBanner")
sys_notifications SystemNotification[] @relation("UserCreatorSystemNotifications")
sys_logs SystemLog[] @relation("UserSystemLogs")
@@map("users")
@ -553,9 +555,24 @@ model EmailSystemHistory {
@@map("email_system_histories")
}
model HeroBanner {
id String @id @db.Uuid
orderPriority Int? @unique
mediaId String @db.Uuid
media Media @relation("MediaBannerPromotion", fields: [mediaId], references: [id])
imageUrl String? @db.Text
startDate DateTime
endDate DateTime
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
creatorId String @db.Uuid
createdBy User @relation("UserHeroBanner", fields: [creatorId], references: [id])
@@map("hero_banner")
}
model SystemPreference {
id String @id @db.Uuid
key String @db.VarChar(225)
key String @db.VarChar(225) @unique
value String @db.VarChar(225)
description String @db.Text
deletedAt DateTime?

View File

@ -1,4 +1,5 @@
import { prisma } from "../../src/utils/databases/prisma/connection";
import { systemPreferenceSeed } from "./systemPreference.seed";
import { userRoleSeed } from "./userRole.seed";
import { userSystemSeed } from "./userSystem.seed";
@ -8,6 +9,7 @@ async function main() {
const userSystemSeedResult = await userSystemSeed();
await userRoleSeed(userSystemSeedResult.id);
await systemPreferenceSeed();
console.log("🌳 All seeds completed");
}

View File

@ -0,0 +1,35 @@
import { Prisma } from "@prisma/client";
import { generateUUIDv7 } from "../../src/helpers/databases/uuidv7";
import { prisma } from "../../src/utils/databases/prisma/connection";
export const systemPreferenceSeed = async () => {
const preferences: Prisma.SystemPreferenceUpsertArgs["create"][] = [
{
id: generateUUIDv7(),
key: "REGISTRATION_ENABLED",
value: process.env.ENABLE_REGISTRATION === "true" ? "true" : "false",
description: "Enable or disable user registration",
},
{
id: generateUUIDv7(),
key: "HERO_BANNER_ENABLED",
value: process.env.ENABLE_HERO_BANNER === "true" ? "true" : "false",
description: "Enable or disable hero banner feature",
},
];
await prisma.$transaction(async (tx) => {
return await Promise.all(
preferences.map(
async (pref) =>
await tx.systemPreference.upsert({
where: {
key: pref.key,
},
update: pref,
create: pref,
}),
),
);
});
};

View File

@ -0,0 +1,18 @@
import { ElysiaOpenAPIConfig } from "@elysiajs/openapi";
export const openAPIConfig: ElysiaOpenAPIConfig = {
documentation: {
info: {
title: "TV Nounoz API",
description: "API documentation for TV Nounoz backend services",
version: "1.0.0",
},
tags: [
{
name: "Internal",
description:
"Endpoints for internal use, such as administrative tasks and data management operations. These endpoints may require authentication and are not intended for public use.",
},
],
},
};

7
src/config/redis/key.ts Normal file
View File

@ -0,0 +1,7 @@
export const redisKey = [
{
name: "HERO_BANNER",
description: "Key for caching active hero banner data",
key: `${process.env.APP_NAME}:system:banner`,
},
];

View File

@ -1,4 +1,3 @@
import { Context } from "elysia";
import { UserHeaderInformation } from "./types";
export interface ClientInfoHeader {
@ -10,25 +9,14 @@ export interface ClientInfoHeader {
ip: string;
}
export const getUserHeaderInformation = (
ctx: Context,
): UserHeaderInformation => {
const clientInfoHeader =
(JSON.parse(
ctx.request.headers.get("x-client-info") as string,
) as ClientInfoHeader) ?? ("unknown" as string);
export const getUserHeaderInformation = (clientInfo: string): UserHeaderInformation => {
const clientInfoHeader = (JSON.parse(clientInfo) as ClientInfoHeader) ?? ("unknown" as string);
const userHeaderInformation = {
ip: clientInfoHeader.ip ?? "unknown",
deviceType: clientInfoHeader.deviceType ?? "unknown",
deviceOS:
(clientInfoHeader.os ?? "unknown") +
" " +
(clientInfoHeader.osVersion ?? "unknown"),
browser:
(clientInfoHeader.browser ?? "unknown") +
" " +
(clientInfoHeader.browserVersion ?? "unknown"),
deviceOS: (clientInfoHeader.os ?? "unknown") + " " + (clientInfoHeader.osVersion ?? "unknown"),
browser: (clientInfoHeader.browser ?? "unknown") + " " + (clientInfoHeader.browserVersion ?? "unknown"),
};
return userHeaderInformation;

View File

@ -0,0 +1,21 @@
import { type RouteSchema } from "elysia";
import type { OpenAPIV3 } from "openapi-types";
export type AppRouteSchema = RouteSchema & {
detail?: Partial<{
tags?: string[];
summary?: string;
description?: string;
externalDocs?: OpenAPIV3.ExternalDocumentationObject;
operationId?: string;
parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
responses: OpenAPIV3.ResponsesObject;
callbacks?: {
[callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
};
deprecated?: boolean;
security?: OpenAPIV3.SecurityRequirementObject[];
servers?: OpenAPIV3.ServerObject[];
}>;
};

View File

@ -1,7 +1,9 @@
/* eslint-disable @typescript-eslint/no-require-imports */
import openapi from "@elysiajs/openapi";
import { middleware } from "./middleware";
import { validateEnv } from "./utils/startups/validateEnv";
import { openAPIConfig } from "./config/documentation/openAPI";
validateEnv();
@ -17,6 +19,7 @@ async function bootstrap() {
new Elysia()
.use(middleware)
.use(routes)
.use(openapi(openAPIConfig))
.listen(process.env.APP_PORT || 3000);
console.log(

View File

@ -3,6 +3,7 @@ import { returnErrorResponse } from "../../helpers/callback/httpResponse";
export const appAccessTokenMiddleware = () =>
new Elysia().onRequest(({ request, set }) => {
if (process.env.APP_ENV !== "development") {
const headerToken = request.headers.get("authorization");
if (!headerToken) return returnErrorResponse(set, 401, "Unauthorized");
@ -13,4 +14,5 @@ export const appAccessTokenMiddleware = () =>
return returnErrorResponse(set, 401, "Invalid auth format");
if (token !== storedToken)
return returnErrorResponse(set, 403, "Forbidden");
}
});

View File

@ -9,8 +9,8 @@ export const getOauthProvidersController = (ctx: Context) => {
return returnReadResponse(
ctx.set,
200,
"Getting all oauth available list",
oauthProviderServices
"Successfully retrieved the list of oauth providers",
oauthProviderServices,
);
} catch (error) {
return mainErrorHandler(ctx.set, error);

View File

@ -1,14 +1,17 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { githubCallbackService } from "../services/http/githubCallback.service";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
import { githubCallbackSchema } from "../schemas/githubCallback.schema";
export const githubCallbackController = async (
ctx: Context & { query: { code: string; callbackURI: string } }
) => {
export const githubCallbackController = async (ctx: {
set: Context["set"];
query: Static<typeof githubCallbackSchema.query>;
headers: Static<typeof githubCallbackSchema.headers>;
}) => {
try {
const userHeaderInfo = getUserHeaderInformation(ctx);
const userHeaderInfo = getUserHeaderInformation(ctx.headers["x-client-info"]);
const authToken = await githubCallbackService(ctx.query, userHeaderInfo);
return returnWriteResponse(ctx.set, 200, "Authenticated successfully!", {

View File

@ -1,21 +1,18 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { returnReadResponse } from "../../../helpers/callback/httpResponse";
import { githubRequestService } from "../services/http/githubRequest.service";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { githubRequestSchema } from "../schemas/githubRequest.schema";
export const githubRequestController = async (
ctx: Context & { query: { callback?: string } },
) => {
export const githubRequestController = async (ctx: {
set: Context["set"];
query: Static<typeof githubRequestSchema.query>;
}) => {
try {
const loginUrl = await githubRequestService(ctx.query.callback);
return returnReadResponse(
ctx.set,
200,
"Login URL generated successfully",
{
return returnReadResponse(ctx.set, 200, "GitHub login URL created successfully.", {
endpointUrl: loginUrl,
},
);
});
} catch (error) {
return mainErrorHandler(ctx.set, error);
}

View File

@ -1,17 +1,20 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { returnReadResponse } from "../../../helpers/callback/httpResponse";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { googleCallbackService } from "../services/http/googleCallback.service";
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
import { googleCallbackSchema } from "../schemas/googleCallback.schema";
export const googleCallbackController = async (
ctx: Context & { query: { code: string; state: string; callbackURI: string } }
) => {
export const googleCallbackController = async (ctx: {
set: Context["set"];
query: Static<typeof googleCallbackSchema.query>;
headers: Static<typeof googleCallbackSchema.headers>;
}) => {
try {
const userHeaderInfo = getUserHeaderInformation(ctx);
const userHeaderInfo = getUserHeaderInformation(ctx.headers["x-client-info"]);
const authToken = await googleCallbackService(ctx.query, userHeaderInfo);
return returnReadResponse(ctx.set, 200, "Authenticated successfully!", {
return returnReadResponse(ctx.set, 200, "Authentication successful!", {
authToken,
});
} catch (error) {

View File

@ -1,14 +1,16 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { googleRequestService } from "../services/http/googleRequest.service";
import { returnReadResponse } from "../../../helpers/callback/httpResponse";
import { googleRequestSchema } from "../schemas/googleRequest.schema";
export const googleRequestController = async (
ctx: Context & { query: { callback?: string } }
) => {
export const googleRequestController = async (ctx: {
set: Context["set"];
query: Static<typeof googleRequestSchema.query>;
}) => {
try {
const loginUrl = await googleRequestService(ctx.query.callback);
return returnReadResponse(ctx.set, 200, "Google login url created!", {
return returnReadResponse(ctx.set, 200, "Google login URL created successfully.", {
endpointUrl: loginUrl,
});
} catch (error) {

View File

@ -7,13 +7,21 @@ import { getOauthProvidersController } from "./controllers/getOauthProviders.con
import { getCallbackProviderUrlController } from "./controllers/getCallbackProviderUrl.controller";
import { tokenValidationController } from "./controllers/tokenValidation.controller";
import { logoutController } from "./controllers/logout.controller";
import { tokenValidationSchema } from "./schemas/tokenValidation.schema";
import { getOauthProvidersSchema } from "./schemas/getOauthProviders.schema";
import { getCallbackProviderUrlSchema } from "./schemas/getCallbackProviderUrl.schema";
import { googleRequestSchema } from "./schemas/googleRequest.schema";
import { googleCallbackSchema } from "./schemas/googleCallback.schema";
import { githubRequestSchema } from "./schemas/githubRequest.schema";
import { githubCallbackSchema } from "./schemas/githubCallback.schema";
import { logoutSchema } from "./schemas/logout.schema";
export const authModule = new Elysia({ prefix: "/auth" })
.post("/token/validate", tokenValidationController)
.get("/providers", getOauthProvidersController)
.get("/providers/:name/callback", getCallbackProviderUrlController)
.get("/github", githubRequestController)
.get("/github/callback", githubCallbackController)
.get("/google", googleRequestController)
.get("/google/callback", googleCallbackController)
.post("/logout", logoutController);
export const authModule = new Elysia({ prefix: "/auth", tags: ["Authentication"] })
.post("/token/validate", tokenValidationController, tokenValidationSchema)
.get("/providers", getOauthProvidersController, getOauthProvidersSchema)
.get("/providers/:name/callback", getCallbackProviderUrlController, getCallbackProviderUrlSchema)
.get("/google", googleRequestController, googleRequestSchema)
.get("/google/callback", googleCallbackController, googleCallbackSchema)
.get("/github", githubRequestController, githubRequestSchema)
.get("/github/callback", githubCallbackController, githubCallbackSchema)
.post("/logout", logoutController, logoutSchema);

View File

@ -0,0 +1,45 @@
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const getCallbackProviderUrlSchema = {
detail: {
summary: "Get the callback URL of oauth provider",
description:
"After users have successfully completed the authentication process on the OAuth provider page, they will be redirected to the callback page on the frontend. This endpoint aims to obtain the actual endpoint for each OAuth response handler.",
responses: {
200: {
description: "The callback URL on the provider has been found.",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
default: true,
},
status: {
type: "number",
default: 200,
},
message: {
type: "string",
default: "The callback URL on the provider has been found.",
},
data: {
type: "object",
properties: {
callback_url: {
type: "string",
description: "The callback URL on the provider.",
example: "auth/google/callback",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,55 @@
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const getOauthProvidersSchema = {
detail: {
summary: "Get all available oauth providers",
description:
"This endpoint returns a list of all available and active oauth providers that can be used for authentication.",
responses: {
200: {
description: "Successfully retrieved the list of oauth providers",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
example: true,
},
status: {
type: "number",
example: 200,
},
message: {
type: "string",
example: "Successfully retrieved the list of oauth providers",
},
data: {
type: "array",
items: {
type: "object",
properties: {
name: {
type: "string",
example: "google",
},
icon: {
type: "string",
example: "logos:google-icon",
},
req_endpoint: {
type: "string",
example: "auth/google",
},
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,57 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const githubCallbackSchema = {
headers: t.Object({
"x-client-info": t.String({
examples: [
'{"os":"Windows","osVersion":"10","browser":"Chrome","browserVersion":"89.0.4389.82","deviceType":"Desktop","ip":"192.168.1.1"}',
],
}),
}),
query: t.Object({
code: t.String({ examples: ["4/0AY0e-xxxxxxxxx"] }),
callbackURI: t.String({ examples: ["https://example.com/auth/github/callback"] }),
}),
detail: {
summary: "GitHub OAuth callback endpoint",
description:
"Handles the callback from GitHub OAuth and processes the authentication response. This endpoint also processes the account provisioning if the user is logging in for the first time.",
responses: {
200: {
description: "Authentication successful",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
example: true,
},
status: {
type: "number",
example: 200,
},
message: {
type: "string",
example: "Authentication successful",
},
data: {
type: "object",
properties: {
authToken: {
type: "string",
description: "JWT token for authenticated user",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,54 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const githubRequestSchema = {
query: t.Object({
callback: t.Optional(
t.String({
description: "The callback URL to redirect after GitHub authentication. It should be URL-encoded if provided.",
}),
),
}),
detail: {
summary: "Initiate GitHub OAuth flow",
description:
"This endpoint initiates the GitHub OAuth flow by redirecting the user to GitHub's authentication page.",
responses: {
200: {
description: "GitHub login URL created successfully.",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
default: true,
},
status: {
type: "number",
default: 200,
},
message: {
type: "string",
default: "GitHub login URL created successfully.",
},
data: {
type: "object",
properties: {
endpointUrl: {
type: "string",
description: "The URL to redirect the user for GitHub authentication.",
example:
"https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=user:email",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,58 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const googleCallbackSchema = {
headers: t.Object({
"x-client-info": t.String({
examples: [
'{"os":"Windows","osVersion":"10","browser":"Chrome","browserVersion":"89.0.4389.82","deviceType":"Desktop","ip":"192.168.1.1"}',
],
}),
}),
query: t.Object({
code: t.String({ examples: ["4/0AY0e-xxxxxxxxx"] }),
state: t.String({ examples: ["random_state_string"] }),
callbackURI: t.String({ examples: ["https://example.com/auth/google/callback"] }),
}),
detail: {
summary: "Google OAuth callback endpoint",
description:
"Handles the callback from Google OAuth and processes the authentication response. This endpoint also processes the account provisioning if the user is logging in for the first time.",
responses: {
200: {
description: "Authentication successful",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
example: true,
},
status: {
type: "number",
example: 200,
},
message: {
type: "string",
example: "Authentication successful",
},
data: {
type: "object",
properties: {
authToken: {
type: "string",
description: "JWT token for authenticated user",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,54 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const googleRequestSchema = {
query: t.Object({
callback: t.Optional(
t.String({
description: "The callback URL to redirect after Google authentication. It should be URL-encoded if provided.",
}),
),
}),
detail: {
summary: "Initiate Google OAuth flow",
description:
"This endpoint initiates the Google OAuth flow by redirecting the user to Google's authentication page.",
responses: {
200: {
description: "Google login URL created successfully.",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
default: true,
},
status: {
type: "number",
default: 200,
},
message: {
type: "string",
default: "Google login URL created successfully.",
},
data: {
type: "object",
properties: {
endpointUrl: {
type: "string",
description: "The URL to redirect the user for Google authentication.",
example:
"https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=email%20profile",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,97 @@
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const logoutSchema = {
detail: {
summary: "Logout endpoint",
description: "Logs out the authenticated user by invalidating their session or token.",
responses: {
200: {
description: "Logout successful",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: {
type: "boolean",
example: true,
},
status: {
type: "number",
example: 200,
},
message: {
type: "string",
example: "Logout successful",
},
data: {
type: "object",
description: "Details about the logout operation. This only returned in development environment.",
properties: {
id: {
type: "string",
example: "123e4567-e89b-12d3-a456-426614174000",
},
isAuthenticated: {
type: "boolean",
example: false,
},
validUntil: {
type: "string",
format: "date-time",
example: "2024-12-31T23:59:59Z",
},
userId: {
type: "string",
example: "user_12345",
},
deletedAt: {
type: "string",
format: "date-time",
example: "2024-01-02T12:00:00Z",
},
createdAt: {
type: "string",
format: "date-time",
example: "2024-01-01T12:00:00Z",
},
updatedAt: {
type: "string",
format: "date-time",
example: "2024-01-02T12:00:00Z",
},
deviceType: {
type: "string",
example: "Desktop",
},
deviceOs: {
type: "string",
example: "Windows 10",
},
deviceIp: {
type: "string",
example: "192.168.1.1",
},
browser: {
type: "string",
example: "Chrome 89.0.4389.82",
},
isOnline: {
type: "boolean",
example: false,
},
lastOnline: {
type: "string",
format: "date-time",
example: "2024-01-02T12:00:00Z",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,108 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const tokenValidationSchema = {
headers: t.Object({
cookie: t.String({ description: "Authentication token in cookie format, e.g., auth_token=your_jwt_token;" }),
}),
detail: {
summary: "Validate authentication JWT token",
description:
"Validates the provided authentication JWT token with checking its validity and expiration in redis cache, if not exists, it will be checked in the database. If the token is valid, it returns the user information associated with the token. if the token is invalid or expired, it returns an error message.",
responses: {
200: {
description: "Validation successful",
content: {
"application/json": {
schema: {
type: "object",
properties: {
id: { type: "string", description: "Session ID", default: "xxxx-xxxxx-xxxxx-xxxx" },
isAuthenticated: {
type: "boolean",
description: "Indicates if the token is valid and the user is authenticated",
default: true,
},
validUntil: {
type: "string",
format: "date-time",
description: "Expiration date and time of the token",
default: "2024-12-31T23:59:59Z",
},
user: {
type: "object",
properties: {
id: { type: "string", description: "User ID", default: "user-12345" },
name: { type: "string", description: "User's full name", default: "Lena Nouzen" },
email: {
type: "string",
format: "email",
description: "User's email address",
default: "lena@example.com",
},
username: { type: "string", description: "User's username", default: "vladilena" },
avatar: {
type: "string",
format: "uri",
description: "URL to the user's avatar image",
default: "https://example.com/avatar.jpg",
},
birthDate: {
type: "string",
format: "date",
description: "User's birth date, can be null if not provided",
default: null,
},
bioProfile: {
type: "string",
description: "User's bio/profile description, can be null if not provided",
default: null,
},
preference: {
type: "object",
properties: {
id: { type: "string", description: "Preference ID", default: "pref-12345" },
userId: { type: "string", description: "Associated User ID", default: "user-12345" },
langPreference: {
type: "string",
description: "User's language preference, can be null if not provided",
default: null,
},
adultFiltering: {
type: "string",
description: "User's adult content filtering setting",
default: "strict",
},
adultAlert: {
type: "string",
description: "User's adult content alert setting",
default: "enabled",
},
videoQuality: {
type: "string",
description: "User's preferred video quality setting",
default: "1080p",
},
serviceDefaultId: {
type: "string",
description: "Default service ID for the user, can be null if not provided",
default: null,
},
hideContries: {
type: "array",
items: { type: "string" },
description: "List of country codes that the user has chosen to hide content from",
default: ["US", "CN"],
},
},
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -1,34 +0,0 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { episodeModel } from "../../episode.model";
export const getAllEpisodeWithThumbnailLinkRepository = async (
serviceReferenceId: string,
) => {
try {
return await episodeModel.findMany({
where: {
deletedAt: null,
},
select: {
id: true,
episode: true,
videos: {
where: {
deletedAt: null,
serviceId: serviceReferenceId,
},
select: {
code: true,
service: {
select: {
endpointThumbnail: true,
},
},
},
},
},
});
} catch (error) {
throw new AppError(500, "Failed to get all episode thumbnails", error);
}
};

View File

@ -0,0 +1,30 @@
import { Prisma } from "@prisma/client";
import { AppError } from "../../../../helpers/error/instances/app";
import { prisma } from "../../../../utils/databases/prisma/connection";
export const bulkUpdateThumbnailRepository = async (
data: { episodeId: string; thumbnailCode: string }[],
) => {
try {
const values = Prisma.join(
data.map(
(item) => Prisma.sql`(${item.episodeId}::uuid, ${item.thumbnailCode})`,
),
);
await prisma.$executeRaw`
UPDATE episodes e
SET "pictureThumbnail" = v."thumbnailCode"
FROM (
VALUES ${values}
) AS v("episodeId", "thumbnailCode")
WHERE e.id = v."episodeId"
`;
} catch (error) {
throw new AppError(
500,
"An error occurred while bulk updating episode thumbnails.",
error,
);
}
};

View File

@ -1,18 +0,0 @@
import { Prisma } from "@prisma/client";
import { AppError } from "../../../../helpers/error/instances/app";
import { episodeModel } from "../../episode.model";
export const updateEpisodeRepository = async (
payload: Prisma.EpisodeUncheckedUpdateInput,
) => {
try {
return await episodeModel.update({
where: {
id: payload.id as string,
},
data: payload,
});
} catch (error) {
throw new AppError(500, "Failed to edit episode", error);
}
};

View File

@ -0,0 +1,8 @@
import { Context } from "elysia";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { clearHeroBannerService } from "../services/clearHeroBanner.service";
export const clearHeroBannerController = async (ctx: { set: Context["set"] }) => {
const cacheCleared = await clearHeroBannerService();
return returnWriteResponse(ctx.set, 200, "Hero banner cache flushed successfully", cacheCleared);
};

View File

@ -0,0 +1,4 @@
import Elysia from "elysia";
import { clearHeroBannerController } from "./controllers/clearHeroBanner.controller";
export const flushCacheModule = new Elysia({ prefix: "/flush-cache" }).put("/hero-banner", clearHeroBannerController);

View File

@ -0,0 +1,12 @@
import { redisKey } from "../../../config/redis/key";
import { AppError } from "../../../helpers/error/instances/app";
import { redis } from "../../../utils/databases/redis/connection";
export const clearHeroBannerService = async () => {
try {
const cache = await redis.del(redisKey.find((key) => key.name === "HERO_BANNER")?.key || "");
return cache > 0; // Returns true if cache was cleared, false if it was not found
} catch (error) {
throw new AppError(500, "Failed to clear hero banner cache", error);
}
};

View File

@ -0,0 +1,18 @@
import { Context } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { returnReadResponse } from "../../../helpers/callback/httpResponse";
import { getActiveHeroBannerService } from "../services/getActiveHeroBanner.service";
export const getActiveHeroBannerController = async (ctx: Context) => {
try {
const response = await getActiveHeroBannerService();
return returnReadResponse(
ctx.set,
200,
"Active hero banners fetched successfully",
response,
);
} catch (error) {
return mainErrorHandler(ctx.set, error);
}
};

View File

@ -0,0 +1,7 @@
import Elysia from "elysia";
import { getActiveHeroBannerController } from "./controllers/getActiveHeroBanner.controller";
export const heroBannerModule = new Elysia({ prefix: "/hero-banner" }).get(
"/",
getActiveHeroBannerController,
);

View File

@ -0,0 +1,46 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { prisma } from "../../../../utils/databases/prisma/connection";
export const findAllActiveHeroBannerRepository = async () => {
try {
return await prisma.heroBanner.findMany({
where: {
startDate: {
lte: new Date(),
},
endDate: {
gte: new Date(),
},
},
orderBy: [
{
orderPriority: "asc",
},
{
startDate: "asc",
},
],
select: {
orderPriority: true,
imageUrl: true,
media: {
select: {
id: true,
title: true,
slug: true,
pictureLarge: true,
synopsis: true,
genres: {
select: {
slug: true,
name: true,
},
},
},
},
},
});
} catch (error) {
throw new AppError(500, "Failed to fetch active hero banners", error);
}
};

View File

@ -0,0 +1,39 @@
import { redisKey } from "../../../config/redis/key";
import { AppError } from "../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { redis } from "../../../utils/databases/redis/connection";
import { findSystemPreferenceService } from "../../systemPreference/services/internal/findSystemPreference.service";
import { findAllActiveHeroBannerRepository } from "../repositories/GET/findAllActiveHeroBanner.repository";
export const getActiveHeroBannerService = async () => {
try {
// Check if Hero Banner is enabled in system preferences
const isHeroBannerEnabled = await findSystemPreferenceService("HERO_BANNER_ENABLED", "boolean");
if (!isHeroBannerEnabled) throw new AppError(403, "Hero Banner is disabled");
// Try to get active banners from Redis cache
const cachedBanners = await redis.get(`${redisKey.filter((key) => key.name === "HERO_BANNER")[0].key}`);
if (cachedBanners) return JSON.parse(cachedBanners);
// If not in cache, fetch from database and cache the result
const activeBanners = await findAllActiveHeroBannerRepository();
const constructedBanners = activeBanners.map((banner) => ({
id: banner.media.id,
title: banner.media.title,
slug: banner.media.slug,
imageUrl: banner.imageUrl || banner.media.pictureLarge,
synopsis: banner.media.synopsis,
genres: banner.media.genres.map((genre) => ({
slug: genre.slug,
name: genre.name,
})),
}));
await redis.set(
`${redisKey.filter((key) => key.name === "HERO_BANNER")[0].key}`,
JSON.stringify(constructedBanners),
);
return constructedBanners;
} catch (error) {
ErrorForwarder(error);
}
};

View File

@ -1,62 +1,23 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { bulkInsertEpisodeService } from "../services/http/bulkInsertEpisode.service";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { bulkInsertEpisodeSchema } from "../schemas/bulkInsertEpisode.schema";
/**
* @function bulkInsertMediaController
* @description Perform bulk insert of episodes for a specific media. This operation fetches episode data from external sources and inserts them into the database. The page parameter is optional; if not provided, the first page of episodes will be fetched.
* Perform bulk insert of episodes for a specific media.
* This operation fetches episode data from external sources and inserts them into the database.
*
* @param {Context & { body: { media_mal_id: number }; query: { page?: number } }} ctx
* The context object containing the request body.
* The body must include:
* - media_mal_id: number - The MyAnimeList ID of the media for which episodes will be inserted.
* The query may include:
* - page?: number - (Optional) The page number of episodes to fetch and insert. If not provided, defaults to the first page.
*
* @example
* Request route: POST /internal/episode/bulk-insert
* Request body:
* {
* "media_mal_id": 12345
* }
* Query parameter:
* ?page=2 (Optional, specifies the page number of episodes to fetch and insert)
*
* @returns {Promise<Object>}
* A response object indicating success or failure.
* Return example:
* {
* success: true,
* status: 201,
* message: "Bulk insert episode operation completed successfully",
* data: { ...bulkInsertResult } // Data returned only if the env run on development mode
* }
*
* @throws {Object}
* An error response object if validation fails or an error occurs during bulk insert operation.
* Return example:
* {
* success: false,
* status: <Status Code>,
* message: "<Error Message>",
* error: { ...errorDetails } // Additional error details if available and the env run on development mode
* }
* See OpenAPI documentation for request/response schema.
*/
export const bulkInsertEpisodeController = async (
ctx: Context & { body: { media_mal_id: number }; query: { page?: number } },
) => {
export const bulkInsertEpisodeController = async (ctx: {
set: Context["set"];
body: Static<typeof bulkInsertEpisodeSchema.body>;
query: Static<typeof bulkInsertEpisodeSchema.query>;
}) => {
try {
const bulkInsertResult = await bulkInsertEpisodeService(
ctx.body.media_mal_id,
ctx.query.page,
);
return returnWriteResponse(
ctx.set,
201,
"Bulk insert episode operation completed successfully",
bulkInsertResult,
);
const bulkInsertResult = await bulkInsertEpisodeService(ctx.body.media_mal_id, ctx.query.page);
return returnWriteResponse(ctx.set, 201, "Bulk insert episode operation completed successfully", bulkInsertResult);
} catch (err) {
return mainErrorHandler(ctx.set, err);
}

View File

@ -1,47 +1,21 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { bulkInsertAnimeService } from "../services/http/bulkInsertAnime.service";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { bulkInsertMediaSchema } from "../schemas/bulkInsertMedia.schema";
/**
* @function bulkInsertMediaController
* @description Insert new anime to the database only with mal_id. This operation including inserting related data such as genres, studios, producers, licensors, themes, demographics, and relations.
* Insert anime and its related data into the database using MAL ID.
*
* @param {Context & { body: { mal_id: number } }} ctx
* The context object containing the request body.
* The body must include:
* - mal_id: number - The MyAnimeList ID of the anime to be inserted.
* This controller orchestrates the bulk insertion process including
* genres, studios, producers, licensors, themes, voice actors, and relations.
*
* @example
* Request route: POST /internal/anime/bulk-insert
* Request body:
* {
* "mal_id": 12345
* }
*
* @returns {Promise<Object>}
* A response object indicating success or failure.
* Return example:
* {
* success: true,
* status: 201,
* message: "Bulk insert anime operation completed successfully",
* data: { ...bulkInsertResult } // Data returned only if the env run on development mode
* }
*
* @throws {Object}
* An error response object if validation fails or an error occurs during bulk insert operation.
* Return example:
* {
* success: false,
* status: <Status Code>,
* message: "<Error Message>",
* error: { ...errorDetails } // Additional error details if available and the env run on development mode
* }
* See OpenAPI documentation for request/response schema.
*/
export const bulkInsertMediaController = async (
ctx: Context & { body: { mal_id: number } },
) => {
export const bulkInsertMediaController = async (ctx: {
set: Context["set"];
body: Static<typeof bulkInsertMediaSchema.body>;
}) => {
try {
const bulkInsertResult = await bulkInsertAnimeService(ctx.body.mal_id);
return returnWriteResponse(

View File

@ -1,87 +1,24 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { bulkInsertVideoService } from "../services/http/bulkInsertVideo.service";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
export interface BulkInsertVideoBodyRequest {
media_id: string;
data: Array<{
episode: number;
videos: Array<{
service_id: string;
video_code: string;
thumbnail_code?: string;
}>;
}>;
}
import { bulkInsertVideoSchema } from "../schemas/bulkInsertVideo.schema";
/**
* @function bulkInsertVideoController
* @description Perform bulk insert of videos for specific episodes of a media. This operation inserts multiple videos associated with different episodes into the database based on the provided data.
* Bulk insert videos into the database.
*
* @param {Context & { body: BulkInsertVideoBodyRequest }} ctx
* The context object containing the request body.
* The body must include:
* - media_id: string - The ID of the media for which episodes will be inserted.
* - data: Array - An array of episode data, each containing:
* - episode: number - The episode number.
* - videos: Array - An array of video data for the episode, each containing:
* - service_id: string - The ID of the video service.
* - code: string - The code of the video on the service.
* This controller handles the bulk insertion of videos by accepting an array of video data in the request body,
* invoking the service to perform the insertion, and returning a response with the inserted video details.
*
* @example
* Request route: POST /internal/video/bulk-insert
* Request body:
* {
* "media_id": "019c064e-a03d-7cc3-b2ae-5d6850ea456b",
* "data": [
* {
* "episode": 1,
* "videos": [
* {
* "service_id": "019c0df6-f8fe-7565-82cd-9c29b20232ab",
* "code": "fzwu9n8ge2qt"
* }
* ]
* },
* {
* "episode": 2,
* "videos": [
* {
* "service_id": "019c0df6-f8fe-7565-82cd-9c29b20232ab",
* "code": "w2maywh53rt8"
* }
* ]
* }
* ]
* },
*
* @returns {Promise<Object>}
* A response object indicating success or failure.
* Return example:
* {
* success: true,
* status: 201,
* message: "Videos inserted",
* data: { ...insertedVideos } // Data returned only if the env run on development mode
* }
*
* @throws {Object}
* An error response object if validation fails or an error occurs during bulk insert operation.
* Return example:
* {
* success: false,
* status: <Status Code>,
* message: "<Error Message>",
* error: { ...errorDetails } // Additional error details if available and the env run on development mode
* }
* See OpenAPI documentation for request/response schema.
*/
export const bulkInsertVideoController = async (
ctx: Context & { body: BulkInsertVideoBodyRequest },
) => {
export const bulkInsertVideoController = async (ctx: {
set: Context["set"];
body: Static<typeof bulkInsertVideoSchema.body>;
}) => {
try {
const insertedVideos = await bulkInsertVideoService(ctx.body);
return returnWriteResponse(ctx.set, 201, "Videos inserted", insertedVideos);
return returnWriteResponse(ctx.set, 201, "Videos inserted successfully", insertedVideos);
} catch (error) {
throw mainErrorHandler(ctx.set, error);
}

View File

@ -0,0 +1,26 @@
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { createHeroBannerService } from "../services/http/createHeroBanner.service";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { createHeroBannerSchema } from "../schemas/createHeroBanner.schema";
/**
* Create a new hero banner.
*
* This controller handles the creation of a hero banner by accepting the necessary
* data in the request body, invoking the service to create the banner, and returning
* an created payload response.
*
* See OpenAPI documentation for request/response schema.
*/
export const createHeroBannerController = async (ctx: {
set: Context["set"];
body: Static<typeof createHeroBannerSchema.body>;
}) => {
try {
const createdBanner = await createHeroBannerService(ctx.body);
return returnWriteResponse(ctx.set, 201, "Hero banner created successfully", createdBanner);
} catch (error) {
return mainErrorHandler(ctx.set, error);
}
};

View File

@ -1,79 +1,26 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { createVideoServiceInternalService } from "../services/http/createVideoService.service";
export interface CreateVideoServiceInternalBodyRequest {
name: string;
domain: string;
logo: string;
hexColor: string;
endpointVideo: string;
endpointThumbnail: string;
endpointDownload?: string;
}
import { createVideoServiceInternalSchema } from "../schemas/createVideoServiceInternal.schema";
/**
* @function createVideoServiceInternalController
* @description Perform creation of a new video service. This operation adds a new video service to the database based on the provided data.
* Controller for creating a new video service.
*
* @param {Context & { body: CreateVideoServiceInternalBodyRequest }} ctx
* The context object containing the request body.
* The body must include:
* - name: string - The name of the video service.
* - domain: string - The domain of the video service.
* - logo: string - The logo URL of the video service.
* - hexColor: string - The hex color associated with the video service.
* - endpointVideo: string - The endpoint URL for video streaming.
* - endpointThumbnail: string - The endpoint URL for thumbnails.
* - endpointDownload?: string - (Optional) The endpoint URL for downloads.
* This controller handles the HTTP request for creating a new video service.
* It validates the incoming request body against the defined schema,
* invokes the service layer to perform the creation logic,
* and returns an appropriate HTTP response based on the outcome of the operation.
*
* @example
* Request route: POST /internal/video-service
* Request body:
* {
* "name": "Example Video Service",
* "domain": "example.com",
* "logo": "https://example.com/logo.png",
* "hexColor": "#FF5733",
* "endpointVideo": "https://api.example.com/videos",
* "endpointThumbnail": "https://api.example.com/thumbnails",
* "endpointDownload": "https://api.example.com/downloads"
* },
*
* @returns {Promise<Object>}
* A response object indicating success or failure.
* Return example:
* {
* success: true,
* status: 201,
* message: "Video service created",
* data: { ...createdVideoService } // Data returned only if the env run on development mode
* }
*
* @throws {Object}
* An error response object if validation fails or an error occurs during bulk insert operation.
* Return example:
* {
* success: false,
* status: <Status Code>,
* message: "<Error Message>",
* error: { ...errorDetails } // Additional error details if available and the env run on development mode
* }
* See OpenAPI documentation for request/response schema.
*/
export const createVideoServiceInternalController = async (
ctx: Context & { body: CreateVideoServiceInternalBodyRequest },
) => {
export const createVideoServiceInternalController = async (ctx: {
set: Context["set"];
body: Static<typeof createVideoServiceInternalSchema.body>;
}) => {
try {
const createdVideoService = await createVideoServiceInternalService(
ctx.body,
);
return returnWriteResponse(
ctx.set,
201,
"Video service created",
createdVideoService,
);
const createdVideoService = await createVideoServiceInternalService(ctx.body);
return returnWriteResponse(ctx.set, 201, "Video service created", createdVideoService);
} catch (error) {
throw mainErrorHandler(ctx.set, error);
}

View File

@ -3,15 +3,18 @@ import { mainErrorHandler } from "../../../helpers/error/handler";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { purgeUnusedSessionService } from "../services/http/purgeUnusedSession.service";
/**
* Controller for purging unused user sessions
*
* This controller handles the HTTP request for purging all unused user sessions. It will delete all unused sessions from the database based on their authentication status and deleted status.
* The response will indicate the success of the operation and may include details about the number of sessions purged if the environment is running in development mode.
*
* See OpenAPI documentation for request/response schema.
*/
export const purgeUnusedSessionController = async (ctx: Context) => {
try {
const result = await purgeUnusedSessionService();
return returnWriteResponse(
ctx.set,
200,
"Successfully purged all unused user sessions",
result,
);
return returnWriteResponse(ctx.set, 200, "Successfully purged all unused user sessions", result);
} catch (error) {
return mainErrorHandler(ctx.set, error);
}

View File

@ -1,55 +1,24 @@
import { Context } from "elysia";
import { Context, Static } from "elysia";
import { mainErrorHandler } from "../../../helpers/error/handler";
import { returnWriteResponse } from "../../../helpers/callback/httpResponse";
import { updateAllEpisodeThumbnailService } from "../services/http/updateAllEpisodeThumbnail.service";
import { updateAllEpisodeThumbnailSchema } from "../schemas/updateAllEpisodeThumbnail.schema";
/**
* @function updateAllEpisodeThumbnailController
* @description Controller to handle the bulk updating of episode thumbnails for all episodes associated with a specific service reference ID.
* Updating all episode thumbnails for a specific target service reference ID.
*
* @param {Context & { body: { service_reference_id: string } }} ctx
* The context object containing the request body.
* The body must include:
* - service_reference_id: string - The ID of the service to which the episodes belong.
* This controller handles the bulk update of episode thumbnails for all episodes associated with a specific service reference ID.
* It fetches the latest thumbnail data from external sources and updates the existing episode records in the database accordingly.
*
* @example
* Request route: PUT /internal/episode/update-thumbnails
* Request body:
* {
* "service_reference_id": "019c0df6-f8fe-7565-82cd-9c29b20232ab"
* },
*
* @returns {Promise<Object>}
* A response object indicating success or failure.
* Return example:
* {
* success: true,
* status: 204,
* message: "Updating {newEpisodeThumbnailsCount} episode thumbnails successfully.",
* }
*
* @throws {Object}
* An error response object if validation fails or an error occurs during bulk insert operation.
* Return example:
* {
* success: false,
* status: <Status Code>,
* message: "<Error Message>",
* error: { ...errorDetails } // Additional error details if available and the env run on development mode
* }
* See OpenAPI documentation for request/response schema.
*/
export const updateAllEpisodeThumbnailController = async (
ctx: Context & { body: { service_reference_id: string } },
) => {
export const updateAllEpisodeThumbnailController = async (ctx: {
set: Context["set"];
body: Static<typeof updateAllEpisodeThumbnailSchema.body>;
}) => {
try {
const newEpisodeThumbnailsCount = await updateAllEpisodeThumbnailService(
ctx.body.service_reference_id,
);
return returnWriteResponse(
ctx.set,
204,
`Updating ${newEpisodeThumbnailsCount} episode thumbnails successfully.`,
);
const newEpisodeThumbnailsCount = await updateAllEpisodeThumbnailService(ctx.body.service_reference_id);
return returnWriteResponse(ctx.set, 204, `Updating ${newEpisodeThumbnailsCount} episode thumbnails successfully.`);
} catch (error) {
return mainErrorHandler(ctx.set, error);
}

View File

@ -5,11 +5,23 @@ import { createVideoServiceInternalController } from "./controllers/createVideoS
import { bulkInsertVideoController } from "./controllers/bulkInsertVideo.controller";
import { updateAllEpisodeThumbnailController } from "./controllers/updateAllEpisodeThumbnail.controller";
import { purgeUnusedSessionController } from "./controllers/purgeUnusedSession.controller";
import { createHeroBannerController } from "./controllers/createHeroBanner.controller";
import { bulkInsertMediaSchema } from "./schemas/bulkInsertMedia.schema";
import { bulkInsertEpisodeSchema } from "./schemas/bulkInsertEpisode.schema";
import { updateAllEpisodeThumbnailSchema } from "./schemas/updateAllEpisodeThumbnail.schema";
import { bulkInsertVideoSchema } from "./schemas/bulkInsertVideo.schema";
import { createVideoServiceInternalSchema } from "./schemas/createVideoServiceInternal.schema";
import { purgeUnusedSessionSchema } from "./schemas/purgeUnusedSession.schema";
import { createHeroBannerSchema } from "./schemas/createHeroBanner.schema";
export const internalModule = new Elysia({ prefix: "/internal" })
.post("/media/bulk-insert", bulkInsertMediaController)
.post("/episode/bulk-insert", bulkInsertEpisodeController)
.put("/episode/update-thumbnails", updateAllEpisodeThumbnailController)
.post("/video/bulk-insert", bulkInsertVideoController)
.post("/video-service", createVideoServiceInternalController)
.post("/user-session/purge-unused", purgeUnusedSessionController);
export const internalModule = new Elysia({
prefix: "/internal",
tags: ["Internal"],
})
.post("/media/bulk-insert", bulkInsertMediaController, bulkInsertMediaSchema)
.post("/episode/bulk-insert", bulkInsertEpisodeController, bulkInsertEpisodeSchema)
.put("/episode/update-thumbnails", updateAllEpisodeThumbnailController, updateAllEpisodeThumbnailSchema)
.post("/video/bulk-insert", bulkInsertVideoController, bulkInsertVideoSchema)
.post("/video-service", createVideoServiceInternalController, createVideoServiceInternalSchema)
.post("/user-session/purge-unused", purgeUnusedSessionController, purgeUnusedSessionSchema)
.post("/hero-banner", createHeroBannerController, createHeroBannerSchema);

View File

@ -0,0 +1,24 @@
import { AppError } from "../../../helpers/error/instances/app";
import { prisma } from "../../../utils/databases/prisma/connection";
import { generateUUIDv7 } from "../../../helpers/databases/uuidv7";
import { SystemAccountId } from "../../../config/account/system";
import { Static } from "elysia";
import { createHeroBannerSchema } from "../schemas/createHeroBanner.schema";
import { Prisma } from "@prisma/client";
export const insertHeroBannerRepository = async (payload: Static<typeof createHeroBannerSchema.body>) => {
try {
return await prisma.heroBanner.create({
data: {
id: generateUUIDv7(),
creatorId: SystemAccountId,
...payload,
},
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
throw new AppError(400, "A hero banner with the order priority already exists", error);
}
throw new AppError(500, "Failed to insert hero banner", error);
}
};

View File

@ -0,0 +1,73 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const bulkInsertEpisodeSchema = {
body: t.Object({
media_mal_id: t.Number({
description: "The MyAnimeList ID of the media for which episodes will be inserted",
}),
}),
query: t.Object({
page: t.Optional(
t.Number({
description: "Episode page number to fetch",
}),
),
}),
detail: {
summary: "Bulk insert episodes for a media",
description:
"Perform bulk insert of episodes for a specific media. This operation fetches episode data from external sources and inserts them into the database. The page parameter is optional; if not provided, the first page of episodes will be fetched.",
responses: {
201: {
description:
"Bulk insert episode operation completed successfully (Data returned only if the env run on development mode)",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 201 },
message: {
type: "string",
default: "Bulk insert episode operation completed successfully",
},
data: {
type: "object",
properties: {
pagination: {
type: "object",
properties: {
last_visible_page: { type: "integer", default: 1 },
has_next_page: { type: "boolean", default: false },
},
},
data: {
type: "array",
items: {
type: "object",
properties: {
mal_id: { type: "integer", default: 1 },
url: { type: "string", default: "https://myanimelist.net/anime/1" },
title: { type: "string", default: "Example Episode Title" },
title_japanese: { type: "string", default: "例のエピソードタイトル" },
title_romanji: { type: "string", default: "Rei no Episōdo Taitoru" },
aired: { type: "string", format: "date-time", default: "2022-01-01T00:00:00.000Z" },
score: { type: "number", default: 8.5 },
filler: { type: "boolean", default: false },
recap: { type: "boolean", default: false },
forum_url: { type: "string", default: "https://myanimelist.net/forum/1" },
},
},
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,96 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const bulkInsertMediaSchema = {
body: t.Object({
mal_id: t.Number({
description:
"The MyAnimeList ID of the media for which episodes will be inserted",
}),
}),
detail: {
summary: "Bulk insert media",
description:
"Fetch media data from external sources and insert them into database",
responses: {
201: {
description: "Bulk insert media operation completed successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 201 },
message: {
type: "string",
default: "Bulk insert anime operation completed successfully",
},
data: {
type: "object",
properties: {
status: { type: "string", default: "airing" },
id: {
type: "string",
default: "019cc6c9-80b2-7f9a-b1b4-c8fb612ed481",
},
title: { type: "string", default: "Sakamoto Days" },
titleAlternative: { type: "object", default: {} },
slug: { type: "string", default: "sakamoto-days" },
malId: { type: "integer", default: 58939 },
pictureMedium: {
type: "string",
default:
"https://myanimelist.net/images/anime/1026/146459.webp",
},
pictureLarge: {
type: "string",
default:
"https://myanimelist.net/images/anime/1026/146459.webp",
},
country: { type: "string", default: "JP" },
score: { type: "string", default: "9.0" },
startAiring: {
type: "string",
format: "date-time",
default: "2022-07-01T00:00:00.000Z",
},
endAiring: {
type: "string",
format: "date-time",
default: "2022-07-01T00:00:00.000Z",
},
synopsis: {
type: "string",
default: "No synopsis available",
},
ageRating: { type: "string", default: "PG-13" },
mediaType: { type: "string", default: "ANIME" },
source: { type: "string" },
onDraft: { type: "boolean", default: false },
uploadedBy: { type: "string", default: "system" },
deletedAt: {
type: "string",
format: "date-time",
default: "2022-07-01T00:00:00.000Z",
},
createdAt: {
type: "string",
format: "date-time",
default: "2022-07-01T00:00:00.000Z",
},
updatedAt: {
type: "string",
format: "date-time",
default: "2022-07-01T00:00:00.000Z",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,63 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const bulkInsertVideoSchema = {
body: t.Object({
media_id: t.String({
description: "The ID of the media for which episodes will be inserted",
}),
data: t.Array(
t.Object({
episode: t.Number({
description: "The episode number",
}),
videos: t.Array(
t.Object({
service_id: t.String({
description: "The ID of the video service",
}),
video_code: t.String({
description: "The code of the video on the service",
}),
thumbnail_code: t.Optional(
t.String({
description: "The code of the thumbnail for the video on the service",
}),
),
}),
),
}),
),
}),
detail: {
summary: "Bulk insert videos for a media episode",
description:
"Perform bulk insert of videos for specific episodes of a media. This operation inserts multiple videos associated with different episodes into the database based on the provided data.",
responses: {
201: {
description: "Videos inserted successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 201 },
message: { type: "string", default: "Videos inserted successfully" },
data: {
type: "array",
default: ["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"],
description: "An array of IDs of the inserted videos",
items: {
type: "string",
description: "The ID of the inserted video",
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,79 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const createHeroBannerSchema = {
body: t.Object({
orderPriority: t.Optional(
t.Number({ description: "The priority order of the hero banner. Lower numbers indicate higher priority." }),
),
mediaId: t.String({ description: "The ID of the media associated with the hero banner" }),
imageUrl: t.Optional(
t.String({
description:
"The URL of the image used in the hero banner. If not provided, a thumbnail image of the media will be used.",
}),
),
startDate: t.Date({ description: "The start date for the hero banner in ISO 8601 format" }),
endDate: t.Date({ description: "The end date for the hero banner in ISO 8601 format" }),
}),
detail: {
summary: "Create a new hero banner",
description:
"Perform creation of a new hero banner. This operation adds a new hero banner to the database based on the provided data.",
responses: {
201: {
description: "Hero banner created successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 201 },
message: { type: "string", default: "Hero banner created successfully" },
data: {
type: "object",
description:
"The created hero banner object. This field is returned only if the environment is running in development mode.",
properties: {
id: { type: "string", description: "The ID of the created hero banner" },
orderPriority: {
type: "number",
description: "The priority order of the hero banner. Lower numbers indicate higher priority.",
},
mediaId: { type: "string", description: "The ID of the media associated with the hero banner" },
imageUrl: {
type: "string",
description:
"The URL of the image used in the hero banner. If not provided, a thumbnail image of the media will be used.",
},
startDate: {
type: "string",
format: "date-time",
description: "The start date for the hero banner in ISO 8601 format",
},
endDate: {
type: "string",
format: "date-time",
description: "The end date for the hero banner in ISO 8601 format",
},
createdAt: {
type: "string",
format: "date-time",
description: "The timestamp when the hero banner was created",
},
updatedAt: {
type: "string",
format: "date-time",
description: "The timestamp when the hero banner was last updated",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,92 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const createVideoServiceInternalSchema = {
body: t.Object({
name: t.String({
description: "The name of the video service",
}),
domain: t.String({
description: "The domain of the video service",
}),
logo: t.String({
description: "The logo URL of the video service",
}),
hexColor: t.String({
description: "The hex color associated with the video service",
}),
endpointVideo: t.String({
description: "The endpoint URL for video streaming",
}),
endpointThumbnail: t.String({
description: "The endpoint URL for thumbnails",
}),
endpointDownload: t.Optional(
t.String({
description: "The endpoint URL for downloads",
}),
),
}),
detail: {
summary: "Create a new video service",
description:
"Perform creation of a new video service. This operation adds a new video service to the database based on the provided data.",
responses: {
201: {
description: "Video service created successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 201 },
message: { type: "string", default: "Video service created" },
data: {
type: "object",
description:
"The created video service object. This field is returned only if the environment is running in development mode.",
properties: {
id: { type: "string", description: "The ID of the created video service" },
name: { type: "string", description: "The name of the video service" },
domain: { type: "string", description: "The domain of the video service" },
logo: { type: "string", description: "The logo URL of the video service" },
hexColor: { type: "string", description: "The hex color associated with the video service" },
endpointVideo: { type: "string", description: "The endpoint URL for video streaming" },
endpointThumbnail: { type: "string", description: "The endpoint URL for thumbnails" },
endpointDownload: {
type: "string",
description:
"The endpoint URL for downloads. This field is optional and may be null if not provided.",
},
createdAt: {
type: "string",
format: "date-time",
description: "The timestamp when the video service was created",
},
updatedAt: {
type: "string",
format: "date-time",
description: "The timestamp when the video service was last updated",
},
deletedAt: {
type: "string",
format: "date-time",
description:
"The timestamp when the video service was deleted. This field is null if the video service is not deleted.",
},
createdBy: {
type: "string",
description:
"The ID of the account that created the video service (filled with the system account ID)",
},
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,34 @@
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const purgeUnusedSessionSchema = {
detail: {
summary: "Purge all unused user sessions",
description:
"Perform purge of all unused user sessions. This operation deletes all user sessions from the database that are considered unused based on authentication status and deleted status. This helps in maintaining a clean session store and improving security by removing stale sessions.",
responses: {
200: {
description: "Unused user sessions purged successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 200 },
message: { type: "string", default: "Successfully purged all unused user sessions" },
data: {
type: "object",
description:
"An object containing details about the purge operation. This field is returned only if the environment is running in development mode.",
properties: {
count: { type: "integer", description: "The number of user sessions that were purged" },
},
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -0,0 +1,35 @@
import { t } from "elysia";
import { AppRouteSchema } from "../../../helpers/types/AppRouteSchema";
export const updateAllEpisodeThumbnailSchema = {
body: t.Object({
service_reference_id: t.String({
description: "The ID of the service to which the target of episode thumbnails belong",
}),
}),
detail: {
summary: "Bulk update episode thumbnails",
description:
"Perform bulk update of episode thumbnails for all episodes associated with a specific service reference ID. This operation fetches the latest thumbnail data from external sources and updates the existing episode records in the database accordingly.",
responses: {
204: {
description: "Updating episode thumbnails operation completed successfully",
content: {
"application/json": {
schema: {
type: "object",
properties: {
success: { type: "boolean", default: true },
status: { type: "integer", default: 204 },
message: {
type: "string",
default: "Updating {newEpisodeThumbnailsCount} episode thumbnails operation completed successfully",
},
},
},
},
},
},
},
},
} satisfies AppRouteSchema;

View File

@ -1,5 +1,4 @@
import { Prisma } from "@prisma/client";
import { getContentReferenceAPI } from "../../../../config/apis/media.reference";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { bulkInsertGenresRepository } from "../../repositories/bulkInsertGenres.repository";
import { InsertMediaRepository } from "../../repositories/bulkinsertMedia.repository";
@ -9,6 +8,7 @@ import { generateSlug } from "../../../../helpers/characters/generateSlug";
import { bulkInsertCharWithVAService } from "../internal/bulkInsertCharWithVA.service";
import { generateUUIDv7 } from "../../../../helpers/databases/uuidv7";
import { SystemAccountId } from "../../../../config/account/system";
import { getContentReferenceAPI } from "../../../../config/apis/jikan/media.reference";
export const bulkInsertAnimeService = async (malId: number) => {
try {
@ -24,8 +24,8 @@ export const bulkInsertAnimeService = async (malId: number) => {
const constructMediaPayload: Prisma.MediaUpsertArgs["create"] = {
id: generateUUIDv7(),
title: mediaFullInfo.data.title,
titleAlternative: (mediaFullInfo.data
.titles as unknown) as Prisma.InputJsonValue,
titleAlternative: mediaFullInfo.data
.titles as unknown as Prisma.InputJsonValue,
slug: await generateSlug(mediaFullInfo.data.title, {
model: "media",
target: "slug",

View File

@ -1,10 +1,10 @@
import { getEpisodeReferenceAPI } from "../../../../config/apis/episode.reference";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { MediaEpisodeInfoResponse } from "../../types/mediaEpisodeInfo.type";
import { getMediaByMalIdRepository } from "../../../media/repositories/GET/getMediaByMalId.repository";
import { AppError } from "../../../../helpers/error/instances/app";
import { SystemAccountId } from "../../../../config/account/system";
import { bulkInsertEpisodesRepository } from "../../repositories/bulkInsertEpisodes.repository";
import { getEpisodeReferenceAPI } from "../../../../config/apis/jikan/episode.reference";
export const bulkInsertEpisodeService = async (
mal_id: number,

View File

@ -1,12 +1,11 @@
import { SystemAccountId } from "../../../../config/account/system";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { BulkInsertVideoBodyRequest } from "../../controllers/bulkInsertVideo.controller";
import { findEpisodeWithMediaIdRepository } from "../../repositories/findEpisodeWithMediaId.repository";
import { bulkInsertVideoRepository } from "../../repositories/bulkInsertVideo.repository";
import { Static } from "elysia";
import { bulkInsertVideoSchema } from "../../schemas/bulkInsertVideo.schema";
export const bulkInsertVideoService = async (
body: BulkInsertVideoBodyRequest,
) => {
export const bulkInsertVideoService = async (body: Static<typeof bulkInsertVideoSchema.body>) => {
try {
const insertedVideos: string[] = [];
for (const episodeData of body.data) {

View File

@ -0,0 +1,12 @@
import { Static } from "elysia";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { insertHeroBannerRepository } from "../../repositories/insertHeroBanner.repository";
import { createHeroBannerSchema } from "../../schemas/createHeroBanner.schema";
export const createHeroBannerService = async (payload: Static<typeof createHeroBannerSchema.body>) => {
try {
return await insertHeroBannerRepository(payload);
} catch (error) {
ErrorForwarder(error);
}
};

View File

@ -1,11 +1,10 @@
import { Static } from "elysia";
import { SystemAccountId } from "../../../../config/account/system";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { CreateVideoServiceInternalBodyRequest } from "../../controllers/createVideoService.controller";
import { createVideoServiceInternalRepository } from "../../repositories/createVideoService.repository";
import { createVideoServiceInternalSchema } from "../../schemas/createVideoServiceInternal.schema";
export const createVideoServiceInternalService = async (
body: CreateVideoServiceInternalBodyRequest,
) => {
export const createVideoServiceInternalService = async (body: Static<typeof createVideoServiceInternalSchema.body>) => {
try {
return await createVideoServiceInternalRepository({
name: body.name,

View File

@ -1,35 +1,39 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { updateEpisodeRepository } from "../../../episode/repositories/PUT/updateEpisode.repository";
import { getAllEpisodeWithThumbnailLinkRepository } from "../../../episode/repositories/GET/getAllEpisodeWithThumbnailLink.repository";
import { bulkUpdateThumbnailRepository } from "../../../episode/repositories/PUT/bulkUpdateThumbnail.repository";
import { getAllVideoServiceWithEpisodeRepository } from "../../../videoService/repositories/GET/getAllVideoServiceWithEpisode.repository";
export const updateAllEpisodeThumbnailService = async (
serviceReferenceId: string,
serviceReferenceId?: string,
) => {
try {
if (!serviceReferenceId)
throw new AppError(400, "Service Reference ID is required.");
const episodesData = await getAllEpisodeWithThumbnailLinkRepository(
const videosData = await getAllVideoServiceWithEpisodeRepository(
serviceReferenceId,
);
let updatedThumbnailsCount = 0;
for (const episode of episodesData) {
if (episode.videos.length === 0) continue;
await updateEpisodeRepository({
id: episode.id,
pictureThumbnail:
episode.videos[0].service.endpointThumbnail?.replace(
if (!videosData || videosData.length === 0)
throw new AppError(
404,
"No episode with no thumbnail found in the specified video service.",
);
const updatePayload = videosData.flatMap((videoService) => {
const { endpointThumbnail, videos } = videoService;
return videos.map((video) => ({
episodeId: video.episode.id,
thumbnailCode: endpointThumbnail!.replace(
":code:",
episode.videos[0].code,
) || null,
video.thumbnailCode || video.videoCode,
),
}));
});
updatedThumbnailsCount++;
}
await bulkUpdateThumbnailRepository(updatePayload);
return updatedThumbnailsCount;
return updatePayload.length;
} catch (error) {
ErrorForwarder(error);
}

View File

@ -1,5 +1,5 @@
import { SystemAccountId } from "../../../../config/account/system";
import { getContentReferenceAPI } from "../../../../config/apis/media.reference";
import { getContentReferenceAPI } from "../../../../config/apis/jikan/media.reference";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { bulkInsertCharactersRepository } from "../../repositories/bulkInsertCharacters.repository";
import { bulkInsertLangVARepository } from "../../repositories/bulkInsertLangVA.repository";

View File

@ -0,0 +1,12 @@
import Elysia, { Context } from "elysia";
import { returnWriteResponse } from "../../helpers/callback/httpResponse";
export const systemPreferenceModule = new Elysia({
prefix: "/system-preference",
}).get("/", (ctx: Context) => {
return returnWriteResponse(
ctx.set,
200,
"System Preference module is up and running",
);
});

View File

@ -0,0 +1,47 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../../helpers/error/instances/forwarder";
import { redis } from "../../../../utils/databases/redis/connection";
import { findSystemPreferenceRepository } from "../repositories/findSystemPreference.repository";
export const findSystemPreferenceService = async (
key: string,
type: "boolean" | "string" | "number" = "string",
) => {
try {
// First, check if the system preference is exists in redis cache
const cachedValue = await redis.get(
`${process.env.APP_NAME}:configs:${key}`,
);
if (!cachedValue) {
// If not exists in cache, fetch from database. If found, return the value and set it to cache, if not found, throw an error
const systemPreference = await findSystemPreferenceRepository(key);
if (!systemPreference)
throw new AppError(404, "System preference not found");
// and set it to cache for future requests
await redis.set(
`${process.env.APP_NAME}:configs:${key}`,
systemPreference.value,
);
// Return the value from database
return parseValue(systemPreference.value, type);
} else {
return parseValue(cachedValue, type);
}
} catch (error) {
ErrorForwarder(error, 500, "Failed to find system preference");
}
};
const parseValue = (value: string, type: "boolean" | "string" | "number") => {
switch (type) {
case "boolean":
return value === "true";
case "number":
return Number(value);
default:
return value;
}
};

View File

@ -0,0 +1,15 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { prisma } from "../../../../utils/databases/prisma/connection";
export const findSystemPreferenceRepository = async (key: string) => {
try {
return await prisma.systemPreference.findUnique({
where: {
key,
deletedAt: null,
},
});
} catch (error) {
throw new AppError(500, "Failed to find system preference", error);
}
};

View File

@ -0,0 +1,13 @@
import Elysia, { Context } from "elysia";
import { returnWriteResponse } from "../../helpers/callback/httpResponse";
export const videoServiceModule = new Elysia({ prefix: "/video-service" }).get(
"/",
async (ctx: Context) => {
return returnWriteResponse(
ctx.set,
200,
"Video service endpoint is working.",
);
},
);

View File

@ -0,0 +1,3 @@
import { prisma } from "../../utils/databases/prisma/connection";
export const videoServiceModel = prisma.videoService;

View File

@ -0,0 +1,44 @@
import { AppError } from "../../../../helpers/error/instances/app";
import { videoServiceModel } from "../../model";
export const getAllVideoServiceWithEpisodeRepository = async (
videoServiceId: string,
) => {
try {
return await videoServiceModel.findMany({
where: {
id: videoServiceId,
endpointThumbnail: {
not: null,
},
videos: {
some: {
episode: {
pictureThumbnail: null,
},
},
},
},
select: {
endpointThumbnail: true,
videos: {
select: {
thumbnailCode: true,
videoCode: true,
episode: {
select: {
id: true,
},
},
},
},
},
});
} catch (error) {
throw new AppError(
500,
"An error occurred while fetching video services with episodes.",
error,
);
}
};