27 Commits
Author SHA1 Message Date
janishutz c27be5f42c fix: improve login page 2026-09-08 14:36:58 +02:00
janishutz 5e322f6c67 revert: "fix: rename config"
This reverts commit 8d6d24a780.
2026-09-08 14:13:50 +02:00
janishutz 8d6d24a780 fix: rename config 2026-09-08 14:13:25 +02:00
janishutz 946ba84518 feat: prepare new popups 2026-09-08 13:00:53 +02:00
janishutz be2a9f3a3e fix: crash, design for playlists
crash was caused by indices not updating correctly
2026-09-08 12:50:34 +02:00
janishutz d573ac90eb feat: basic design of share page, various small fixes 2026-09-08 12:27:36 +02:00
janishutz b11882c993 feat: improve sync 2026-09-08 11:20:17 +02:00
janishutz 047a3a8b29 feat: song editor 2026-09-08 09:52:40 +02:00
janishutz 6d9853f2c1 feat: basic rendering of queue on share screen 2026-09-07 20:24:23 +02:00
janishutz 054fda2fb9 feat: basic connection between frontend and backend 2026-09-07 19:35:30 +02:00
janishutz 867374fa47 feat: playlist loading 2026-09-07 16:15:31 +02:00
janishutz a5910df441 fix: Progress bar not moving properly when updated 2026-09-07 16:15:00 +02:00
janishutz cb5cdc483f fix(backend): crashes due to logger and missing server-stubs files 2026-09-07 16:14:13 +02:00
janishutz 18bdf82bcf fix(backend): send use poll on attempted sse connection establishing 2026-09-07 14:13:37 +02:00
janishutz 68bbfa7896 fix(backend): don't send connect type on own check 2026-09-07 12:46:28 +02:00
janishutz 8a83326d60 feat: request wrapper utility 2026-09-07 12:46:08 +02:00
janishutz ab08a94d55 feat(backend): login, most endpoints complete 2026-09-07 12:28:09 +02:00
janishutz 4d4ddfe255 feat: set up backend 2026-09-04 14:57:40 +02:00
janishutz c123673ca5 chore: prepare backend 2026-09-03 08:46:53 +02:00
janishutz 223478f7cc chore: add todos 2026-09-02 15:44:05 +02:00
janishutz b77f0a6dcf chore: move to AGPL license 2026-09-02 15:43:33 +02:00
janishutz 778f54055d chore: basic dockerfiles 2026-09-02 15:41:49 +02:00
janishutz b903eb416f chore: refactor vue components 2026-09-02 15:21:43 +02:00
janishutz 8a3dd7a583 feat: loading local songs, basic association
association used to load existing playlists with local files
2026-09-02 14:23:16 +02:00
janishutz aba98d3122 chore: mark web and backend eslint configs as generated explicitly 2026-09-02 13:28:42 +02:00
janishutz 4339861ffd chore: remove eslint config from code stats 2026-09-02 13:27:47 +02:00
janishutz 01526034ce feat: redesign main page, get player working (mostly) with Apple Music source 2026-09-01 18:16:11 +02:00
102 changed files with 3987 additions and 1159 deletions
+2
View File
@@ -0,0 +1,2 @@
web/eslint.config.mjs linguist-generated
backend/eslint.config.mjs linguist-generated
+2
View File
@@ -1,7 +1,9 @@
# ignore node_modules
node_modules
*.secret.json
*.secret.json
apple_private_key.p8
musicplayerv2-server.zip
dist
package-lock.json
yarn.lock
+184 -591
View File
@@ -1,619 +1,212 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
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.
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, 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.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
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.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
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.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
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.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"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.
"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.
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.
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 "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.
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.
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.
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.
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.
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 "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
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. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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.
+24 -13
View File
@@ -4,21 +4,21 @@
</div>
<div id="badges" align="center">
<img alt="Project License" src="https://img.shields.io/github/license/simplePCBuilding/MusicPlayerV2.svg">
<img alt="GitHub Repo size" src="https://img.shields.io/github/repo-size/simplePCBuilding/MusicPlayerV2.svg">
<img alt="GitHub Repo issues" src="https://img.shields.io/github/issues-pr-raw/simplePCBuilding/MusicPlayerV2">
<img alt="Top Languages" src="https://img.shields.io/github/languages/top/simplePCBuilding/MusicPlayerV2">
<img alt="GitHub Repo filecount" src="https://img.shields.io/github/directory-file-count/simplePCBuilding/MusicPlayerV2.svg">
<img alt="Project License" src="https://img.shields.io/github/license/janishutz/MusicPlayer.svg">
<img alt="GitHub Repo size" src="https://img.shields.io/github/repo-size/janishutz/MusicPlayer.svg">
<img alt="GitHub Repo issues" src="https://img.shields.io/github/issues-pr-raw/janishutz/MusicPlayer">
<img alt="Top Languages" src="https://img.shields.io/github/languages/top/janishutz/MusicPlayer">
<img alt="GitHub Repo filecount" src="https://img.shields.io/github/directory-file-count/janishutz/MusicPlayer.svg">
<br>
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/simplePCBuilding/MusicPlayerV2">
<img alt="GitHub watchers" src="https://img.shields.io/github/watchers/simplePCBuilding/MusicPlayerV2">
<img alt="GitHub forks" src="https://img.shields.io/github/forks/simplePCBuilding/MusicPlayerV2">
<img alt="GitHub commit activity" src="https://img.shields.io/github/commit-activity/m/simplePCBuilding/MusicPlayerV2">
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/janishutz/MusicPlayer">
<img alt="GitHub watchers" src="https://img.shields.io/github/watchers/janishutz/MusicPlayer">
<img alt="GitHub forks" src="https://img.shields.io/github/forks/janishutz/MusicPlayer">
<img alt="GitHub commit activity" src="https://img.shields.io/github/commit-activity/m/janishutz/MusicPlayer">
<br>
<img alt="GitHub all releases" src="https://img.shields.io/github/downloads/simplePCBuilding/MusicPlayerV2/total?label=Downloads (total)">
<img alt="GitHub release (latest by date)" src="https://img.shields.io/github/downloads/simplePCBuilding/MusicPlayerV2/latest/total?label=Downloads (latest)">
<img alt="Latest release" src="https://img.shields.io/github/release/simplePCBuilding/MusicPlayerV2.svg">
<img alt="App Version" src="https://img.shields.io/github/package-json/v/simplePCBuilding/MusicPlayerV2.svg?label=Development Version">
<img alt="GitHub all releases" src="https://img.shields.io/github/downloads/janishutz/MusicPlayer/total?label=Downloads (total)">
<img alt="GitHub release (latest by date)" src="https://img.shields.io/github/downloads/janishutz/MusicPlayer/latest/total?label=Downloads (latest)">
<img alt="Latest release" src="https://img.shields.io/github/release/janishutz/MusicPlayer.svg">
<img alt="App Version" src="https://img.shields.io/github/package-json/v/janishutz/MusicPlayer.svg?label=Development Version">
</div>
# Development Branch
@@ -38,9 +38,20 @@ The [hosted version](https://music.janishutz.com) of this MusicPlayer, which is
</div>
# Features
**NOTICE:** This section has not been updated for the new version of MusicPlayer yet
- Browser based App that runs on all OS (Linux, MacOS, Windows, iOS, Android, iPadOS, ...)
- Fully featured Music Player
- Show all song information over the Internet on any amount of client displays
- Client displays show the playback position and all information from song metadata fetched from the Apple Music API
- Play most common music files
- No setup required when using the hosted version at [music.janishutz.com](https://music.janishutz.com)
## License
MusicPlayer Copyright (C) 2026 janishutz
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 http://www.gnu.org/licenses/.
+19
View File
@@ -0,0 +1,19 @@
FROM node:25-alpine3.21 AS build
WORKDIR /usr/src/build
COPY . /usr/src/build
RUN npm i
RUN npm run build
# Prod build with fewer deps
FROM node:25-alpine3.21 AS prod
WORKDIR /usr/src/musicplayer
COPY --from=build /usr/src/build/dist /usr/src/musicplayer/dist
COPY ./index.js /usr/src/musicplayer/index.js
RUN npm i --omit=dev
CMD [ "node", "index.js" ]
+33
View File
@@ -0,0 +1,33 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"foss",
"hosted"
],
"default": "foss",
"description": "Mode to use for the login. If set to hosted, sdk configuration needs to be complete"
},
"clientMode": {
"type": "string",
"enum": [
"sse",
"poll"
],
"default": "poll",
"description": "Default information retrieval mode for the basic remote displays. Polling is slightly cheaper at the cost of responsiveness"
},
"webUrl": {
"type": "string",
"description": "The URL to the frontend. Just the host, in form https://music.janishutz.com"
}
},
"required": [
"mode",
"clientMode",
"webUrl"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"$schema": "../config.schema.json",
"mode": "hosted",
"clientMode": "sse",
"webUrl": "http://localhost:8081"
}
+1
View File
@@ -0,0 +1 @@
{"playlists":[{"name":"Hello World","songs":[{"duration":236,"name":"CAN'T STOP THE FEELING! (Original Song From DreamWorks Animation's \"TROLLS\")","additional-info":"Test 3","artist":"Justin Timberlake","artwork":"https://is1-ssl.mzstatic.com/image/thumb/Music124/v4/52/d0/02/52d002d7-1f7f-8d91-4791-ed04c460ec93/886445894653.jpg/2000x2000bb.jpg","identifier":"blob:http://localhost:8081/fdb6fccd-30cb-458c-a9f6-c424d2f53c43","source":"local","additional-identifier":"16_Can't_Stop_The_Feeling-Justin_Timberlake.mp3__4407330"},{"duration":258,"name":"Muévelo","additional-info":"Test","artist":"Rey Ruiz","artwork":"https://is1-ssl.mzstatic.com/image/thumb/Music122/v4/58/15/0d/58150db1-0e74-dd19-f7eb-3f15e8a04b56/197187182459.jpg/2000x2000bb.jpg","identifier":"blob:http://localhost:8081/18dcea36-839d-4714-b7fc-6800f26e07b9","source":"local","additional-identifier":"18_Muevlo-Rey_Ruiz.mp3__4831574"}]}],"userid":"server-stubs","version":"1"}
+13 -5
View File
@@ -1,17 +1,25 @@
{
"dependencies": {
"@janishutz/login-sdk-server": "^1.4.0",
"@janishutz/login-sdk-server-stubs": "^1.4.0",
"@janishutz/store-sdk": "^1.2.1",
"body-parser": "^2.3.0",
"cors": "^2.8.6",
"express": "^5.2.1",
"express-session": "^1.19.0",
"jsonwebtoken": "^9.0.3"
"jsonwebtoken": "^9.0.3",
"typescript": "^6.0.3"
},
"devDependencies": {
"eslint": "^10.9.0",
"@types/express": "^5.0.6",
"@types/express-session": "^1.19.0",
"@types/node": "^26.2.0",
"@eslint/js": "^10.0.1",
"@stylistic/eslint-plugin": "^5.10.0",
"@types/body-parser": "^1.19.6",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
"@types/express-session": "^1.19.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^26.2.0",
"eslint": "^10.9.0",
"eslint-plugin-vue": "^10.10.0",
"globals": "^17.11.0",
"typescript-eslint": "^8.67.0"
+74 -35
View File
@@ -1,55 +1,94 @@
import {
getLoginSdk,
getStoreSdk
} from './sdk';
import {
Config
} from './dtype/config';
import devtoken from './routes/devtoken';
import express from 'express';
import expressSession from 'express-session';
import fs from 'fs';
import jwt from 'jsonwebtoken';
import logger from './logger';
import path from 'path';
import room from './routes/room';
import user from './routes/user';
const run = () => {
// FIXME: Use DB instead of memory optionally
const config = JSON.parse( fs.readFileSync( path.join(
__dirname,
'/../config/config.json'
) ).toString() ) as Config;
const foss = config.mode !== 'hosted';
const sdkConfig = JSON.parse( fs.readFileSync( path.join(
__dirname,
`/../config/sdk.config.${ foss ? 'testing' : 'secret' }.json`
) ).toString() );
const sdk = getLoginSdk( foss );
const storeSdk = getStoreSdk( foss );
const app = express();
app.use( expressSession( {
'secret': 'dev',
'resave': true,
'saveUninitialized': false
} ) );
logger.info( 'Starting in', foss ? 'FOSS' : 'hosted', 'mode' );
app.use( logger.routeLogging() );
// Load id.janishutz.com SDK and allow signing in
sdk.setUp(
{
'prod': false,
'service': {
'serviceID': sdkConfig[ 'name' ],
'serviceToken': sdkConfig[ 'token' ]
},
'user-agent': sdkConfig[ 'ua' ],
'sessionType': 'memory',
'frontendURL': config.webUrl,
'corsWhitelist': [ config.webUrl ],
'recheckTimeout': 300 * 1000,
'advancedVerification': 'sdk',
'defaultRedirectURL': '/app'
},
app,
async () => {
return true;
},
async ( uid: string ) => {
fs.writeFileSync( path.join( __dirname, '/data/', uid ), '{}' );
return true;
},
async () => {
return true;
},
async () => {
return true;
}
);
app.get( '/', ( request: express.Request, response: express.Response ) => {
response.send( 'HELLO WORLD' );
} );
const privateKey = fs.readFileSync( path.join(
// Load store sdk
const storeConfig = JSON.parse( fs.readFileSync( path.join(
__dirname,
'/config/apple_private_key.p8'
) ).toString();
const musicApiConfig = JSON.parse( fs.readFileSync( path.join(
__dirname,
'/config/apple-music-api.config.secret.json'
`/../config/store-sdk.config.${ foss ? 'testing' : 'secret' }.json`
) ).toString() );
app.get( '/dev-token', ( _request: express.Request, response: express.Response ) => {
// sign dev token
const now = new Date().getTime();
const tomorrow = now + ( 24 * 3600 * 1000 );
const jwtToken = jwt.sign( {
'iss': musicApiConfig.teamID,
'iat': Math.floor( now / 1000 ),
'exp': Math.floor( tomorrow / 1000 )
}, privateKey, {
'algorithm': 'ES256',
'keyid': musicApiConfig.keyID
} );
response.send( jwtToken );
storeSdk.configure( storeConfig );
app.get( '/', ( _request: express.Request, response: express.Response ) => {
response.redirect( config.webUrl ?? 'https://music.janishutz.com' );
} );
// Load extra routes
devtoken.routes( app, foss );
room.routes( app, foss, config );
user.routes( app, foss );
app.use( ( _request: express.Request, response: express.Response ) => {
response.sendFile( path.join( __dirname, '' ) );
response.sendStatus( 404 );
} );
const PORT = process.env.PORT || 8080;
app.listen( PORT );
+56
View File
@@ -0,0 +1,56 @@
import {
CorsOptions
} from 'cors';
import cors from 'cors';
let corsWhitelist: string[] = [];
const configure = ( whitelist: string[] ) => {
corsWhitelist = whitelist;
};
const middleware = ( rest: boolean = false ) => {
return cors( genCorsOpts( rest ) );
};
/**
* Generate the options for the CORS library
* @param rest - [OPTIONAL] Whether to allow REST requests or not
* @returns CORS options object that can be used for the cors library
*/
const genCorsOpts = ( rest: boolean = false ): CorsOptions => {
const corsOpts: CorsOptions = {
'credentials': true,
'optionsSuccessStatus': 200,
'origin': ( origin, cb ) => {
const status = blockREST( origin! );
cb( null, status );
}
};
if ( rest ) {
corsOpts[ 'origin' ] = ( origin, cb ) => {
const status = allowREST( origin! );
cb( null, status );
};
}
return corsOpts;
};
const blockREST = ( origin: string ): boolean => {
return corsWhitelist.includes( origin );
};
const allowREST = ( origin: string ): boolean => {
return blockREST( origin ) || !origin;
};
export default {
genCorsOpts,
configure,
middleware
};
+5
View File
@@ -0,0 +1,5 @@
export interface Config {
'mode': 'foss' | 'hosted';
'clientMode': 'sse' | 'poll';
'webUrl': string;
}
+55
View File
@@ -0,0 +1,55 @@
export interface UserPlaylistFile {
'version': '1',
'userid': string,
'playlists': Playlist[]
}
export interface Playlist {
'name': string;
'songs': PlaylistSongs;
}
export type PlaylistSongs = Song[];
export interface Song {
/**
* Where the song can be found
*/
'source': 'local' | 'applemusic';
/**
* The identifier for the song so it can be found again (such as Apple Music ID or URL for playback)
*/
'identifier': string;
/**
* Any additional identifiers (such as filename, etc) to associate.
* Even if this is not used, set this value if local files are needed
*/
'additional-identifier'?: string;
/**
* Additional info, such as dance type to be displayed on remote screens
*/
'additional-info': string;
/**
* The artist of the song
*/
'artist': string;
/**
* The name of the song
*/
'name': string;
/**
* The cover image as a URL
*/
'artwork': string;
/**
* Song duration
*/
'duration': number;
}
+23 -14
View File
@@ -1,29 +1,37 @@
import express from 'express';
import {
writeFile
} from 'node:fs';
const log = ( ...msg: string[] ) => {
output( 'log', log.caller.toString(), ...msg );
const log = ( ...msg: unknown[] ) => {
output( 'log', 'UNKNOWN', ...msg );
};
const info = ( ...msg: string[] ) => {
output( 'info', log.caller.toString(), ...msg );
const info = ( ...msg: unknown[] ) => {
output( 'info', 'UNKNOWN', ...msg );
};
const debug = ( ...msg: string[] ) => {
output( 'debug', log.caller.toString(), ...msg );
const debug = ( ...msg: unknown[] ) => {
output( 'debug', 'UNKNOWN', ...msg );
};
const warn = ( ...msg: string[] ) => {
output( 'warn', log.caller.toString(), ...msg );
const warn = ( ...msg: unknown[] ) => {
output( 'warn', 'UNKNOWN', ...msg );
};
const error = ( ...msg: string[] ) => {
output( 'error', log.caller.toString(), ...msg );
const error = ( ...msg: unknown[] ) => {
output( 'error', 'UNKNOWN', ...msg );
};
const fatal = ( ...msg: string[] ) => {
output( 'fatal', log.caller.toString(), ...msg );
const fatal = ( ...msg: unknown[] ) => {
output( 'fatal', 'UNKNOWN', ...msg );
};
const routeLogging = () => {
return ( request: express.Request, _response: express.Response, next: express.NextFunction ) => {
output( 'info', 'ROUTER', request.originalUrl, 'from', request.headers['user-agent'] ?? 'No UA' );
next();
};
};
@@ -51,7 +59,7 @@ const configure = ( location: 'stderr' | 'file', minLevel: LogLevel, file?: stri
const logfile: string[] = [];
const output = ( level: LogLevel, caller: string, ...message: string[] ) => {
const output = ( level: LogLevel, caller: string, ...message: unknown[] ) => {
if ( levels.indexOf( level ) < lev ) {
return;
}
@@ -100,5 +108,6 @@ export default {
warn,
error,
fatal,
configure
configure,
routeLogging
};
+186
View File
@@ -0,0 +1,186 @@
import {
Client,
Room,
RoomStore
} from './room';
import {
PlaylistSongs
} from '../../dtype/file';
import {
Response
} from 'express';
const rooms: RoomStore = {};
/**
* The room to get
* @param room - The name of the room to get
* @returns The room, or undefined if it is not present
*/
const get = ( room: string ): Room | undefined => {
return rooms[room];
};
/**
* @param name - The name of the room to create
* @param uid - The ID of the user
*/
const create = ( name: string, uid: string ) => {
if ( rooms[ name ] ) {
return false;
} else {
rooms[ name ] = {
'clients': [],
'trackingClients': [],
'owner': uid,
'playlist': {
'playlist': [],
'lastUpdate': new Date().getTime()
},
'state': {
'index': 0,
'lastUpdate': new Date().getTime(),
'playing': false,
'start': new Date().getTime(),
'offset': 0
}
};
return true;
}
};
/**
* Add a listening client to a room
* @param roomName - The room ID this client should belong to
* @param id - The ID of the client
* @param kind - The type of client that is to be removed
* @param response - The express response object
* @returns true if successful, false otherwise
*/
const addClient = ( roomName: string, id: string, kind: 'client' | 'trackingClient', response: Response ) => {
if ( !rooms[roomName] ) return false;
const room = rooms[roomName][kind + 's' as 'clients' | 'trackingClients'] as Client[];
room.push( {
'response': response,
'id': id
} );
return true;
};
/**
* Remove a listening client by its ID
* @param roomName - The room ID this client belongs to
* @param id - The ID of the client
* @param kind - The type of client that is to be removed
* @returns true if successful, false otherwise
*/
const removeClient = ( roomName: string, id: string, kind: 'client' | 'trackingClient' ) => {
if ( !rooms[roomName] ) return false;
const room = rooms[roomName][kind + 's' as 'clients' | 'trackingClients'] as Client[];
const idx = room.findIndex( client => client.id === id );
if ( idx < 0 )
return false;
room.splice( idx, 1 );
return true;
};
/**
* Close the room and disconnect all clients
* @param name - The name of the room
* @param uid - The name of the owner of the room
*/
const close = ( name: string, uid: string ) => {
if ( !rooms[name] || rooms[name].owner !== uid ) return false;
rooms[name].clients.forEach( client => client.response.send( 'data: closed\n\n' ) );
delete rooms[name];
return true;
};
/**
* Update the state of the specified room
* @param room - The room to update the state for
* @param uid - The UserID of the user that created the room (i.e. the owner)
* @param playing - Set to true if the player is playing currently
* @param index - The current playback index
* @param start - The timestamp where playback of the current song started
* @param offset - The playback offset from the start in seconds
* @returns true if update succeeded
*/
const updateState = ( room: string, uid: string, playing: boolean, index: number, start: number, offset: number ) => {
if ( !rooms[room] || rooms[room].owner !== uid ) {
return false;
}
rooms[room].state = {
'playing': playing,
'index': index,
'lastUpdate': new Date().getTime(),
'start': start,
'offset': offset
};
return sendUpdate( room, 'state' );
};
/**
* Update the playlist of the specified room
* @param room - The room to update the state for
* @param uid - The UserID of the user that created the room (i.e. the owner)
* @param playlist - The playlist that is currently playing
* @returns true if update succeeded
*/
const updatePlaylist = ( room: string, uid: string, playlist: PlaylistSongs ) => {
if ( !rooms[room] || rooms[room].owner !== uid ) return false;
rooms[room].playlist = {
'playlist': playlist,
'lastUpdate': new Date().getTime()
};
return sendUpdate( room, 'playlist' );
};
const sendUpdate = ( room: string, kind: 'state' | 'playlist' ) => {
const roomObject = rooms[room];
if ( !roomObject ) return false;
roomObject.clients.forEach( client => client.response.write( `data: json:${ JSON.stringify( {
'type': kind,
'data': roomObject[kind]
} ) }\n\n` ) );
return true;
};
/**
* Send an update from the trackking system to all admin clients
* @param room - The room to send it to
* @param update - The update to send
*/
const sendTrackingUpdate = ( room: string, update: string ) => {
if ( !rooms[room] ) return false;
rooms[room].trackingClients.forEach( client => client.response.write( `data: ${ update }\n\n` ) );
};
export default {
get,
create,
close,
updateState,
updatePlaylist,
sendTrackingUpdate,
addClient,
removeClient
};
+33
View File
@@ -0,0 +1,33 @@
import {
PlaylistSongs
} from '../../dtype/file';
import {
Response
} from 'express';
export interface Client {
'id': string;
'response': Response;
}
export interface Room {
'playlist': {
'lastUpdate': number;
'playlist': PlaylistSongs;
}
'state': {
'index': number;
'start': number;
'playing': boolean;
'lastUpdate': number;
'offset': number;
};
'owner': string;
'clients': Client[];
'trackingClients': Client[];
}
export interface RoomStore {
[id: string]: Room
}
+40
View File
@@ -0,0 +1,40 @@
import {
Config
} from '../../dtype/config';
import express from 'express';
import {
generateToken
} from '../../token';
import rooms from '.';
export const sseMiddleware = ( kind: 'client' | 'trackingClient', config?: Config ) => {
return ( request: express.Request, response: express.Response ) => {
if ( typeof request.params.id !== 'string' )
return response.sendStatus( 400 );
const room = rooms.get( request.params.id );
if ( !room ) return response.sendStatus( 404 );
response.writeHead( 200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
} );
response.status( 200 );
response.flushHeaders();
if ( kind === 'trackingClient' || config?.clientMode === 'poll' )
response.write( 'data: use-poll\n\n' );
else
response.write( 'data: connected\n\n' );
const token = generateToken( 20 );
rooms.addClient( request.params.id, token, kind, response );
request.on( 'close', () => {
rooms.removeClient( request.params.id as string, token, kind );
} );
};
};
+56
View File
@@ -0,0 +1,56 @@
import {
readFile,
stat,
writeFile
} from 'node:fs';
import {
UserPlaylistFile
} from '../../dtype/file';
import path from 'node:path';
export const getUserFile = async ( uid: string ): Promise<UserPlaylistFile> => {
return new Promise( ( resolve, reject ) => {
readFile( getUserFilePath( uid ), ( err, data ) => {
if ( err ) return reject( err );
resolve( JSON.parse( String( data ) ) as UserPlaylistFile );
} );
} );
};
const createUserFile = async ( uid: string ): Promise<void> => {
writeUserFile( uid, {
'playlists': [],
'userid': uid,
'version': '1'
} );
};
export const getUserFilePath = ( uid: string ): string => {
return path.join( __dirname, '/../../../data/', uid + '.json' );
};
export const testUserFileExists = async ( uid: string ): Promise<boolean> => {
return new Promise( resolve => {
stat( getUserFilePath( uid ), err => {
if ( err ) return resolve( false );
resolve( true );
} );
} );
};
export const writeUserFile = async ( uid: string, file: UserPlaylistFile ) => {
writeFile( getUserFilePath( uid ), JSON.stringify( file ), err => {
if ( err ) return Promise.reject( err );
else Promise.resolve();
} );
};
export default {
getUserFilePath,
getUserFile,
writeUserFile,
testUserFileExists,
createUserFile
};
+46
View File
@@ -0,0 +1,46 @@
import {
getLoginSdk,
getStoreSdk
} from '../../sdk';
import express from 'express';
const cache: {
[key: string]: boolean
} = {};
export const getOwnershipManager = ( foss: boolean ) => {
const storeSdk = getStoreSdk( foss );
const sdk = getLoginSdk( foss );
const getOwned = async ( request: express.Request ) => {
const uid = sdk.getUID( request )!;
if ( cache[ uid ] ) {
return true;
} else {
const now = new Date().getTime();
if ( ( await storeSdk.getSubscriptions( uid ) ).findIndex(
sub => ( sub.id === 'com.janishutz.MusicPlayer.subscription' || sub.id === 'com.janishutz.MusicPlayer.subscription-month' ) && sub.expires - now > 0
) > -1 ) {
cache[ uid ] = true;
return true;
} else {
return true;
}
}
};
const middleware = () => {
return async ( request: express.Request, response: express.Response, next: express.NextFunction ) => {
if ( !await getOwned( request ) ) response.sendStatus( 402 );
else next();
};
};
return {
getOwned,
middleware
};
};
+50
View File
@@ -0,0 +1,50 @@
import corsManager from '../corsManager';
import express from 'express';
import fs from 'fs';
import {
getLoginSdk
} from '../sdk';
import {
getOwnershipManager
} from '../manager/users/ownership';
import jwt from 'jsonwebtoken';
import path from 'path';
const routes = ( app: express.Application, foss: boolean ) => {
const sdk = getLoginSdk( foss );
const privateKey = fs.readFileSync( path.join(
__dirname,
'/../config/apple_private_key.p8'
) ).toString();
const musicApiConfig = JSON.parse( fs.readFileSync( path.join(
__dirname,
'/../config/apple-music-api.config.secret.json'
) ).toString() );
const ownership = getOwnershipManager( foss );
app.get(
'/dev-token',
corsManager.middleware( false ),
sdk.loginCheck(),
ownership.middleware(),
( _request: express.Request, response: express.Response ) => {
// sign dev token
const now = new Date().getTime();
const tomorrow = now + ( 24 * 3600 * 1000 );
const jwtToken = jwt.sign( {
'iss': musicApiConfig.teamID,
'iat': Math.floor( now / 1000 ),
'exp': Math.floor( tomorrow / 1000 )
}, privateKey, {
'algorithm': 'ES256',
'keyid': musicApiConfig.keyID
} );
response.send( jwtToken );
}
);
};
export default {
routes
};
+52
View File
@@ -0,0 +1,52 @@
import {
Config
} from '../../dtype/config';
import express from 'express';
import {
getLoginSdk
} from '../../sdk';
import {
getOwnershipManager
} from '../../manager/users/ownership';
import rooms from '../../manager/rooms';
import tracking from './tracking';
import update from './update';
const routes = ( app: express.Application, foss: boolean, config: Config ) => {
const sdk = getLoginSdk( foss );
const ownership = getOwnershipManager( foss );
tracking.routes( app, foss );
update.routes( app, foss, config );
app.get(
'/room/create',
sdk.loginCheck(),
ownership.middleware(),
( request: express.Request, response: express.Response ) => {
if ( !request.query.room || !( /^[a-zA-Z0-9-]{3,20}/ ).test( String( request.query.room ) ) ) return response.sendStatus( 400 );
if ( rooms.create( String( request.query.room ), sdk.getUID( request )! ) )
response.sendStatus( 200 );
else
response.sendStatus( 409 );
}
);
app.get(
'/room/:id/close',
sdk.loginCheck(),
( request: express.Request, response: express.Response ) => {
if ( typeof request.params.room !== 'string' ) return response.sendStatus( 400 );
if ( rooms.close( String( request.query.room ), sdk.getUID( request )! ) )
response.sendStatus( 200 );
else
response.sendStatus( 500 );
}
);
};
export default {
routes
};
+48
View File
@@ -0,0 +1,48 @@
import corsManager from '../../corsManager';
import express from 'express';
import {
getLoginSdk
} from '../../sdk';
import rooms from '../../manager/rooms';
import {
sseMiddleware
} from '../../manager/rooms/sse';
const tackingUpdate = ( message: string ) => {
return ( request: express.Request, response: express.Response ) => {
if ( typeof request.params.id === 'string' ) {
if ( rooms.sendTrackingUpdate( request.params.id, message ) )
response.sendStatus( 200 );
else
response.sendStatus( 500 );
} else
response.sendStatus( 400 );
};
};
const routes = ( app: express.Application, foss: boolean ) => {
const sdk = getLoginSdk( foss );
app.get(
'/room/:id/tracking/exit',
corsManager.middleware( false ),
tackingUpdate( 'exit' )
);
app.get(
'/room/:id/tracking/ping',
corsManager.middleware( false ),
tackingUpdate( 'ping' )
);
app.get(
'/room/:id/admin',
corsManager.middleware( false ),
sdk.loginCheck(),
sseMiddleware( 'trackingClient' )
);
};
export default {
routes
};
+98
View File
@@ -0,0 +1,98 @@
import {
Config
} from '../../dtype/config';
import bodyParser from 'body-parser';
import corsManager from '../../corsManager';
import express from 'express';
import {
getLoginSdk
} from '../../sdk';
import logger from '../../logger';
import rooms from '../../manager/rooms';
import {
sseMiddleware
} from '../../manager/rooms/sse';
const routes = ( app: express.Application, foss: boolean, config: Config ) => {
const sdk = getLoginSdk( foss );
app.get( '/room/:id/connect', corsManager.middleware( false ), sseMiddleware( 'client', config ) );
app.get( '/room/:id/poll', corsManager.middleware( false ), ( request: express.Request, response: express.Response ) => {
if ( typeof request.params.id !== 'string' )
return response.sendStatus( 400 );
const room = rooms.get( request.params.id );
if ( !room ) response.sendStatus( 404 );
const lastRequest = parseInt( String( request.query.last ) ) ?? 0;
response.send(
JSON.stringify( {
'state': room?.state,
'playlist': ( lastRequest < room!.playlist!.lastUpdate || isNaN( lastRequest ) ) ? room!.playlist.playlist : undefined
} )
);
} );
app.options( '/room/:id/update/playlist', corsManager.middleware( false ) );
app.post(
'/room/:id/update/playlist',
corsManager.middleware( false ),
sdk.loginCheck(),
bodyParser.json(),
( request: express.Request, response: express.Response ) => {
if ( typeof request.params.id !== 'string' )
return response.sendStatus( 400 );
try {
if ( rooms.updatePlaylist(
request.params.id,
sdk.getUID( request )!,
request.body.playlist ?? []
) )
response.sendStatus( 200 );
else
response.sendStatus( 400 );
} catch ( err ) {
logger.error( 'Failed sending updated playlists with error', err );
response.sendStatus( 500 );
}
}
);
app.options( '/room/:id/update/state', corsManager.middleware( false ) );
app.post(
'/room/:id/update/state',
corsManager.middleware( false ),
sdk.loginCheck(),
bodyParser.json(),
( request: express.Request, response: express.Response ) => {
if ( typeof request.params.id !== 'string' ) {
return response.sendStatus( 400 );
}
try {
if ( rooms.updateState(
request.params.id,
sdk.getUID( request )!,
request.body.playing ?? false,
request.body.index ?? -1,
request.body.start ?? new Date().getTime(),
request.body.offset ?? 0
) )
response.sendStatus( 200 );
else
response.sendStatus( 400 );
} catch ( err ) {
logger.error( 'Failed sending updated state with error', err );
response.sendStatus( 500 );
}
}
);
};
export default {
routes
};
+73
View File
@@ -0,0 +1,73 @@
import {
Playlist,
UserPlaylistFile
} from '../../dtype/file';
import {
getUserFile,
writeUserFile
} from '../../manager/users';
import bodyParser from 'body-parser';
import express from 'express';
import {
getLoginSdk
} from '../../sdk';
import {
getOwnershipManager
} from '../../manager/users/ownership';
import logger from '../../logger';
const routes = ( app: express.Application, foss: boolean ) => {
const sdk = getLoginSdk( foss );
const ownership = getOwnershipManager( foss );
app.get( '/user/owned', sdk.loginCheck(), async ( request: express.Request, response: express.Response ) => {
if ( await ownership.getOwned( request ) )
response.send( true );
else
response.send( true );
} );
app.get(
'/user/playlists',
sdk.loginCheck(),
async ( request: express.Request, response: express.Response ) => {
try {
const playlists = await getUserFile( sdk.getUID( request )! );
response.send( JSON.stringify( playlists.playlists ) );
} catch ( e ) {
logger.error( 'Failed retrieving user file with error', e );
}
}
);
app.post(
'/user/playlists',
sdk.loginCheck(),
ownership.middleware(),
bodyParser.json(),
async ( request: express.Request, response: express.Response ) => {
try {
const contents: UserPlaylistFile = {
'playlists': request.body as Playlist[],
'userid': sdk.getUID( request )!,
'version': '1'
};
try {
await writeUserFile( contents.userid, contents );
response.sendStatus( 200 );
} catch ( e ) {
logger.error( 'Failed updating user playlists', e );
response.sendStatus( 500 );
}
} catch ( e ) {
logger.error( 'Failed retrieving user file with error', e );
}
}
);
};
export default {
routes
};
+14
View File
@@ -0,0 +1,14 @@
import loginSdk from '@janishutz/login-sdk-server';
import loginSdkStub from '@janishutz/login-sdk-server-stubs';
import storeSdk from '@janishutz/store-sdk';
import storeSdkStub from './store-sdk-stub';
export const getLoginSdk = ( foss: boolean ) => {
if ( foss ) return loginSdkStub;
else return loginSdk;
};
export const getStoreSdk = ( foss: boolean ) => {
if ( foss ) return storeSdkStub;
else return storeSdk;
};
+24 -9
View File
@@ -1,15 +1,30 @@
interface StoreSDKConfig {
'backendURL': string;
'signingSecret': string;
'name': string;
'loglevel': 'debug' | 'info' | 'log' | 'warn' | 'error' | 'none';
}
interface SubscriptionData {
'id': string;
'status': string;
'expires': number;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getSubscriptions = ( _uid: string ) => {
return [
{
'id': 'com.janishutz.MusicPlayer.subscription',
'expires': new Date().getTime() + 200000,
'status': true
}
];
const getSubscriptions = async ( _uid: string ): Promise<SubscriptionData[]> => {
return [ {
'id': 'com.janishutz.MusicPlayer.subscription',
'expires': new Date().getTime() + 200000,
'status': 'active'
} ];
};
const configure = ( config: StoreSDKConfig ) => {
console.log( config );
};
export default {
getSubscriptions,
configure
};
+35
View File
@@ -0,0 +1,35 @@
import crypto from 'node:crypto';
/**
* Generate a token for e.g. login, etc
* @param length - The number of characters of the token
* @returns The generated token
*/
export const generateToken = ( length: number ): string => {
let token = '';
const min = 45;
const max = 122;
for ( let i = 0; i < length; i++ ) {
const buf = new Uint8Array( 1 );
crypto.getRandomValues( buf );
let randomNumber = Math.floor( ( buf[ 0 ] / 256 * ( max - min ) ) + min );
while (
( 58 < randomNumber && randomNumber < 63 )
|| ( 90 < randomNumber && randomNumber < 95 )
|| ( 95 < randomNumber && randomNumber < 97 )
) {
const buf = new Uint8Array( 1 );
crypto.getRandomValues( buf );
randomNumber = Math.floor( ( buf[ 0 ] / 256 * ( max - min ) ) + min );
}
token += String.fromCharCode( randomNumber );
}
return token;
};
+15
View File
@@ -0,0 +1,15 @@
FROM node:25-alpine3.21 AS build
# Frontend Build stage
WORKDIR /usr/src/build
COPY . /usr/src/build
RUN npm i
RUN npm run build
# Build final image
FROM nginx AS prod
COPY --from=build /usr/src/build/dist /usr/share/nginx/html
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 3000
+6 -3
View File
@@ -15,7 +15,9 @@
"@fortawesome/fontawesome-svg-core": "^7.3.1",
"@fortawesome/free-regular-svg-icons": "^7.3.1",
"@globalhive/vuejs-tour": "^3.0.1",
"@janishutz/login-sdk-browser": "^1.1.0",
"@kyvg/vue3-notification": "^3.4.2",
"music-metadata": "^11.15.0",
"nprogress": "^0.2.0",
"pinia": "^4.0.2",
"vue": "^3.5.40",
@@ -28,13 +30,14 @@
"@types/node": "^24.13.3",
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"eslint": "^10.9.1",
"eslint-plugin-vue": "^10.10.0",
"globals": "^17.11.0",
"musickitjs-v3-types": "^1.1.1",
"globals": "^17.12.0",
"musickitjs-v3-types": "^1.2.1",
"npm-run-all2": "^9.0.2",
"sass-embedded": "^1.103.1",
"typescript": "~6.0.0",
"typescript-eslint": "^8.67.0",
"typescript-eslint": "^8.69.0",
"vite": "^8.1.5",
"vite-plugin-vue-devtools": "^8.1.5",
"vue-tsc": "^3.3.7"
+35 -13
View File
@@ -1,4 +1,7 @@
<script setup lang="ts">
import {
Notifications
} from '@kyvg/vue3-notification';
import {
RouterView
} from 'vue-router';
@@ -6,38 +9,45 @@
ref
} from 'vue';
const theme = ref( '&#9788;' );
const theme = ref( 'dark' );
const changeTheme = () => {
if ( theme.value === '&#9789;' ) {
if ( theme.value === 'moon' ) {
document.documentElement.classList.remove( 'dark' );
document.documentElement.classList.add( 'light' );
localStorage.setItem( 'theme', '&#9788;' );
theme.value = '&#9788;';
} else if ( theme.value === '&#9788;' ) {
localStorage.setItem( 'theme', 'light' );
theme.value = 'sun';
} else if ( theme.value === 'sun' ) {
document.documentElement.classList.remove( 'light' );
document.documentElement.classList.add( 'dark' );
localStorage.setItem( 'theme', '&#9789;' );
theme.value = '&#9789;';
localStorage.setItem( 'theme', 'dark' );
theme.value = 'moon';
}
};
theme.value = localStorage.getItem( 'theme' ) ?? '';
if ( window.matchMedia( '(prefers-color-scheme: dark)' ).matches || theme.value === '&#9789;' ) {
if ( window.matchMedia( '(prefers-color-scheme: dark)' ).matches || theme.value === 'dark' ) {
document.documentElement.classList.add( 'dark' );
theme.value = '&#9789;';
theme.value = 'moon';
} else {
document.documentElement.classList.add( 'light' );
theme.value = '&#9788;';
theme.value = 'sun';
}
</script>
<template>
<div>
<notifications
position="top center"
:duration="5000"
class="notifications"
style="top: 20px;"
width="400px"
:max="3"
/>
<button id="themeSelector" title="Toggle between light and dark mode" @click="changeTheme();">
<!-- eslint-disable-next-line vue/no-v-html -->
<span class="material-symbols-outlined" v-html="theme"></span>
<i :class="['fa-solid', 'fa-' + theme]"></i>
</button>
<router-view id="main-view" v-slot="{ Component, route }">
<transition :name="route.meta.transition ? String( route.meta.transition ) : 'fade'" mode="out-in">
@@ -47,11 +57,23 @@
</div>
</template>
<style>
<style lang="scss">
body {
background-color: var( --background-color );
}
.notifications {
.vue-notification {
padding: 20px;
.notification-title {
font-size: 1rem;
}
.notification-text {
font-size: 0.75rem;
}
}
}
:root, :root.light {
--primary-color: #0a1520;
--secondary-color: white;
-60
View File
@@ -1,60 +0,0 @@
<script setup lang="ts">
import ImportTypePicker from '@/composables/ImportTypePicker.vue';
import PopupElement from '@/components/PopupElement.vue';
import player from '@/ts/player';
import {
sources
} from '@/ts/player/state';
const showPopup = defineModel<boolean>( {
'required': true
} );
const addSong = ( source: string ) => {
player.addSongFromSource( source );
showPopup.value = false;
};
</script>
<template>
<div>
<ImportTypePicker />
<PopupElement v-model="showPopup" show-close>
<h1>Add Song</h1>
<div class="song-sources">
<div v-for="(source, index) in sources" :key="index" @click="() => addSong( source.id )">
<i v-if="source.icon" :class="['fa-solid', 'fa-' + source.icon]"></i>
<p>{{ source.name }}</p>
</div>
</div>
</PopupElement>
</div>
</template>
<style lang="scss" scoped>
.song-sources {
display: flex;
flex-wrap: wrap;
width: 50vw;
height: 35vh;
justify-content: center;
overflow-y: scroll;
overflow-x: hidden;
>div {
width: 32%;
margin: 0.5%;
height: 50%;
background-color: var(--accent-background);
border-radius: 20px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
>.fa-solid {
font-size: 1.5rem;
}
}
}
</style>
-5
View File
@@ -1,5 +0,0 @@
<template>
<div>
Hello World
</div>
</template>
-16
View File
@@ -1,16 +0,0 @@
<script setup lang="ts">
import PopupElement from './PopupElement.vue';
const model = defineModel<boolean>( {
'required': true
} );
</script>
<template>
<div>
<PopupElement v-model="model" show-close>
<h2>Edit Song</h2>
<!-- TODO: Need a way to use the search feature to replace the song details, as of course as well text editors -->
</PopupElement>
</div>
</template>
@@ -0,0 +1,58 @@
<script setup lang="ts">
import {
queue,
queueIdx
} from '@/ts/player/state';
import CurrentSong from '../player/CurrentSong.vue';
import PlayerControls from '../player/PlayerControls.vue';
import QueueViewer from '../player/QueueViewer.vue';
</script>
<template>
<div class="player">
<div
class="panel"
>
<div class="current-song-wrapper">
<CurrentSong
v-model="queue[queueIdx]"
/>
</div>
<PlayerControls />
</div>
<div class="panel">
<QueueViewer />
</div>
</div>
</template>
<style lang="scss" scoped>
.player {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
.panel {
width: 45%;
margin-left: 2.5%;
margin-right: 2.5%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
>.current-song-wrapper {
margin-bottom: 1.5rem;
width: 100%;
height: 100%;
max-height: calc(100% - 15rem);
overflow: hidden;
}
}
}
</style>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import AssociationView from '@/composables/AssociationView.vue';
import PlayerComponent from './PlayerComponent.vue';
import SmallPlayerComponent from './SmallPlayerComponent.vue';
import {
fullPlayer
} from '@/ts/player/state';
const close = () => {
fullPlayer.value = false;
};
</script>
<template>
<div class="player-wrapper">
<AssociationView />
<SmallPlayerComponent v-model="fullPlayer" />
<div :class="['player-container', fullPlayer ? undefined : 'hidden']">
<i class="fa-solid fa-xmark" @click="close"></i>
<PlayerComponent />
</div>
</div>
</template>
<style lang="scss" scoped>
.player-container {
width: 100vw;
height: 100vh;
position: fixed;
bottom: 0;
left: 0;
background-color: var(--secondary-color);
transition: bottom 1s ease;
transition-delay: 0.25s;
overflow: hidden;
&.hidden {
transition-delay: 0s;
bottom: -100vh;
}
>.fa-xmark {
position: absolute;
top: 10px;
right: 10px;
font-size: 1.5rem;
cursor: pointer;
}
}
</style>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import UserPlaylists from '../playlists/UserPlaylists.vue';
</script>
<template>
<div class="playlist-main">
<h1>Playlists</h1>
<UserPlaylists />
</div>
</template>
<style lang="scss" scoped>
.playlist-main {
height: 100%;
width: 100%;
}
</style>
@@ -0,0 +1,142 @@
<script setup lang="ts">
import {
type ComputedRef,
computed
} from 'vue';
import {
isPlaying,
queue,
queueIdx
} from '@/ts/player/state';
import type {
Song
} from '@/ts/dtype/playlist';
import {
beautifyTime
} from '@/ts/util/time';
import {
playbackPercentage
} from '@/ts/player/status-tracking';
import player from '@/ts/player';
const closed = defineModel<boolean>( {
'required': true
} );
const open = () => {
closed.value = true;
};
const song: ComputedRef<Song> = computed( () => {
if ( queueIdx.value >= 0 && queue.value.length > queueIdx.value ) {
return queue.value[ queueIdx.value ]!;
} else {
return {
'artwork': '',
'additional-info': '',
'artist': 'No artist',
'duration': -1,
'identifier': 'nosong-ident',
'name': 'Not Playing',
'source': 'local'
};
}
} );
</script>
<template>
<div :class="['small-player', closed ? 'hidden' : undefined]">
<div>
<img
v-if="song.artwork"
:src="song.artwork"
alt="Song cover"
class="song-cover"
>
<i v-else class="fa-solid fa-music song-cover" @click="open"></i>
<div @click="open">
<h3>{{ song.name }}</h3>
<p>{{ song.artist }}</p>
</div>
<p @click="open">
{{ beautifyTime( playbackPercentage * song.duration ) }} / {{ beautifyTime( song.duration ) }}
</p>
<i v-if="!isPlaying" class="fa-solid fa-play" @click="player.play"></i>
<i v-else class="fa-solid fa-pause" @click="player.pause"></i>
<i class="fa-solid fa-forward-step" @click="player.next"></i>
</div>
</div>
</template>
<style lang="scss" scoped>
.small-player {
background-color: var(--secondary-color);
width: 80vw;
height: 4.5rem;
position: fixed;
left: 10vw;
bottom: 15px;
border-radius: 2rem;
overflow: hidden;
transition: bottom 0.5s ease;
transition-delay: 0.75s;
display: flex;
align-items: center;
justify-content: center;
&.hidden {
bottom: -8vh;
transition-delay: 0s;
}
>div {
display: flex;
align-items: center;
justify-content: center;
width: calc(100% - 6rem);
height: 100%;
>.song-cover {
display: flex;
justify-content: center;
align-items: center;
width: 3rem;
height: 3rem;
font-size: 2.5rem;
cursor: pointer;
margin-right: 30px;
}
>div {
cursor: pointer;
margin-right: auto;
display: flex;
align-items: flex-start;
justify-content: center;
flex-direction: column;
width: calc(100% - 20rem);
overflow-x: hidden;
height: 100%;
>h3 {
margin: 0;
}
>p {
margin: 0;
}
}
>p {
cursor: pointer;
margin-right: 15px;
width: max-content;
}
>.fa-solid {
font-size: 2rem;
cursor: pointer;
}
}
}
</style>
+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import type {
Song
} from '@/ts/dtype/playlist';
const song = defineModel<Song>( {
'required': false
} );
const props = defineProps<{
'showAdditionalInfo'?: boolean
}>();
</script>
<template>
<div class="current-song">
<div class="artwork">
<img
v-if="song?.artwork"
:src="song.artwork"
alt="Song cover"
class="song-cover"
>
<i v-else class="fa-solid fa-music song-cover"></i>
</div>
<div class="song-details">
<h1>
{{ song?.name ?? 'Not playing' }}
</h1>
<p>{{ song?.artist ?? 'No artist' }}</p>
<p v-if="props.showAdditionalInfo">
{{ song?.['additional-info'] }}
</p>
</div>
</div>
</template>
<style lang="scss" scoped>
.current-song {
width: 100%;
height: 100%;
position: relative;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
.artwork {
width: 100%;
height: 100%;
max-height: calc(100% - 9rem);
>img, .fa-solid {
height: 100%;
font-size: 40vh;
}
}
.song-details {
>* {
margin: 10px;
}
}
}
</style>
@@ -1,14 +1,20 @@
<script setup lang="ts">
import {
computed,
ref
} from 'vue';
import ProgressBar from './ProgressBar.vue';
import ShareManagement from './ShareManagement.vue';
import {
beautifyTime
} from '@/ts/util/time';
import messages from '@/ts/messages';
import player from '@/ts/player';
const playbackPercentage = player.playbackPercentage;
const duration = player.duration;
const repeatMode = player.repeat;
const shuffleMode = player.shuffle;
const showShareMenu = ref( false );
const seek = () => {
player.seekTo( playbackPercentage.value );
@@ -28,18 +34,26 @@
};
const openShareMenu = () => {
alert( 'Share menu not yet implemented' );
showShareMenu.value = true;
};
// TODO: Button availability
const current = computed( () => {
return beautifyTime( player.playbackPercentage.value * player.duration.value );
} );
const duration = computed( () => {
return beautifyTime( player.duration.value );
} );
messages.useRoomWatchers();
</script>
<template>
<div class="mp-player">
<ShareManagement v-model="showShareMenu" />
<div class="controls">
<i class="fa-solid fa-backward-step" @click="player.prev"></i>
<i class="fa-solid fa-arrow-rotate-left quick-seek" @click="player.back10"></i>
<div :class="['play-pause', 'paused']">
<div :class="['play-pause', player.isPlaying.value ? undefined : 'paused']">
<i class="fa-solid fa-play" @click="player.play"></i>
<i class="fa-solid fa-pause" @click="player.pause"></i>
</div>
@@ -48,12 +62,11 @@
</div>
<div class="time">
<!-- TODO: Probably needs to be a computed -->
<p class="current">
{{ beautifyTime( playbackPercentage * duration ) }}
{{ current }}
</p>
<p class="duration">
{{ beautifyTime( duration ) }}
{{ duration }}
</p>
</div>
<ProgressBar v-model="playbackPercentage" @move-end="seek" />
@@ -8,23 +8,35 @@
'required': true,
'default': 0.5
} );
const moveVal = ref( 0 );
const offset = ref( -1 );
const isMoving = ref( false );
const bar = useTemplateRef( 'bar' );
const props = defineProps<{
'disallowMove'?: boolean
}>();
const start = ( ev: MouseEvent ) => {
offset.value = ev.x - bar.value!.offsetLeft;
val.value = offset.value / bar.value!.clientWidth;
if ( props.disallowMove ) return;
offset.value = bar.value!.getBoundingClientRect().x;
isMoving.value = true;
moveVal.value = ( ev.x - offset.value ) / bar.value!.clientWidth;
emit( 'move-start' );
};
const move = ( ev: MouseEvent ) => {
if ( offset.value > -1 ) {
val.value = Math.max( 0, Math.min( ev.x / bar.value!.clientWidth, 1 ) );
if ( isMoving.value ) {
moveVal.value = Math.max( 0, Math.min( ( ev.x - offset.value ) / bar.value!.clientWidth, 1 ) );
}
};
const end = () => {
const end = ( ev: MouseEvent ) => {
if ( !isMoving.value ) return;
val.value = ( ev.x - offset.value ) / bar.value!.clientWidth;
offset.value = -1;
isMoving.value = false;
emit( 'move-end' );
};
@@ -37,10 +49,10 @@
<template>
<div class="progressbar">
<div ref="bar" class="back">
<div :style="`width: ${ val * 100 }%;`"></div>
<div :style="`width: ${ isMoving ? moveVal * 100 : val * 100 }%;`"></div>
</div>
<div
:class="['click-target', offset >= 0 ? 'active' : undefined]"
:class="['click-target', offset >= 0 ? 'active' : undefined, props.disallowMove ? 'disallowed' : undefined]"
@mousedown="start"
@mousemove="move"
@mouseup="end"
@@ -5,26 +5,31 @@
computed,
ref
} from 'vue';
import AddSong from './AddSong.vue';
import AddSong from '../popups/AddSong.vue';
import type {
Song
} from '@/ts/dtype/playlist';
import SongEditor from './SongEditor.vue';
import SortableList from './SortableList.vue';
import SongEditor from '../popups/SongEditor.vue';
import SortableList from '../SortableList.vue';
import {
beautifyTime
} from '@/ts/util/time';
import player from '@/ts/player';
import {
queueIdx
} from '@/ts/player/state';
import {
savePlaylist
} from '@/ts/userPlaylists/save';
const queue: WritableComputedRef<Song[]> = computed( {
get () {
return player.queue.value.slice( player.queueIdx.value );
return player.queue.value.slice( player.queueIdx.value + 1 );
},
set ( val ) {
player.queue.value = player.queue.value.slice( 0, player.queueIdx.value ).concat( val );
player.queue.value = player.queue.value.slice( 0, player.queueIdx.value + 1 ).concat( val );
}
} );
const isPlaying = player.isPlaying;
const showAddSong = ref( false );
const showEditSong = ref( false );
const editingSong: Ref<null | Song> = ref( null );
@@ -35,16 +40,16 @@
const editSong = ( idx: number ) => {
showEditSong.value = true;
editingSong.value = player.queue.value[ idx ]!;
editingSong.value = player.queue.value[ idx + queueIdx.value + 1 ]!;
};
const deleteSong = ( idx: number ) => {
player.removeSong( idx );
player.removeSong( idx + queueIdx.value + 1 );
};
</script>
<template>
<div>
<div class="queue-viewer">
<div>
<button @click="addSong">
<i class="fa-solid fa-plus"></i>
@@ -54,19 +59,18 @@
<i class="fa-solid fa-xmark"></i>
Clear
</button>
<button>
<button @click="editSong( -1 )">
<i class="fa-solid fa-pen-to-square"></i>
Edit Current
</button>
<button @click="savePlaylist">
<i class="fa-solid fa-save"></i>
Save
</button>
<!-- TODO: Should only appear when sharing -->
<button>
<i class="fa-solid fa-paper-plane"></i>
Transmit
</button>
</div>
<SongEditor v-model="showEditSong" editing-song="" />
<SongEditor v-model="showEditSong" :song="editingSong" />
<AddSong v-model="showAddSong" />
<div>
<div v-if="queue.length > 0" class="queue-container">
<SortableList v-slot="{ item: song, index }" v-model="queue">
<div class="song-list-element">
<div class="song-cover-wrapper">
@@ -77,19 +81,8 @@
class="song-cover"
>
<i v-else class="fa-solid fa-music song-cover"></i>
<div v-if="index === 0" class="play-overlay">
<div v-if="isPlaying" class="playing-symbols">
<div id="bar-1" class="playing-bar"></div>
<div id="bar-2" class="playing-bar"></div>
<div id="bar-3" class="playing-bar"></div>
</div>
<i
v-else
class="fa-solid fa-pause"
></i>
</div>
<div v-else class="play-overlay hover">
<i class="fa-solid fa-play" @click="() => player.playIndex( index )"></i>
<div class="play-overlay hover">
<i class="fa-solid fa-play" @click="() => player.playIndex( index + queueIdx + 1 )"></i>
</div>
</div>
<div class="song-details">
@@ -105,6 +98,16 @@
</div>
</SortableList>
</div>
<div v-else class="queue-container">
<p>
No more songs in queue
</p>
<button @click="addSong">
<i class="fa-solid fa-plus"></i>
Add
</button>
</div>
</div>
</template>
@@ -0,0 +1,52 @@
<script setup lang="ts">
import messages, {
isConnected
} from '@/ts/messages';
import PopupElement from '../popups/PopupElement.vue';
import {
ref
} from 'vue';
const showPopup = defineModel<boolean>( {
'required': true
} );
const shareName = ref( '' );
const useAntiTamper = ref( false );
const errorMessage = ref( '' );
const startShare = async () => {
if ( !await messages.createRoom( shareName.value, useAntiTamper.value ) ) {
errorMessage.value = 'Invalid room name';
}
};
const stopShare = () => {
messages.closeRoom();
};
</script>
<template>
<div>
<PopupElement v-model="showPopup" show-close>
<h2>Share</h2>
<div v-if="!isConnected">
<p>
You can use a share to show what you are currently listening to (and the progress) on a page.
</p>
<p>{{ errorMessage }}</p>
<input v-model="shareName" type="text">
<button @click="startShare">
Create Share
</button>
</div>
<div v-else>
<!-- TODO: Need to explain and add controls -->
<!-- TODO: How to handle anti-tamper? -->
<p>Connected</p>
<button @click="stopShare">
End share
</button>
</div>
</PopupElement>
</div>
</template>
@@ -0,0 +1,86 @@
<script setup lang="ts">
import PopupElement from '../popups/PopupElement.vue';
import {
ref
} from 'vue';
const showPopup = defineModel<boolean>( {
'required': true
} );
const addPlaylist = () => {
showPopup.value = false;
emit( 'add-playlist', playlistName.value );
};
const playlistName = ref( '' );
const emit = defineEmits<{
( e: 'add-playlist', name: string ): void;
}>();
</script>
<template>
<div>
<PopupElement v-model="showPopup" show-close>
<div class="title">
<h1>Add Playlist</h1>
</div>
<input v-model="playlistName" type="text" placeholder="Playlist name">
<br>
<button @click="addPlaylist">
<i class="fa-solid fa-plus"></i>
Add Playlist
</button>
</PopupElement>
</div>
</template>
<style lang="scss" scoped>
.title {
>h1 {
margin-bottom: 5px;
}
>p {
margin: 0;
margin-bottom: 10px;
}
}
.song-sources {
display: flex;
flex-wrap: wrap;
width: 50vw;
height: 40vh;
justify-content: center;
overflow-y: scroll;
overflow-x: hidden;
>div {
width: 45%;
margin: 0.5%;
height: 60%;
background-color: var(--accent-background);
border-radius: 20px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
flex-direction: column;
>div {
display: flex;
justify-content: center;
align-items: center;
>.fa-solid {
font-size: 1.5rem;
}
}
>.not-auth-notice {
font-size: 0.6rem;
margin: 0;
width: 70%;
}
}
}
</style>
@@ -0,0 +1,114 @@
<script setup lang="ts">
import {
addPlaylist,
removePlaylist,
selectPlaylist
} from '@/ts/userPlaylists';
import {
editingPlaylists,
playlists
} from '@/ts/userPlaylists/state';
import {
getPlaylists,
savePlaylists
} from '@/ts/userPlaylists/save';
import {
onMounted,
ref
} from 'vue';
import AddPlaylist from './AddPlaylist.vue';
import {
UnownedError
} from '@/ts/request';
import router from '@/router';
const checkingStatus = ref( true );
const dots = ref( 0 );
const showAddPlaylist = ref( false );
let interval = -1;
const loadPlaylists = async () => {
if ( interval < 0 ) {
interval = setInterval( () => {
dots.value = ( dots.value + 1 ) % 4;
}, 500 );
}
try {
await getPlaylists();
} catch ( e ) {
if ( e instanceof UnownedError ) {
router.push( '/get' );
}
}
checkingStatus.value = false;
try {
clearInterval( interval );
interval = -1;
} catch { /* Empty */ }
};
onMounted( () => {
loadPlaylists();
} );
onMounted( () => {} );
const openAddPlaylistPopup = () => {
showAddPlaylist.value = true;
};
const togglePlaylistEditing = ( idx: number ) => {
editingPlaylists.value[ idx ] = !editingPlaylists.value[ idx ];
};
</script>
<template>
<div class="playlists">
<AddPlaylist v-model="showAddPlaylist" @add-playlist="addPlaylist" />
<div v-if="checkingStatus" class="playlist-wrapper">
Loading{{ '.'.repeat( dots ) }}
</div>
<div v-else-if="playlists.length === 0" class="playlist-wrapper">
No playlists
<button @click="openAddPlaylistPopup">
<i class="fa-solid fa-plus"></i>
Add one
</button>
</div>
<div v-else class="playlist-wrapper">
<div class="playlist-actions">
<button @click="openAddPlaylistPopup">
<i class="fa-solid fa-plus"></i>
Add Playlist
</button>
<button @click="savePlaylists">
<i class="fa-solid fa-floppy-disk"></i>
Save Changes
</button>
<button @click="loadPlaylists">
<i class="fa-solid fa-rotate"></i>
Undo unsaved changes
</button>
</div>
<div class="playlist-container">
<div v-for="(playlist, index) in playlists" :key="index" class="playlist">
<i class="fa-solid fa-circle-play" @click="() => selectPlaylist( index )"></i>
<input v-if="editingPlaylists[ index ]" v-model="playlist.name" type="text">
<h2 v-else @click="() => selectPlaylist( index )">
{{ playlist.name }}
</h2>
<i class="fa-solid fa-pen-to-square" @click="() => togglePlaylistEditing( index )"></i>
<i class="fa-solid fa-trash" @click="() => removePlaylist( index )"></i>
</div>
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
@use '@/scss/components/playlists.scss';
</style>
+93
View File
@@ -0,0 +1,93 @@
<script setup lang="ts">
import DiskLoader from '@/composables/DiskLoader.vue';
import ImportTypePicker from '@/composables/ImportTypePicker.vue';
import PopupElement from './PopupElement.vue';
import player from '@/ts/player';
import {
sources
} from '@/ts/player/state';
const showPopup = defineModel<boolean>( {
'required': true
} );
const addSong = async ( source: string ) => {
if ( await player.addSongFromSource( source ) ) {
showPopup.value = false;
}
};
</script>
<template>
<div>
<ImportTypePicker />
<DiskLoader />
<PopupElement v-model="showPopup" show-close>
<div class="title">
<h1>Add Song(s)</h1>
<p>Pick the source of your songs</p>
</div>
<div class="song-sources">
<div v-for="(source, index) in sources" :key="index" @click="() => addSong( source.id )">
<div>
<i v-if="source.icon" :class="['fa-solid', 'fa-' + source.icon]"></i>
<p>{{ source.name }}</p>
</div>
<p v-if="!source.authorized.value" class="not-auth-notice">
You have not yet logged into this source. Clicking this will start login
</p>
</div>
</div>
</PopupElement>
</div>
</template>
<style lang="scss" scoped>
.title {
>h1 {
margin-bottom: 5px;
}
>p {
margin: 0;
margin-bottom: 10px;
}
}
.song-sources {
display: flex;
flex-wrap: wrap;
width: 50vw;
height: 40vh;
justify-content: center;
overflow-y: scroll;
overflow-x: hidden;
>div {
width: 45%;
margin: 0.5%;
height: 60%;
background-color: var(--accent-background);
border-radius: 20px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
flex-direction: column;
>div {
display: flex;
justify-content: center;
align-items: center;
>.fa-solid {
font-size: 1.5rem;
}
}
>.not-auth-notice {
font-size: 0.6rem;
margin: 0;
width: 70%;
}
}
}
</style>
@@ -33,6 +33,7 @@
align-items: center;
z-index: 1000;
transition-delay: 0;
overflow: hidden;
.popup-backdrop {
width: 100vw;
@@ -42,7 +43,7 @@
top: 0;
left: 0;
overflow: hidden;
transition: all 0.5s;
transition: all 0.25s;
}
.popup-main {
@@ -53,7 +54,7 @@
border-radius: 20px;
transform: scale(1);
position: relative;
overflow-y: scroll;
overflow: hidden;
display: block;
transition: transform 0.25s ease, opacity 0.25s ease;
@@ -69,7 +70,7 @@
&.hidden {
top: -100vh;
transition-delay: 0.5s;
transition-delay: 0.25s;
.popup-main {
transform: scale(1.25);
+76
View File
@@ -0,0 +1,76 @@
<script setup lang="ts">
import {
type Ref, ref,
watch
} from 'vue';
import PopupElement from './PopupElement.vue';
import type {
Song
} from '@/ts/dtype/playlist';
import player from '@/ts/player';
const model = defineModel<boolean>( {
'required': true
} );
const props = defineProps<{
'song': Song | null
}>();
const localSong: Ref<Song> = ref( {
'name': '',
'artist': '',
'artwork': '',
'additional-info': '',
'duration': -1,
'identifier': '',
'source': 'local'
} );
watch( props, () => {
if ( props.song )
localSong.value = props.song;
} );
const search = () => {
player.addSongFromSource( 'applemusic', ( songs: Song[] ) => {
const song = songs[ 0 ];
if ( !song ) return;
localSong.value.artist = song.artist;
localSong.value.artwork = song.artwork;
localSong.value.name = song.name;
}, true );
};
const save = () => {
model.value = false;
document.dispatchEvent( new CustomEvent( 'musicplayer:update' ) );
};
</script>
<template>
<div>
<PopupElement v-model="model" show-close>
<h2>Edit Song</h2>
<button @click="search">
Search song on Apple Music
</button>
<label for="song-name">Song title</label>
<input id="song-name" v-model="localSong.name" type="text">
<label for="song-artist">Artist</label>
<input id="song-artist" v-model="localSong.artist" type="text">
<label for="song-artwork">Artwork URL</label>
<input id="song-artwork" v-model="localSong.artwork" type="text">
<label for="song-add-info">Additional Info</label>
<input id="song-add-info" v-model="localSong['additional-info']" type="text">
<button @click="save">
Save
</button>
</PopupElement>
</div>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import PopupElement from '../popups/PopupElement.vue';
const show = defineModel<boolean>();
const props = defineProps<{
'title': string;
'message'?: string;
}>();
const close = () => {
show.value = false;
};
</script>
<template>
<div>
<PopupElement v-model="show">
<h2>{{ props.title }}</h2>
<p>{{ props.message }}</p>
<button @click="close">
Ok
</button>
</PopupElement>
</div>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import PopupElement from '../popups/PopupElement.vue';
const show = defineModel<boolean>();
const close = () => {
show.value = false;
};
</script>
<template>
<div>
<!-- TODO: Beacon request when exiting browser (and confirm popup for that!) -->
<PopupElement v-model="show">
<h2>Settings</h2>
<button @click="close">
Ok
</button>
</PopupElement>
</div>
</template>
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import {
currentQueue,
currentQueueIdx,
playbackTime,
showArtworks
} from '@/ts/shared/state';
import {
computed
} from 'vue';
const songs = computed( () => currentQueue.value?.slice( currentQueueIdx.value + 1 ) ?? [] );
const timeToPlay = computed( () => {
return ( idx: number ) => {
let total = 0;
for ( let i = 0; i < idx; i++ ) {
total += songs.value[ i ]!.duration;
}
total += currentQueue.value[ currentQueueIdx.value ]?.duration ?? 0;
total -= playbackTime.value;
return Math.ceil( total / 60 );
};
} );
</script>
<template>
<div class="queue-viewer">
<div class="queue-container">
<div v-if="songs.length > 0" class="queue-scroll">
<div v-for="(song, index) in songs" :key="index" class="song-list-element">
<div class="song-cover-wrapper">
<img
v-if="song.artwork && showArtworks"
:src="song.artwork"
alt="Song cover"
class="song-cover"
>
<i v-else class="fa-solid fa-music song-cover"></i>
</div>
<div class="song-details">
<h3>{{ song.name }}</h3>
<p>{{ song.artist }}</p>
<p>{{ song['additional-info'] }}</p>
</div>
<div class="song-actions">
<p>In {{ '<' + timeToPlay( index ) }}min</p>
</div>
</div>
</div>
<div v-else class="queue-empty">
No upcoming songs
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
@use '@/scss/components/queue.scss';
.queue-scroll {
height: 100%;
width: 100%;
margin-top: 20px;
justify-content: flex-start !important;
overflow-y: scroll;
}
</style>
+135
View File
@@ -0,0 +1,135 @@
<script setup lang="ts">
import {
associationOpts,
associationResults,
isAnalyzing,
isShowingAssociationManager,
needsFiles,
saveAssociations
} from './associationManager';
import {
fullPlayer,
queue
} from '@/ts/player/state';
import {
onMounted,
useTemplateRef
} from 'vue';
import PopupElement from '@/components/popups/PopupElement.vue';
import player from '@/ts/player';
const fileinput = useTemplateRef( 'fileinput' );
onMounted( () => {
fileinput.value?.addEventListener( 'change', async () => {
if ( fileinput.value && fileinput.value.files ) {
await associationOpts.value?.get( fileinput.value.files );
}
} );
} );
const deleteSong = ( idx: number ) => {
const id = associationResults.value[ idx ]!.song.identifier;
for ( let i = 0; i < queue.value.length; i++ ) {
const song = queue.value[ i ]!;
if ( song.identifier === id ) {
player.removeSong( i );
return;
}
}
associationResults.value.splice( idx, 1 );
};
const cancel = () => {
player.clearQueue();
isShowingAssociationManager.value = false;
fullPlayer.value = false;
};
const retry = () => {
associationResults.value = [];
isAnalyzing.value = false;
needsFiles.value = true;
};
</script>
<template>
<div>
<PopupElement v-model="isShowingAssociationManager">
<h2>Load from disk</h2>
<div v-if="needsFiles">
<p>Some songs in this playlist require local files.</p>
<!-- TODO: probably need to list songs here somehow -->
<input
ref="fileinput"
type="file"
multiple
:accept="associationOpts?.mime ?? '*'"
>
</div>
<div v-if="needsFiles && !isAnalyzing && associationResults.length > 0" class="association-wrapper">
<button @click="saveAssociations">
Save
</button>
<div v-for="(result, index) in associationResults" :key="index" class="association">
<p>
<b>{{ result.song.name.length > 30 ? result.song.name.slice( 0, 30 ) + '...' : result.song.name }}</b>
by
<i>{{ result.song.artist.length > 20 ? result.song.artist.slice( 0, 20 ) + '...' : result.song.artist }}</i>
</p>
<select v-if="result.match === 'multiple'">
<option v-for="(file, idx) in result.possibleFiles" :key="idx" :value="idx">
{{ file.name }}
</option>
</select>
<div v-else-if="result.match === 'none'">
<p>
No match
</p>
<i class="fa-solid fa-trash" @click="() => deleteSong( index )"></i>
</div>
</div>
</div>
<div v-else-if="associationResults.length === 0"></div>
<div v-else>
An error occurred. Please try again
<button @click="retry">
Retry
</button>
</div>
<button @click="cancel">
Cancel
</button>
</PopupElement>
</div>
</template>
<style lang="scss" scoped>
.association-wrapper {
width: 60vw;
height: 50vh;
overflow-x: hidden;
overflow-y: scroll;
.association {
display: flex;
justify-content: center;
align-items: center;
height: 3rem;
>div, select {
display: flex;
margin-left: auto;
justify-content: center;
align-items: center;
>p {
margin-right: 10px;
}
}
}
}
</style>
+38 -2
View File
@@ -1,14 +1,50 @@
<script setup lang="ts">
import PopupElement from '@/components/PopupElement.vue';
import {
diskLoaderOpts,
isShowingDiskLoader
} from './diskLoader';
import {
onMounted,
ref,
useTemplateRef
} from 'vue';
import PopupElement from '@/components/popups/PopupElement.vue';
const fileinput = useTemplateRef( 'fileinput' );
const progress = ref( -1 );
onMounted( () => {
fileinput.value?.addEventListener( 'change', async () => {
if ( fileinput.value && fileinput.value.files ) {
progress.value = 0;
await diskLoaderOpts.value?.process( fileinput.value.files, ( curr: number ) => {
progress.value = curr;
} );
isShowingDiskLoader.value = false;
setTimeout( () => {
progress.value = -1;
}, 1000 );
}
} );
} );
</script>
<template>
<div>
<PopupElement v-model="isShowingDiskLoader" show-close>
<h3>Load from disk</h3>
<h2>Load from disk</h2>
<input
ref="fileinput"
type="file"
multiple
:accept="diskLoaderOpts?.mime ?? '*'"
>
<div v-if="progress >= 0">
<p style="margin-bottom: 0;">
Analyzing, please wait
</p>
<progress :value="progress" max="1"></progress>
</div>
</PopupElement>
</div>
</template>
+1 -1
View File
@@ -4,7 +4,7 @@
importers,
isShowingImportTypePicker
} from './importTypePicker';
import PopupElement from '@/components/PopupElement.vue';
import PopupElement from '@/components/popups/PopupElement.vue';
import SearchView from './SearchView.vue';
import {
openDiskLoaderInterface
+19 -15
View File
@@ -1,19 +1,15 @@
<script setup lang="ts">
import {
type Ref,
ref
} from 'vue';
import {
isShowingSearchView,
query,
results,
searchOpts
} from './searchManager';
import PopupElement from '@/components/PopupElement.vue';
import type {
Song
} from '@/ts/dtype/playlist';
import PopupElement from '@/components/popups/PopupElement.vue';
import {
ref
} from 'vue';
const results: Ref<Song[]> = ref( [] );
const query = ref( '' );
const isSearching = ref( false );
const addedIndex = ref( -1 );
@@ -23,13 +19,12 @@
const search = ( ev: KeyboardEvent ) => {
if ( ev.key === 'Enter' ) {
// TODO: If no new input, instead of searching, add first song
try {
clearTimeout( timeout );
} catch { /* empty */ }
doSearch();
} else if ( query.value.length > 2 ) {
} else if ( query.value.length > ( searchOpts.value?.minChars ?? 0 ) - 1 ) {
try {
clearTimeout( timeout );
} catch { /* empty */ }
@@ -43,7 +38,7 @@
isSearching.value = true;
searchedForQuery = query.value;
results.value = await searchOpts.value?.search( query.value ) ?? [];
results.value = await searchOpts.value?.search( query.value, 0 ) ?? [];
isSearching.value = false;
};
@@ -54,6 +49,10 @@
addedIndex.value = idx;
searchOpts.value?.addSelected( idx );
if ( searchOpts.value?.autoClose )
isShowingSearchView.value = false;
addedTimeout = setTimeout( () => {
addedIndex.value = -1;
}, 2000 );
@@ -70,15 +69,20 @@
placeholder="Search..."
@keypress="search"
>
<div v-if="!isSearching" class="search-results-wrapper">
<div v-if="!isSearching && results.length > 0" class="search-results-wrapper">
<div v-for="(result, index) in results" :key="index" @click="() => add(index)">
<img :src="result.artwork" :alt="'Album artwork of ' + result.name + ' by ' + result.artist">
<img v-if="result.artwork" :src="result.artwork" :alt="'Album artwork of ' + result.name + ' by ' + result.artist">
<i v-else class="fa-solid fa-music img-placeholder"></i>
<div>
<h4>{{ result.name }}</h4>
<p>{{ result.artist }}</p>
</div>
<i v-if="addedIndex === index" class="fa-solid fa-check"></i>
</div>
<!-- TODO: load more if close to bottom of scroll view -->
</div>
<div v-else-if="!isSearching && results.length === 0" class="search-results-wrapper placeholder">
No results found
</div>
<div v-else class="search-results-wrapper placeholder">
Searching...
+67
View File
@@ -0,0 +1,67 @@
import {
type Ref,
ref
} from 'vue';
import type {
AssociationResult
} from '@/ts/player/plugins/interface';
import player from '@/ts/player';
import {
queue
} from '@/ts/player/state';
import {
updateIdentifiers
} from '@/ts/player/plugins/local/association';
export const isShowingAssociationManager = ref( false );
export const needsFiles = ref( true );
export const isAnalyzing = ref( false );
export const associationResults: Ref<AssociationResult[]> = ref( [] );
export const associationOpts: Ref<{
'get': ( files: FileList ) => Promise<void>,
'mime': string;
} | null> = ref( null );
export const openAssociationManager = ( cb: ( files: FileList ) => Promise<AssociationResult[]>, mime: string ) => {
isShowingAssociationManager.value = true;
associationResults.value = [];
needsFiles.value = true;
isAnalyzing.value = false;
const callback = async ( files: FileList ): Promise<void> => {
const results = await cb( files );
if ( results?.length ?? -1 > 0 ) {
associationResults.value = associationResults.value.concat( results! );
} else {
isShowingAssociationManager.value = false;
player.playIndex( 0 );
}
};
associationOpts.value = {
'get': callback,
'mime': mime
};
};
export const saveAssociations = () => {
for ( const result of associationResults.value ) {
for ( const song of queue.value ) {
if ( result.song.identifier === song.identifier ) {
updateIdentifiers( song, result.possibleFiles[ result.selectedIdx ?? 0 ]! );
break;
}
}
}
if ( associationResults.value.length === 0 ) {
isShowingAssociationManager.value = false;
player.playIndex( 0 );
}
};
+6 -4
View File
@@ -7,18 +7,20 @@ import type {
} from '@/ts/dtype/playlist';
export interface CloudImport {
// TODO: Consider if should make selectable and display album / playlist contents to select specific songs
'name': string;
'type': 'cloud';
'search': ( term: string ) => Promise<Song[]>;
'search': ( term: string, offset: number ) => Promise<Song[]>;
'addSelected': ( index: number ) => void;
'minChars'?: number;
'autoClose': boolean;
}
// TODO: Need to add a way to access Apple Music API everywhere (maybe configure MusicKitJS globally and consume it in its plugin later?)
export interface FileImport {
'name': string;
'type': 'file';
'process': ( files: File[] ) => Promise<Song[]>;
'mime': string;
'process': ( files: FileList, cb: ( progress: number ) => void ) => Promise<void>;
'autoClose': boolean;
}
export type ImportTypes = CloudImport | FileImport;
+9
View File
@@ -5,12 +5,21 @@ import {
import type {
CloudImport
} from './importTypePicker';
import type {
Song
} from '@/ts/dtype/playlist';
export const isShowingSearchView = ref( false );
export const searchOpts: Ref<CloudImport | null> = ref( null );
export const results: Ref<Song[]> = ref( [] );
export const query = ref( '' );
export const openSearchInterface = ( options: CloudImport ) => {
searchOpts.value = options;
isShowingSearchView.value = true;
results.value = [];
query.value = '';
};
+2
View File
@@ -1,5 +1,6 @@
import '@fortawesome/fontawesome-free/css/all.css';
import App from './App.vue';
import Notifications from '@kyvg/vue3-notification';
import {
createApp
} from 'vue';
@@ -12,5 +13,6 @@ const app = createApp( App );
app.use( createPinia() );
app.use( router );
app.use( Notifications );
app.mount( '#app' );
+18 -8
View File
@@ -1,9 +1,10 @@
import {
createRouter,
createWebHistory
} from 'vue-router';
import {
useAuthStore
} from '@/stores/authstore';
import {
createRouter, createWebHistory
} from 'vue-router';
const router = createRouter( {
'history': createWebHistory( import.meta.env.BASE_URL ),
@@ -26,6 +27,15 @@ const router = createRouter( {
'auth': true
}
},
{
'path': '/share/:name',
'name': 'share',
'component': () => import( '@/views/SharedView.vue' ),
'meta': {
'title': 'Shared',
'auth': false
}
},
{
'path': '/:pathMatch(.*)*',
'name': 'NotFound',
@@ -38,16 +48,16 @@ const router = createRouter( {
]
} );
router.beforeEach( ( to, from ) => {
router.beforeEach( to => {
const store = useAuthStore();
if ( to.meta.authRequired && !store.isAuth ) {
if ( to.meta.auth && !store.isAuth ) {
return {
'name': 'login'
'name': 'home'
};
} else if ( ( to.name === 'login' && store.isAuth ) || ( to.name === 'signup' && store.isAuth ) ) {
} else if ( to.name === 'home' && store.isAuth ) {
return {
'name': 'app-home'
'name': 'app'
};
}
} );
+16 -1
View File
@@ -1,6 +1,5 @@
.mp-player {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
@@ -19,10 +18,15 @@
display: flex;
align-items: center;
justify-content: center;
height: 3rem;
>.play-pause {
cursor: pointer;
>.fa-play {
display: none;
}
&.paused {
>.fa-pause {
display: none;
@@ -60,6 +64,11 @@
margin-left: auto;
margin-right: auto;
>p {
margin-top: 0px;
margin-bottom: 5px;
}
>.duration {
margin-left: auto;
}
@@ -70,6 +79,12 @@
}
>.bottom-bar {
display: flex;
align-items: center;
justify-content: center;
height: 3rem;
margin-top: 15px;
>.fa-shuffle {
&.active {
background-color: var(--primary-color);
+55
View File
@@ -0,0 +1,55 @@
.playlists {
height: 100%;
width: 100%;
position: relative;
>.playlist-wrapper {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
>.playlist-container {
width: 100%;
height: 100%;
display: flex;
align-items: center;
flex-direction: column;
overflow-x: scroll;
>.playlist {
width: 50%;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
height: 3rem;
>h2, >input {
margin: 0;
margin-right: auto;
margin-left: 10px;
width: 100%;
text-align: start;
cursor: pointer;
}
>input {
margin-right: auto;
margin-left: 10px;
width: 50%;
min-width: 200px;
}
>.fa-circle-play {
font-size: 1.5rem;
}
>.fa-solid {
cursor: pointer;
}
}
}
}
}
+4
View File
@@ -33,5 +33,9 @@
position: fixed;
z-index: 10000;
}
&.disallowed {
cursor: default;
}
}
}
+79 -114
View File
@@ -1,127 +1,92 @@
.song-list-element {
display: flex;
width: 100%;
.queue-viewer {
height: 100%;
width: 90%;
overflow: hidden;
>.song-cover-wrapper {
height: 10rem;
width: 10rem;
position: relative;
margin-right: 20px;
>.queue-container {
display: flex;
width: 100%;
height: 90%;
flex-direction: column;
justify-content: center;
align-items: center;
.song-cover,
.fa-solid {
height: 10rem;
width: 10rem;
font-size: 7rem;
line-height: 100%;
.song-list-element {
display: flex;
justify-content: center;
align-items: center;
}
>.play-overlay {
background-color: var(--overlay-color);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
&.hover {
display: none;
>.song-cover-wrapper {
height: 7rem;
width: 7rem;
position: relative;
margin-right: 20px;
.song-cover,
.fa-solid {
height: 100%;
width: 100%;
font-size: 6rem;
line-height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
>.play-overlay {
background-color: var(--overlay-color);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
&.hover {
display: none;
}
}
&:hover {
>.play-overlay.hover {
display: block;
}
}
}
}
&:hover {
>.play-overlay.hover {
display: block;
>.song-details {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
>* {
margin: 5px;
}
>h3 {
font-size: 1.2rem;
}
}
>.song-actions {
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
margin-left: auto;
margin-right: 10px;
>* {
margin: 5px;
}
>.fa-solid {
font-size: 1.25rem;
cursor: pointer;
}
}
}
}
>.song-details {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
>* {
margin: 5px;
}
>h3 {
font-size: 1.8rem;
}
}
>.song-actions {
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
margin-left: auto;
margin-right: 10px;
>* {
margin: 5px;
}
>.fa-solid {
font-size: 1.25rem;
cursor: pointer;
}
}
}
.playing-symbols {
position: absolute;
left: 0;
right: 0;
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
margin: 0;
padding-left: 20%;
padding-right: 20%;
width: 60%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
.playing-bar {
height: 40%;
background-color: white;
width: 12%;
border-radius: 50px;
margin: auto;
}
#bar-1 {
animation: music-playing 0.9s infinite ease-in-out;
}
#bar-2 {
animation: music-playing 0.9s infinite ease-in-out;
animation-delay: 0.3s;
}
#bar-3 {
animation: music-playing 0.9s infinite ease-in-out;
animation-delay: 0.6s;
}
@keyframes music-playing {
0% {
transform: scaleY(1);
}
50% {
transform: scaleY(0.5);
}
100% {
transform: scaleY(1);
}
}
}
+9 -6
View File
@@ -30,15 +30,18 @@
}
}
>img {
height: 7rem;
width: 7rem;
margin-right: 20px;
}
>.fa-solid {
margin-left: auto;
font-size: 2rem;
}
>img,
.img-placeholder {
height: 7rem;
width: 7rem;
margin-right: 20px;
font-size: 6rem;
margin-left: 0;
}
}
}
@@ -2,6 +2,7 @@
overflow-y: scroll;
overflow-x: hidden;
height: 100%;
width: 100%;
position: relative;
>.grip-target {
@@ -22,6 +23,7 @@
&.moving {
position: fixed;
user-select: none;
}
>i {
+44
View File
@@ -0,0 +1,44 @@
.shared-view {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
.panel {
width: 45%;
margin-left: 2.5%;
margin-right: 2.5%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
>.current-song-wrapper {
margin-bottom: 1.5rem;
width: 100%;
height: 100%;
max-height: calc(100% - 10rem);
overflow: hidden;
}
>.time {
display: flex;
width: 85%;
margin-left: auto;
margin-right: auto;
>p {
margin-top: 0px;
margin-bottom: 5px;
}
>.duration {
margin-left: auto;
}
}
}
}
+8
View File
@@ -4,4 +4,12 @@ import type {
declare global {
var MusicKit: MusicKitObject;
interface GlobalEventHandlersEventMap {
'musicplayer:playpause': CustomEvent<void>;
'musicplayer:playindex': CustomEvent<void>;
'musicplayer:seek': CustomEvent<void>;
'musicplayer:update': CustomEvent<void>;
'musicplayer:reauth': CustomEvent<void>;
'musicplayer:autherror': CustomEvent<void>;
}
}
+7 -3
View File
@@ -1,6 +1,9 @@
// NOTE: For re-associating files with details here, can use dropdown in UI
export interface Playlist {
'name': string;
'songs': PlaylistSongs;
}
export type Playlist = Song[];
export type PlaylistSongs = Song[];
export interface UrlToFileMapping {
[key: string]: string
@@ -18,7 +21,8 @@ export interface Song {
'identifier': string;
/**
* Any additional identifiers (such as filename, etc) to associate
* Any additional identifiers (such as filename, etc) to associate.
* Even if this is not used, set this value if local files are needed
*/
'additional-identifier'?: string;
View File
+186
View File
@@ -0,0 +1,186 @@
import {
isPlaying,
queue,
queueIdx
} from '../player/state';
import {
onMounted,
onUnmounted,
ref,
watch
} from 'vue';
import {
playbackPercentage
} from '../player/status-tracking';
import {
reauth
} from '../util/reauth';
import request from '../request';
const RETRY_CAP = 10;
export const room = ref( localStorage.getItem( 'room' ) ?? '' );
export const isConnected = ref( false );
export const useAntiTamper = ref( false );
// TODO: Anit-Tamper
// const antiTamperClients = [];
let connection: null | EventSource = null;
let retries = 0;
const createRoom = async ( name: string, antiTamper: boolean ): Promise<boolean> => {
if ( !( /^[a-zA-Z0-9-]{3,20}$/ ).test( name ) ) return false;
try {
await request.get( '/room/create?room=' + name );
} catch ( err ) {
if ( err === 'ERR_409' ) {
return await connect();
}
}
localStorage.setItem( 'room', name );
useAntiTamper.value = antiTamper;
room.value = name;
document.addEventListener( 'musicplayer:autherror', reauth );
return await connect();
};
const closeRoom = async () => {
// TODO: Trigger close on backend and disconnect.
isConnected.value = false;
localStorage.removeItem( 'room' );
connection?.close();
try {
document.removeEventListener( 'musicplayer:autherror', reauth );
} catch { /* empty */ }
};
const connect = (): Promise<boolean> => {
return new Promise( ( resolve, reject ) => {
if ( !useAntiTamper.value ) {
isConnected.value = true;
sendPlaylistData();
sendStateData();
return resolve( true );
}
connection = new EventSource( request.backendURL + `/room/${ room.value }/admin`, {
'withCredentials': true
} );
connection.onopen = () => {
isConnected.value = true;
console.log( '[SSE] Connection established successfully' );
sendPlaylistData();
sendStateData();
resolve( true );
};
connection.onmessage = msg => {
console.log( msg );
};
connection.onerror = () => {
connection?.close();
console.error( '[SSE] Reconnecting due to error' );
if ( !isConnected.value ) reject( 'ERR_CONNECT' );
if ( retries <= RETRY_CAP ) {
retries += 1;
setTimeout( () => {
createRoom( room.value, useAntiTamper.value );
}, 1000 * retries );
}
};
} );
};
// FIXME: This is not a sensible solution, but easy for now (i.e. solve properly)
let playlistLock = false;
let stateLock = false;
const sendPlaylistData = () => {
if ( isConnected.value && !playlistLock ) {
playlistLock = true;
try {
request.post( `/room/${ room.value }/update/playlist`, JSON.stringify( {
'playlist': queue.value
} ) );
} catch ( e ) {
console.error( e );
}
setTimeout( () => {
playlistLock = false;
}, 500 );
}
};
const sendStateData = async () => {
if ( isConnected.value && !stateLock ) {
stateLock = true;
try {
request.post( `/room/${ room.value }/update/state`, JSON.stringify( {
'playing': isPlaying.value,
'index': queueIdx.value,
'start': new Date().getTime() - 100,
'offset': playbackPercentage.value * ( queue.value[ queueIdx.value ]?.duration ?? 0 )
} ) );
} catch ( e ) {
console.error( e );
}
setTimeout( () => {
stateLock = false;
}, 500 );
}
};
const useRoomWatchers = () => {
watch( queue, sendPlaylistData );
onMounted( () => {
document.addEventListener( 'musicplayer:playindex', sendStateData );
document.addEventListener( 'musicplayer:seek', sendStateData );
document.addEventListener( 'musicplayer:playpause', sendStateData );
document.addEventListener( 'musicplayer:update', sendPlaylistData );
} );
onUnmounted( () => {
try {
document.addEventListener( 'musicplayer:play', sendStateData );
} catch { /* empty */ }
try {
document.addEventListener( 'musicplayer:seek', sendStateData );
} catch { /* empty */ }
try {
document.addEventListener( 'musicplayer:playpause', sendStateData );
} catch { /* empty */ }
try {
document.addEventListener( 'musicplayer:update', sendPlaylistData );
} catch { /* empty */ }
} );
if ( room.value ) connect();
};
export default {
createRoom,
useRoomWatchers,
closeRoom
};
+34 -4
View File
@@ -23,6 +23,12 @@ import {
import type {
RepeatMode
} from '../dtype/player';
import type {
Song
} from '../dtype/playlist';
import {
load
} from './playlists/loader';
import {
playIndex
} from './playlists';
@@ -32,7 +38,9 @@ const next = () => {
};
const prev = () => {
// TODO: Back to beginning if more than some seconds have passed?
if ( playbackPercentage.value * duration.value > 7 )
return seekTo( 0 );
playIndex( ( queueIdx.value - 1 + queue.value.length ) % queue.value.length );
};
@@ -43,6 +51,7 @@ const play = () => {
sources[currentSource.value]?.play();
startTracking();
document.dispatchEvent( new CustomEvent( 'musicplayer:playpause' ) );
};
const pause = () => {
@@ -52,6 +61,7 @@ const pause = () => {
sources[currentSource.value]?.pause();
stopTracking();
document.dispatchEvent( new CustomEvent( 'musicplayer:playpause' ) );
};
/**
@@ -62,6 +72,7 @@ const seekTo = ( pos: number ) => {
if ( currentSource.value === '' ) return;
sources[currentSource.value]?.seekTo( pos );
document.dispatchEvent( new CustomEvent( 'musicplayer:seek' ) );
};
const skip10 = () => {
@@ -118,12 +129,30 @@ const getSources = (): string[] => {
return Object.keys( sources );
};
const addToSongList = ( songs: Song[] ) => {
addSongList( songs );
if ( currentSource.value === '' ) {
playIndex( 0 );
}
};
/**
* Add songs to the playlist from given source
* @param source - The ID of the source to add from
* @param cb - A custom callback to be executed instead of the default, which adds to queue
* @param skipLogin - Whether to skip login checks
*/
const addSongFromSource = async ( source: string ) => {
sources[source]!.addSongsFromThisSource( addSongList );
const addSongFromSource = async ( source: string, cb?: ( songs: Song[] ) => void, skipLogin?: boolean ): Promise<boolean> => {
if ( sources[source]!.authorized.value || skipLogin ) {
sources[source]!.addSongsFromThisSource( cb ? cb : addToSongList, skipLogin ? 0 : undefined, skipLogin );
} else {
sources[source]!.login!();
return false;
}
return true;
};
export default {
@@ -147,5 +176,6 @@ export default {
playbackPercentage,
repeat,
shuffle,
isPlaying
isPlaying,
'loadPlaylist': load
};
+26 -11
View File
@@ -1,28 +1,43 @@
import {
currentSource,
isPlaying,
queue,
queueIdx,
rawQueue,
shuffle
repeat,
shuffle,
sources
} from '../state';
import {
duration,
playbackPercentage
} from '../status-tracking';
import type {
Song
} from '@/ts/dtype/playlist';
import {
setPlaylistIdx
} from '@/ts/userPlaylists';
export const addSongList = ( songs: Song[], first: boolean = false ) => {
if ( first ) {
// FIXME: Needs to insert at current index in queue, but where for rawQueue?
// Probably at end if shuffled, else insert into queue, then copy
rawQueue.value = songs.concat( rawQueue.value );
queue.value = songs.concat( queue.value );
} else {
rawQueue.value = rawQueue.value.concat( songs );
queue.value = queue.value.concat( songs );
}
export const addSongList = ( songs: Song[] ) => {
rawQueue.value = rawQueue.value.concat( songs );
queue.value = queue.value.concat( songs );
};
export const clearQueue = () => {
setPlaylistIdx( 0 );
queue.value = [];
rawQueue.value = [];
sources[currentSource.value]?.stop();
duration.value = -1;
playbackPercentage.value = 1;
isPlaying.value = false;
repeat.value = 'off';
shuffle.value = false;
for ( const song of queue.value ) {
sources[ song.source ]?.songUnload( song );
}
};
/**
+15 -3
View File
@@ -1,5 +1,6 @@
import {
currentSource,
isPlaying,
queue,
queueIdx,
repeat,
@@ -14,16 +15,22 @@ import {
* Play a song at the given index of the queue. Wraps to 0 and end if index below 0 or above end
* @param idx - The index in the queue to play at
*/
export const playIndex = async ( idx: number ) => {
export const playIndex = ( idx: number ) => {
if ( idx >= queue.value.length ) {
idx = repeat.value === 'all' ? 0 : -1;
} else if ( idx < 0 ) {
idx = repeat.value === 'all' ? queue.value.length - 1 : -1;
}
if ( idx < 0 ) return false;
sources[currentSource.value]?.stop();
if ( idx < 0 ) {
isPlaying.value = false;
currentSource.value = '';
return false;
}
stopTracking();
const nextSong = queue.value[ idx ]!;
@@ -33,4 +40,9 @@ export const playIndex = async ( idx: number ) => {
sources[currentSource.value]?.playSong( nextSong.identifier );
startTracking();
isPlaying.value = true;
setTimeout( () => {
document.dispatchEvent( new CustomEvent( 'musicplayer:playindex', {} ) );
}, 500 );
};
+57 -2
View File
@@ -1,2 +1,57 @@
// TODO: If local files contained, prompt user to select files, then associate based on file names
export const load = () => {};
import {
fullPlayer,
queue,
rawQueue,
sources
} from '../state';
import type {
AssociationResult
} from '../plugins/interface';
import type {
PlaylistSongs
} from '@/ts/dtype/playlist';
import {
openAssociationManager
} from '@/composables/associationManager';
export const load = ( playlist: PlaylistSongs ) => {
queue.value = playlist;
rawQueue.value = playlist;
let needToLoadLocalSongs = false;
for ( const song of playlist ) {
if ( song['additional-identifier'] ) {
needToLoadLocalSongs = true;
break;
}
}
const fileLoader = async ( files: FileList ) => {
const associationResults: AssociationResult[] = [];
for ( const song of playlist ) {
const source = sources[song.source]!;
if ( source.loading.requiresLocalFiles === true ) {
associationResults.push( await source.loading.association( files as FileList, song ) );
}
}
return associationResults.filter( val => val.match !== 'exact' );
};
if ( needToLoadLocalSongs ) {
const mime = Object.values( sources )
.map( src => {
return src.loading.requiresLocalFiles === true ? src.loading.mime : '';
} )
.reduce( ( prev, curr ) => {
return prev === '' ? curr : prev + ',' + curr;
} );
openAssociationManager( fileLoader, mime );
}
fullPlayer.value = true;
};
+37 -11
View File
@@ -1,10 +1,19 @@
import type {
Ref
} from 'vue';
import type {
Song
} from '@/ts/dtype/playlist';
// TODO: Add search interface elements to plugin's args (such as a search interface)
export type PlayerSourcePluginInitializer = () => Promise<PlayerSourcePlugin>;
export interface AssociationResult {
'song': Song,
'match': 'exact' | 'none' | 'multiple';
'possibleFiles': File[],
'selectedIdx'?: number;
}
export interface PlayerSourcePlugin {
/**
* The name of the source that is displayed in the UI
@@ -30,17 +39,26 @@ export interface PlayerSourcePlugin {
*/
'requiresLocalFiles': true;
/**
* The allowed MIME types for loading associated files
*/
'MIMETypes': string;
/**
* Function used to associate the file to the songs of the playlist
* @param files - The files that were picked by the user
* @returns A promise resolving to an array of song identifiers (corresponding to Song.identifier, for association)
* @param song - The song to update
* @returns A promise resolving to the (possibly) updated song and metadata
*/
'association': ( files: File[] ) => Promise<string[]>;
'association': ( files: FileList, song: Song ) => Promise<AssociationResult>;
/**
* Function used to update the additional identifier of the song if the file has changed
* @param song - The song that needs updating
* @param file - The file that it should be updated to
* @returns The updated song
*/
'updateIdentifiers': ( song: Song, file: File ) => Promise<Song>;
/**
* The mime types that this source's files may have
*/
'mime': string;
} | {
/**
* Set to true if the user needs to load files
@@ -91,13 +109,21 @@ export interface PlayerSourcePlugin {
'getDuration': () => number;
/**
* Check if source is available for playback
* Check if source is authorized
*/
'available': () => boolean;
'authorized': Ref<boolean>;
/**
* Called when user adds another song to the playlist via this source.
* You may use the provided interface elements (search bar and popups) to e.g. ask if user wants to use a playlist, album, etc
* @param cb - Added songs are the arguments
* @param kindIdx - The index in the list of import types that should be used without showing popup. If unset, will show the picker
* @param autoClose - Whether or not to automatically close the interface after a single pick
*/
'addSongsFromThisSource': ( cb: ( songs: Song[] ) => void ) => void;
'addSongsFromThisSource': ( cb: ( songs: Song[] ) => void, kindIdx?: number, autoClose?: boolean ) => void;
/**
* Fully unload a song. This is called on clear of a playlist
*/
'songUnload': ( song: Song ) => Promise<void>;
}
@@ -0,0 +1,57 @@
import type {
AssociationResult
} from '../interface';
import type {
Song
} from '@/ts/dtype/playlist';
export const createFileAssociationString = ( file: File ) => {
return file.name + '__' + file.size;
};
export const associate = async ( files: FileList, song: Song ): Promise<AssociationResult> => {
const candidates: File[] = [];
if ( !song['additional-identifier'] ) {
return {
'match': 'none',
'song': song,
'possibleFiles': []
};
}
for ( const file of files ) {
if ( createFileAssociationString( file ) === song['additional-identifier'] ) {
candidates.push( file );
}
}
if ( candidates.length === 0 ) {
return {
'match': 'none',
'song': song,
'possibleFiles': []
};
} else if ( candidates.length === 1 ) {
song.identifier = URL.createObjectURL( candidates[ 0 ]! );
return {
'match': 'exact',
'song': song,
'possibleFiles': []
};
} else {
return {
'match': 'multiple',
'song': song,
'possibleFiles': candidates
};
}
};
export const updateIdentifiers = async ( song: Song, file: File ): Promise<Song> => {
song.identifier = URL.createObjectURL( file );
song['additional-identifier'] = createFileAssociationString( file );
return song;
};
+22 -11
View File
@@ -2,9 +2,20 @@ import type {
PlayerSourcePlugin,
PlayerSourcePluginInitializer
} from '../interface';
import {
associate,
updateIdentifiers
} from './association';
import {
load,
unload
} from './loader';
import {
ref
} from 'vue';
export const useLocalPlayer: PlayerSourcePluginInitializer = async (): Promise<PlayerSourcePlugin> => {
const player = document.createElement( 'audio' );
const player = new Audio();
const playSong = async ( id: string ) => {
player.src = id;
@@ -12,23 +23,23 @@ export const useLocalPlayer: PlayerSourcePluginInitializer = async (): Promise<P
};
return {
'available': () => true,
'authorized': ref( true ),
'id': 'local',
'name': 'Local Disk',
'play': player.play,
'play': () => player.play(),
'getPlaybackPos': () => player.currentTime / player.duration,
'getDuration': () => player.duration,
playSong,
'seekTo': pos => player.currentTime = pos,
'pause': player.pause,
'seekTo': pos => player.currentTime = pos * player.duration,
'pause': () => player.pause(),
'stop': () => player.src = '',
// TODO: Implement
'addSongsFromThisSource': async () => [],
'addSongsFromThisSource': load,
'loading': {
'requiresLocalFiles': true,
'MIMETypes': 'audio/mp3,audio/wav',
// TODO: Implement
'association': async () => []
}
'association': associate,
'updateIdentifiers': updateIdentifiers,
'mime': 'audio/aac,audio/mpeg,audio/wav,audio/mp4,audio/ogg'
},
'songUnload': unload
};
};
+81
View File
@@ -0,0 +1,81 @@
import type {
Song
} from '@/ts/dtype/playlist';
import {
createFileAssociationString
} from './association';
import {
initAppleMusicApiSearch
} from '@/ts/util/search';
import {
openDiskLoaderInterface
} from '@/composables/diskLoader';
import {
parseBlob
} from 'music-metadata';
export const load = ( cb: ( songs: Song[] ) => void ) => {
const search = initAppleMusicApiSearch();
const process = async ( files: FileList, status: ( progress: number ) => void ) => {
const songs: Song[] = [];
for ( let i = 0; i < files.length; i++ ) {
const file = files[i]!;
try {
songs.push( await generateSongObject( file ) );
} catch ( error ) {
console.error( '[LOADER] Failed generating song info for file', file, 'with error', error );
}
status( ( i + 1 ) / files.length );
}
cb( songs );
};
openDiskLoaderInterface( {
'name': 'From Disk',
'process': process,
'type': 'file',
'mime': 'audio/aac,audio/mpeg,audio/wav,audio/mp4,audio/ogg'
} );
const generateSongObject = async ( file: File ): Promise<Song> => {
console.log( 'Analyzing file', file );
const url = URL.createObjectURL( file );
const blob = await ( await fetch( url ) ).blob();
// Load audio file and parse its metadata
const data = await parseBlob( blob );
const searchTerm = data.common.title
? data.common.title + ( data.common.artist ? ' ' + data.common.artist : '' )
: file.name.split( '.' )[ 0 ]!.replace( '_', ' ' );
const result = ( await search( searchTerm, 1 ) )[ 0 ];
if ( result ) {
result.source = 'local';
result['additional-identifier'] = createFileAssociationString( file );
result.identifier = url;
return result;
} else {
console.warn( '[LOADER] No results found for', searchTerm );
return {
'additional-identifier': file.name,
'source': 'local',
'identifier': url,
'artist': data.common.artist ?? 'Unknown Artist',
'name': data.common.title ?? 'Unknown title',
'artwork': '',
'additional-info': '',
'duration': -1
};
}
};
};
export const unload = async ( song: Song ) => {
URL.revokeObjectURL( song.identifier );
};
+37 -46
View File
@@ -2,66 +2,57 @@ import type {
PlayerSourcePlugin,
PlayerSourcePluginInitializer
} from '../interface';
import type {
Song
} from '@/ts/dtype/playlist';
import {
addFromAppleMusic
} from './search';
import {
musicKitPlayback
} from './playback';
import request from '@/ts/request';
export const useMusicKit: PlayerSourcePluginInitializer = ( storefront: string = 'ch' ): Promise<PlayerSourcePlugin> => {
return new Promise( ( resolve, reject ) => {
const init = async ( storefront: string ): Promise<PlayerSourcePlugin> => {
const res = await fetch( import.meta.env.VITE_BACKEND_URL + '/dev-token', {
'credentials': 'include'
const token = await ( await request.get( '/dev-token' ) ).text();
const instance = await window.MusicKit.configure( {
'developerToken': token,
'app': {
'name': 'MusicPlayer',
'build': '4'
// 'icon': 'https://music.janishutz.com/logo.jpg'
},
'storefrontId': storefront.toUpperCase()
} );
const controls = musicKitPlayback( instance );
if ( res.status === 200 ) {
const token = await res.text();
const instance = await window.MusicKit.configure( {
'developerToken': token,
'app': {
'name': 'MusicPlayer',
'build': '4'
// 'icon': 'https://music.janishutz.com/logo.jpg'
},
'storefrontId': storefront.toUpperCase()
} );
const controls = musicKitPlayback( instance );
const login = async (): Promise<boolean> => {
try {
await instance.authorize();
const login = async (): Promise<boolean> => {
try {
await instance.authorize();
return true;
} catch {
return false;
}
};
return true;
} catch {
return false;
}
};
return {
'available': controls.getLoggedIn,
'play': controls.play,
'pause': controls.pause,
'stop': controls.stop,
'playSong': controls.playSong,
'getDuration': controls.getDuration,
'getPlaybackPos': controls.getPlaybackPos,
'id': 'applemusic',
'name': 'Apple Music',
'seekTo': controls.seekTo,
'login': login,
'addSongsFromThisSource': ( cb: ( songs: Song[] ) => void ) => addFromAppleMusic( instance, cb ),
'loading': {
'requiresLocalFiles': false
}
};
} else {
throw new Error( 'ERR_AUTH' );
}
return {
'authorized': controls.loggedIn,
'play': controls.play,
'pause': controls.pause,
'stop': controls.stop,
'playSong': controls.playSong,
'getDuration': controls.getDuration,
'getPlaybackPos': controls.getPlaybackPos,
'id': 'applemusic',
'name': 'Apple Music',
'seekTo': controls.seekTo,
'login': login,
'addSongsFromThisSource': addFromAppleMusic,
'loading': {
'requiresLocalFiles': false
},
'songUnload': async () => {}
};
};
if ( !window.MusicKit ) {
+10 -5
View File
@@ -1,6 +1,9 @@
import type {
MusicKitInstance
} from 'musickitjs-v3-types/MusicKitInstance';
import {
ref
} from 'vue';
export const musicKitPlayback = ( musickitInstance: MusicKitInstance ) => {
const play = () => {
@@ -27,16 +30,18 @@ export const musicKitPlayback = ( musickitInstance: MusicKitInstance ) => {
};
const getPlaybackPos = (): number => {
return musickitInstance.currentPlaybackProgress;
return musickitInstance.currentPlaybackTime / musickitInstance.currentPlaybackDuration;
};
const getDuration = (): number => {
return musickitInstance.currentPlaybackDuration;
};
const getLoggedIn = (): boolean => {
return musickitInstance.isAuthorized;
};
const loggedIn = ref( musickitInstance.isAuthorized );
musickitInstance.addEventListener( 'authorizationStatusDidChange', () => {
loggedIn.value = musickitInstance.isAuthorized;
} );
return {
play,
@@ -46,6 +51,6 @@ export const musicKitPlayback = ( musickitInstance: MusicKitInstance ) => {
stop,
getPlaybackPos,
getDuration,
getLoggedIn
loggedIn
};
};
+18 -1
View File
@@ -18,9 +18,26 @@ export interface AppleMusicSongData {
'attributes': {
'albumName': string;
'artistName': string;
'artwork': Artwork,
'artwork': Artwork;
'name': string;
'genreNames': string[];
'durationInMillis': number;
}
}
export interface AppleMusicPlaylistData {
'id': string;
'type': string;
'href': string;
'attributes': {
'artwork': Artwork;
'name': string;
},
'relationships'?: {
'tracks': {
'href': string,
'next': string,
'data': AppleMusicSongData
}[]
}
}
@@ -1,12 +1,13 @@
import type {
MusicKitInstance
} from 'musickitjs-v3-types/MusicKitInstance';
import {
type CloudImport,
openImportTypePicker
} from '@/composables/importTypePicker';
import type {
Song
} from '@/ts/dtype/playlist';
import {
openImportTypePicker
} from '@/composables/importTypePicker';
openSearchInterface
} from '@/composables/searchManager';
import {
searchPlaylists
} from './playlists';
@@ -14,22 +15,29 @@ import {
searchSongs
} from './songs';
export const addFromAppleMusic = async ( instance: MusicKitInstance, cb: ( songs: Song[] ) => void ): Promise<void> => {
const songs = await searchSongs( instance, cb );
const playlists = await searchPlaylists( instance, cb );
openImportTypePicker( [
export const addFromAppleMusic = async ( cb: ( songs: Song[] ) => void, kindIdx?: number, autoClose?: boolean ): Promise<void> => {
const songs = await searchSongs( cb );
const playlists = await searchPlaylists( cb );
const kinds: CloudImport[] = [
{
'name': 'Songs',
'type': 'cloud',
'addSelected': songs.addSelected,
'search': songs.search
'search': songs.search,
'minChars': 3,
'autoClose': autoClose ?? false
},
{
'name': 'Playlists',
'type': 'cloud',
'addSelected': playlists.addSelected,
'search': playlists.search
'search': playlists.search,
'autoClose': autoClose ?? false
}
] );
];
if ( kindIdx === undefined )
openImportTypePicker( kinds );
else
openSearchInterface( kinds[kindIdx]! );
};
@@ -1,20 +1,67 @@
import type {
MusicKitInstance
} from 'musickitjs-v3-types/MusicKitInstance';
AppleMusicPlaylistData,
AppleMusicSongData
} from './dtype';
import type {
Song
} from '@/ts/dtype/playlist';
export const searchPlaylists = async ( instance: MusicKitInstance, cb: ( songs: Song[] ) => void ) => {
// TODO: Get all playlists
export const searchPlaylists = async ( cb: ( songs: Song[] ) => void ) => {
let playlists: Song[] = [];
let filtered: Song[] = [];
const search = async ( term: string ): Promise<Song[]> => {
return [];
const instance = window.MusicKit.getInstance();
const search = async ( term: string, offset: number = 0 ): Promise<Song[]> => {
if ( playlists.length === 0 ) {
playlists = ( ( await instance.api.music( '/v1/me/library/playlists', {
'limit': 100,
'offset': offset
} ) ).data as {
'data': AppleMusicPlaylistData[]
} ).data.map( val => {
return {
'artist': 'Playlist',
'artwork': val.attributes.artwork ? window.MusicKit.formatArtworkURL( val.attributes.artwork, 1000, 100 ) : '',
'duration': 0,
'identifier': val.id,
'additional-info': '',
'name': val.attributes.name,
'source': 'applemusic'
};
} );
}
term = term.toLocaleLowerCase();
filtered = playlists.filter( val => {
return val.name.toLocaleLowerCase().includes( term );
} );
return filtered;
};
const addSelected = async ( idx: number ) => {
// TODO: Implement
cb( [] );
try {
const results = ( await instance.api.music( '/v1/me/library/playlists/' + filtered[idx]!.identifier + '/tracks' ) ).data as {
'data': AppleMusicSongData[]
};
const songs: Song[] = results.data
.map( val => {
return {
'identifier': val.id,
'additional-info': '',
'artist': val.attributes.artistName,
'name': val.attributes.name,
'artwork': window.MusicKit.formatArtworkURL( val.attributes.artwork, 1000, 1000 ),
'duration': val.attributes.durationInMillis * 1000,
'source': 'applemusic'
};
} );
cb( songs );
} catch ( error ) {
console.error( '[ADD PLAYLIST] Failed to add playlist due to error', error );
}
};
return {
@@ -1,36 +1,17 @@
import type {
AppleMusicApiSearchResult
} from './dtype';
import type {
MusicKitInstance
} from 'musickitjs-v3-types/MusicKitInstance';
import type {
Song
} from '@/ts/dtype/playlist';
import {
initAppleMusicApiSearch
} from '@/ts/util/search';
export const searchSongs = async ( instance: MusicKitInstance, cb: ( songs: Song[] ) => void ) => {
export const searchSongs = async ( cb: ( songs: Song[] ) => void ) => {
let songs: Song[] = [];
const search = async ( term: string ): Promise<Song[]> => {
const params = {
'term': term,
'types': [ 'songs' ]
};
const results = ( ( await instance.api.music( '/v1/catalog/{{storefrontId}}/search', params ) ).data as AppleMusicApiSearchResult ).results.songs.data;
const searchFunc = initAppleMusicApiSearch();
songs = [];
for ( const result of results ) {
songs.push( {
'duration': Math.round( result.attributes.durationInMillis / 1000 ),
'name': result.attributes.name,
'additional-info': '',
'artist': result.attributes.artistName,
'artwork': window.MusicKit.formatArtworkURL( result.attributes.artwork, 1000, 1000 ),
'identifier': result.id,
'source': 'applemusic'
} );
}
const search = async ( term: string, offset: number = 0 ) => {
songs = await searchFunc( term, 15, offset );
return songs;
};
+6 -4
View File
@@ -6,7 +6,7 @@ import type {
PlayerSourcePlugin
} from './plugins/interface';
import type {
Playlist
PlaylistSongs
} from '../dtype/playlist';
import type {
RepeatMode
@@ -24,11 +24,11 @@ export const sources: {
export const currentSource = ref( '' );
export const rawQueue: Ref<Playlist> = ref( [] );
export const rawQueue: Ref<PlaylistSongs> = ref( [] );
export const queueIdx = ref( 0 );
export const queueIdx = ref( -1 );
export const queue: Ref<Playlist> = ref( [] );
export const queue: Ref<PlaylistSongs> = ref( [] );
export const isPlaying = ref( false );
@@ -36,6 +36,8 @@ export const shuffle = ref( false );
export const repeat: Ref<RepeatMode> = ref( 'off' );
export const fullPlayer = ref( false );
const initSources = async () => {
try {
sources['applemusic'] = await useMusicKit();
+8 -4
View File
@@ -14,9 +14,9 @@ import {
// Tracking of time and player status
let interval = -1;
export const playbackPercentage = ref( 0 );
export const playbackPercentage = ref( 1 );
export const duration = ref( 0 );
export const duration = ref( -1 );
export const startTracking = () => {
if ( interval === -1 ) {
@@ -24,12 +24,15 @@ export const startTracking = () => {
}
duration.value = sources[currentSource.value]?.getDuration() ?? -1;
setTimeout( () => {
duration.value = sources[currentSource.value]?.getDuration() ?? -1;
}, 2000 );
};
const tracker = () => {
playbackPercentage.value = sources[currentSource.value]?.getPlaybackPos() ?? -1;
if ( playbackPercentage.value > duration.value ) {
if ( playbackPercentage.value > 0.995 && duration.value > 0 ) {
if ( repeat.value === 'one' ) {
sources[currentSource.value]?.seekTo( 0 );
} else {
@@ -42,8 +45,9 @@ const tracker = () => {
export const stopTracking = () => {
try {
clearInterval( interval );
interval = -1;
} catch {
// empty
}
interval = -1;
};
+45
View File
@@ -0,0 +1,45 @@
export class AuthError extends Error {}
export class UnownedError extends Error {}
const get = async ( url: string ): Promise<Response> => {
return await wrapper( url, {
'credentials': 'include'
} );
};
const backendURL = import.meta.env.VITE_BACKEND_URL;
const post = async ( url: string, payload: string, mime: string = 'application/json' ): Promise<Response> => {
return await wrapper( url, {
'credentials': 'include',
'body': payload,
'method': 'post',
'headers': {
'Content-Type': mime ?? 'application/json'
}
} );
};
const wrapper = async ( url: string, opts: RequestInit ): Promise<Response> => {
const res = await fetch( backendURL + url, opts );
if ( res.ok ) {
return res;
} else if ( res.status === 403 || res.status === 401 ) {
document.dispatchEvent( new CustomEvent( 'musicplayer:autherror' ) );
throw new AuthError( 'ERR_USER_UNAUTHORIZED' );
} else if ( res.status === 402 ) {
throw new UnownedError( 'ERR_USER_UNOWNED' );
} else {
throw new Error( 'ERR_' + res.status );
}
};
export default {
get,
post,
backendURL
};
+87
View File
@@ -0,0 +1,87 @@
import {
type StateUpdate,
messageHandler
} from './messageHandler';
import {
currentQueue,
currentQueueIdx,
isPlaying,
playbackOffset,
playbackProgress,
playbackTime,
startTime
} from './state';
import type {
Song
} from '../dtype/playlist';
import request from '../request';
const RETRY_CAP = 10;
let room = location.pathname;
let connection: EventSource | null = null;
let hasConnected = false;
let retries = 0;
// TODO: Persist settings in local storage
// TODO: Polling instead of sse as option
const connect = (): Promise<void> => {
return new Promise( ( resolve, reject ) => {
room = location.pathname.substring( location.pathname.lastIndexOf( '/' ) + 1 );
connection = new EventSource( request.backendURL + `/room/${ room }/connect` );
connection.onopen = async () => {
hasConnected = true;
console.log( '[SSE] Connection established successfully' );
const data = await ( await request.get( `/room/${ room }/poll` ) ).json() as {
'playlist': Song[],
'state': StateUpdate
};
currentQueue.value = data.playlist;
currentQueueIdx.value = data.state.index;
isPlaying.value = data.state.playing;
startTime.value = data.state.start;
if ( data.playlist.length === 0 )
playbackTime.value = 0;
else
playbackTime.value = data.state.offset;
playbackOffset.value = data.state.offset;
playbackProgress.value = data.state.offset / ( data.playlist[ data.state.index ]?.duration ?? -1 );
resolve();
};
connection.onmessage = msg => {
if ( msg.data === 'close' ) {
connection?.close();
// TODO: Show popup informing user that share was closed
return;
}
messageHandler( msg.data );
};
connection.onerror = () => {
connection?.close();
if ( !hasConnected ) return reject( 'ERR_CONNECT' );
console.error( '[SSE] Connection failed, reconnecting' );
if ( retries <= RETRY_CAP ) {
retries += 1;
setTimeout( () => {
connect();
}, 1000 * retries );
}
};
} );
};
export default {
connect
};
+51
View File
@@ -0,0 +1,51 @@
import {
currentQueue,
currentQueueIdx,
isPlaying,
playbackOffset,
playbackTime,
startTime
} from './state';
import type {
Song
} from '../dtype/playlist';
interface ReceivedJSONMessage {
'type': 'state' | 'playlist';
'data': unknown;
}
export interface StateUpdate {
'playing': boolean;
'index': number;
'start': number;
'offset': number;
}
export const messageHandler = ( msg: string ) => {
if ( msg.startsWith( 'json:' ) ) {
try {
const data = JSON.parse( msg.substring( 5 ) ) as ReceivedJSONMessage;
if ( data.type === 'playlist' ) {
currentQueue.value = ( data.data as {
'playlist': Song[]
} ?? {
'playlist': []
} ).playlist;
} else if ( data.type === 'state' ) {
const state = data.data as StateUpdate;
currentQueueIdx.value = state.index;
isPlaying.value = state.playing;
startTime.value = state.start;
playbackTime.value = state.offset;
playbackOffset.value = state.offset;
} else {
console.log( '[SSE] Received unknown data', data.type );
}
} catch ( err ) {
console.error( 'JSON DECODE failed with error', err );
}
}
};
+23
View File
@@ -0,0 +1,23 @@
import {
type Ref,
ref
} from 'vue';
import type {
Song
} from '../dtype/playlist';
export const currentQueue: Ref<Song[]> = ref( [] );
export const isPlaying = ref( false );
export const currentQueueIdx = ref( -1 );
export const startTime = ref( new Date().getTime() );
export const showArtworks = ref( false );
export const playbackTime = ref( 0 );
export const playbackOffset = ref( 0 );
export const playbackProgress = ref( 0 );
+14
View File
@@ -0,0 +1,14 @@
import type {
PlaylistSongs
} from '../dtype/playlist';
interface UserPlaylistFile {
'version': '1',
'userid': string,
'playlists': Playlist[]
}
interface Playlist {
'name': string;
'songs': PlaylistSongs;
}
+32
View File
@@ -0,0 +1,32 @@
import {
editingPlaylists,
playlistIdx,
playlists
} from './state';
import player from '../player';
export const addPlaylist = ( name: string ) => {
playlists.value.push( {
'name': name,
'songs': []
} );
editingPlaylists.value.push( false );
};
export const removePlaylist = ( idx: number ) => {
if ( confirm( 'Do you really want to delete this playlist?' ) ) {
playlists.value.splice( idx, 1 );
editingPlaylists.value.splice( idx, 1 );
}
};
export const selectPlaylist = ( idx: number ) => {
playlistIdx.value = idx;
player.clearQueue();
player.loadPlaylist( playlists.value[ idx ]!.songs );
};
export const setPlaylistIdx = ( idx: number ) => {
playlistIdx.value = idx;
};
+64
View File
@@ -0,0 +1,64 @@
import {
editingPlaylists,
playlistIdx,
playlists
} from './state';
import {
queue,
rawQueue,
shuffle
} from '../player/state';
import {
addPlaylist
} from '.';
import request from '../request';
import {
useNotification
} from '@kyvg/vue3-notification';
export const savePlaylist = () => {
rawQueue.value = queue.value;
shuffle.value = false;
if ( playlistIdx.value < 0 ) {
let name: null | string = '';
while ( !name || name.length === 0 ) {
name = prompt( 'You are trying to save a playlist that has not previously been created. Please enter a name for it' );
if ( !name ) return;
}
addPlaylist( name );
playlistIdx.value = playlists.value.length - 1;
}
playlists.value[ playlistIdx.value ]!.songs = rawQueue.value;
savePlaylists();
};
export const getPlaylists = async () => {
playlists.value = await ( await request.get( '/user/playlists' ) ).json();
editingPlaylists.value = playlists.value.map( () => false );
};
export const savePlaylists = async () => {
const notifications = useNotification();
try {
await request.post( '/user/playlists', JSON.stringify( playlists.value ) );
notifications.notify( {
'text': 'Playlists saved successfully',
'type': 'success',
'title': 'Playlists'
} );
} catch ( e ) {
console.error( e );
notifications.notify( {
'text': 'Failed to save playlists',
'type': 'error',
'title': 'Playlists'
} );
}
};
+13
View File
@@ -0,0 +1,13 @@
import {
type Ref,
ref
} from 'vue';
import type {
Playlist
} from './file';
export const playlistIdx = ref( -1 );
export const playlists: Ref<Playlist[]> = ref( [] );
export const editingPlaylists: Ref<boolean[]> = ref( [] );
+17
View File
@@ -0,0 +1,17 @@
export const reauth = () => {
localStorage.setItem( 'close-tab', 'true' );
const listener = () => {
if ( localStorage.getItem( 'reauth-ok' ) === 'true' ) {
try {
window.removeEventListener( 'storage', listener );
} catch { /* empty */ }
localStorage.removeItem( 'reauth-ok' );
document.dispatchEvent( new CustomEvent( 'musicplayer:reauth' ) );
}
};
window.addEventListener( 'storage', listener );
};
+45
View File
@@ -0,0 +1,45 @@
import type {
AppleMusicApiSearchResult, AppleMusicSongData
} from '../player/plugins/musickit/search/dtype';
import type {
Song
} from '../dtype/playlist';
export const initAppleMusicApiSearch = () => {
const instance = window.MusicKit.getInstance();
return async ( term: string, limit: number = 20, offset: number = 0 ): Promise<Song[]> => {
const params = {
'term': term,
'types': [ 'songs' ],
'offset': offset ?? 20,
'limit': limit ?? 0
};
let results: AppleMusicSongData[] = [];
try {
results = ( ( await instance.api.music( '/v1/catalog/{{storefrontId}}/search', params ) ).data as AppleMusicApiSearchResult ).results.songs.data;
} catch {
console.debug( 'Failed results: got', results );
return [];
}
const songs: Song[] = [];
for ( const result of results ) {
songs.push( {
'duration': Math.round( result.attributes.durationInMillis / 1000 ),
'name': result.attributes.name,
'additional-info': '',
'artist': result.attributes.artistName,
'artwork': window.MusicKit.formatArtworkURL( result.attributes.artwork, 1000, 1000 ),
'identifier': result.id,
'source': 'applemusic'
} );
}
return songs;
};
};
+4 -4
View File
@@ -10,13 +10,13 @@ export const beautifyTime = ( time: number ): string => {
else if ( Math.floor( t / 60 ) > 0 )
return `${ helper( Math.floor( t / 60 ), depth + 1 ) }:${ t % 60 < 10 ? '0' : '' }${ Math.floor( t % 60 ) }`;
else
return `${ t % 60 < 10 ? '0' : '' }${ Math.floor( t % 60 ) }`;
return `${ depth === 1 ? '00:' : '' }${ t % 60 < 10 ? '0' : '' }${ Math.floor( t % 60 ) }`;
};
if ( time < 0 ) {
return '-:--';
if ( time < 0 || isNaN( time ) ) {
return '--:--';
} else if ( time == 0 ) {
return '0:00';
return '00:00';
}
return helper( Math.round( time ), 1 );
+7 -17
View File
@@ -1,33 +1,23 @@
<script setup lang="ts">
import PlayerControls from '@/components/PlayerControls.vue';
import QueueViewer from '@/components/QueueViewer.vue';
import PlayerWrapper from '@/components/main/PlayerWrapper.vue';
import PlaylistsComponent from '@/components/main/PlaylistsComponent.vue';
</script>
<template>
<div class="main-app">
<div class="player-controls">
<PlayerControls />
</div>
<div class="song-queue">
<QueueViewer />
</div>
<PlaylistsComponent />
<PlayerWrapper />
</div>
</template>
<style lang="scss" scoped>
.main-app {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
.player-controls {
width: 60%;
}
.song-queue {
width: 80%;
}
flex-direction: row;
}
</style>
+86
View File
@@ -0,0 +1,86 @@
<script setup lang="ts">
import {
type ComputedRef,
computed,
onMounted
} from 'vue';
import {
currentQueue,
currentQueueIdx,
isPlaying,
playbackOffset,
playbackProgress,
playbackTime,
startTime
} from '@/ts/shared/state';
import CurrentSong from '@/components/player/CurrentSong.vue';
import ProgressBar from '@/components/player/ProgressBar.vue';
import SharedQueue from '@/components/shared/SharedQueue.vue';
import type {
Song
} from '@/ts/dtype/playlist';
import {
beautifyTime
} from '@/ts/util/time';
import shared from '@/ts/shared';
shared.connect();
onMounted( () => {
setInterval( () => {
if ( !isPlaying.value ) return;
playbackTime.value = ( ( new Date().getTime() - startTime.value ) / 1000 ) + playbackOffset.value;
playbackProgress.value = playbackTime.value / song.value.duration;
if ( playbackTime.value > song.value.duration ) {
playbackOffset.value -= song.value.duration;
if ( currentQueueIdx.value < currentQueue.value.length - 1 )
currentQueueIdx.value++;
else
isPlaying.value = false;
}
}, 250 );
} );
const song: ComputedRef<Song> = computed( () => {
if ( currentQueueIdx.value >= 0 && currentQueue.value.length > currentQueueIdx.value )
return currentQueue.value[currentQueueIdx.value]!;
else
return {
'artist': 'No artist',
'duration': -1,
'name': 'Not playing',
'artwork': '',
'additional-info': '',
'identifier': 'nosong-ident',
'source': 'local'
};
} );
</script>
<template>
<div class="shared-view">
<div class="panel">
<div class="current-song-wrapper">
<CurrentSong v-model="song" :show-additional-info="true" />
</div>
<ProgressBar v-model="playbackProgress" :disallow-move="true" />
<div class="time">
<p class="current">
{{ beautifyTime( song.duration >= 0 ? playbackTime : -1 ) }}
</p>
<p class="duration">
{{ beautifyTime( song.duration ) }}
</p>
</div>
</div>
<div class="panel">
<SharedQueue />
</div>
</div>
</template>
<style lang="scss" scoped>
@use '@/scss/shared/main.scss';
</style>

Some files were not shown because too many files have changed in this diff Show More