Initial import: Discodrome codebase (ignore docker-compose.yml and data.env)

This commit is contained in:
joelilas
2026-01-26 00:29:08 +01:00
commit 9f4437c247
15 changed files with 2731 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# Exclude deployment-specific files
Dockerfile
docker-compose.yml
data.env

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the 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.
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.
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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
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.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

124
README.md Normal file
View File

@@ -0,0 +1,124 @@
<div align="center">
# <img src="resources/discodrome.png" width="32" height="32" alt="Discodrome Icon"> Discodrome
### Subsonic Compatible Discord Music Bot
[![GitHub issues](https://img.shields.io/github/issues/7eventy7/discodrome.svg)](https://github.com/7eventy7/discodrome/issues)
[![Docker Pulls](https://img.shields.io/docker/pulls/7eventy7/discodrome.svg)](https://hub.docker.com/r/7eventy7/discodrome)
[![License](https://img.shields.io/github/license/7eventy7/discodrome.svg)](https://github.com/7eventy7/discodrome/blob/main/LICENSE)
A discord music bot that seamlessly streams music from your personal music server directly to your voice channels. Works great with Navidrome, and other subsonic compatible music servers.
</div>
---
## 🎮 Commands
| Command | Description |
|---------|-------------|
| `/play` | Plays a specified track, album or playlist |
| `/disco` | Plays an artist's entire discography |
| `/queue` | View the current queue |
| `/clear` | Clear the current queue |
| `/shuffle` | Shuffles the current queue |
| `/skip` | Skip the current track |
| `/stop` | Stop playing the current track |
| `/autoplay` | Toggle autoplay |
| `/playlists` | List available playlists |
## 🚀 Complete Setup Guide
### Step 1: Create a Discord Bot
1. Go to the [Discord Developer Portal](https://discord.com/developers/applications)
2. Click "New Application" and give it a name
3. Navigate to the "Bot" tab and click "Add Bot"
4. Under the TOKEN section, click "Reset Token" and copy your new token
5. Enable the following Privileged Gateway Intents:
- `MESSAGE CONTENT INTENT`
- `SERVER MEMBERS INTENT`
- `PRESENCE INTENT`
6. Navigate to "OAuth2" → "URL Generator"
7. Select the following scopes:
- `bot`
- `applications.commands`
8. Select bot permissions:
- `Send Messages`
- `Connect`
- `Speak`
- `Use Voice Activity`
- `Read Message History`
9. Copy the generated URL and paste it in your browser to invite the bot to your server
### Step 2: Set Up Your Environment
#### Required Information:
- **Discord Bot Token**: From step 1
- **Discord Server ID**: Right-click your server icon → "Copy ID" (Developer Mode must be enabled in Discord settings)
- **Your Discord User ID**: Right-click your username → "Copy ID"
- **Subsonic Server Details**: URL, username, and password for your music server
### Step 3: Deploy with Docker
1. Pull the Docker image:
`docker pull 7eventy7/discodrome:latest`
2. Run the container with the required environment variables from the configuration section below:
## ⚙️ Configuration Options
### Environment Variables
| Variable | Description | Required |
|----------|-------------|----------|
| `SUBSONIC_SERVER` | URL of your Subsonic server (include http/https) | Yes |
| `SUBSONIC_USER` | Username for your Subsonic server | Yes |
| `SUBSONIC_PASSWORD` | Password for your Subsonic server | Yes |
| `DISCORD_BOT_TOKEN` | Your Discord bot token | Yes |
| `DISCORD_TEST_GUILD` | Discord server ID where commands will be registered | Yes |
| `DISCORD_OWNER_ID` | Your Discord user ID | Yes |
| `BOT_STATUS` | Custom status message for the bot | No |
### Supported Subsonic Servers
- Navidrome
- Airsonic
- Subsonic
- Gonic
- Ampache (with Subsonic API enabled)
- Jellyfin (with Subsonic plugin)
## 🛠️ Technical Stack
- Discord.js v14
- Node.js
- Subsonic API
- Docker
- FFmpeg for audio processing
## 👥 Contributing
We welcome contributions! Whether it's:
- 🐛 Reporting bugs
- 💡 Suggesting features
- 📝 Improving documentation
- 🔍 Submitting fixes
- ✨ Adding new features
Please check our [GitHub Issues](https://github.com/7eventy7/discodrome/issues) before submitting new ones.
## 📝 License
GPL-3.0 license - feel free to use this project for most any purpose.
## 🙏 Acknowledgments
This project is a fork of [Submeister](https://github.com/Gimzie/submeister) by Gimzie. We've built upon their excellent foundation to add new features and improvements while maintaining the core functionality that made the original project great.
---
<div align="center">
Projet repris et maintenu par <a href="http://192.168.1.132:8929/joelilas">joelilas</a>
</div>

137
data.py Normal file
View File

@@ -0,0 +1,137 @@
''' Data used throughout the application '''
'''
TODO: Save one properties pickle file per-guild, instead of saving all in one file at once
'''
import logging
import os
import pickle
from enum import Enum
from typing import Final
from subsonic import Song
from player import Player
logger = logging.getLogger(__name__)
# Guild data
_default_data: dict[str, any] = {
"player": None,
}
class GuildData():
''' Class that holds all Discodrome data specific to a guild (not saved to disk) '''
def __init__(self) -> None:
self._data = _default_data
self.player = Player()
if self.player.queue is None:
self.player.queue = []
@property
def player(self) -> Player:
'''The guild's player.'''
return self._data["player"]
@player.setter
def player(self, value: Player) -> None:
self._data["player"] = value
_guild_data_instances: dict[int, GuildData] = {} # Dictionary to store temporary data for each guild instance
def guild_data(guild_id: int) -> GuildData:
''' Returns the temporary data for the chosen guild '''
# Return property if guild exists
if guild_id in _guild_data_instances:
return _guild_data_instances[guild_id]
# Create & store new data object if guild does not already exist
data = GuildData()
# Load queue from disk if it exists
if guild_properties(guild_id).queue is not None:
data.player.queue = guild_properties(guild_id).queue
_guild_data_instances[guild_id] = data
return _guild_data_instances[guild_id]
# Guild properties
class AutoplayMode(Enum):
''' Enum representing an autoplay mode '''
NONE : Final[int] = 0
RANDOM : Final[int] = 1
SIMILAR : Final[int] = 2
_default_properties: dict[str, any] = {
"queue": None,
"autoplay-mode": AutoplayMode.NONE,
}
class GuildProperties():
''' Class that holds all Discodrome properties specific to a guild (saved to disk) '''
def __init__(self) -> None:
self._properties = _default_properties
@property
def autoplay_mode(self) -> AutoplayMode:
'''The autoplay mode in use by this guild'''
return self._properties["autoplay-mode"]
@autoplay_mode.setter
def autoplay_mode(self, value: AutoplayMode) -> None:
self._properties["autoplay-mode"] = value
@property
def queue(self) -> list[Song]:
return self._properties["queue"]
@queue.setter
def queue(self, value: list[Song]) -> None:
self._properties["queue"] = value
_guild_property_instances: dict[int, GuildProperties] = {} # Dictionary to store properties for each guild instance
def guild_properties(guild_id: int) -> GuildProperties:
''' Returns the properties for the chosen guild '''
# Return property if guild exists
if guild_id in _guild_property_instances:
return _guild_property_instances[guild_id]
# Create & store new properties object if guild does not already exist
properties = GuildProperties()
_guild_property_instances[guild_id] = properties
return _guild_property_instances[guild_id]
def save_guild_properties_to_disk() -> None:
''' Saves guild properties to disk. '''
# Copy the queues from each guild data into each guild property
for guild_id, properties in _guild_property_instances.items():
properties.queue = guild_data(guild_id).player.queue
with open("guild_properties.pickle", "wb") as file:
try:
pickle.dump(_guild_property_instances, file, protocol=pickle.HIGHEST_PROTOCOL)
logger.info("Guild properties saved successfully.")
except pickle.PicklingError as err:
logger.error("Failed to save guild properties to disk.", exc_info=err)
def load_guild_properties_from_disk() -> None:
''' Loads guild properties that have been saved to disk. '''
if not os.path.exists("guild_properties.pickle"):
logger.info("Unable to load guild properties from disk. File was not found.")
return
with open("guild_properties.pickle", "rb") as file:
try:
_guild_property_instances.update(pickle.load(file))
logger.info("Guild properties loaded successfully.")
except pickle.UnpicklingError as err:
logger.error("Failed to load guild properties from disk.", exc_info=err)

112
discodrome.py Normal file
View File

@@ -0,0 +1,112 @@
import asyncio
import signal
import discord
import logging
import os
logger = logging.getLogger(__name__)
from discord.ext import commands
import data
from util import env
from util import logs
from subsonic import close_session, ping_api
class DiscodromeClient(commands.Bot):
''' An instance of the Discodrome client '''
test_guild: int
def __init__(self, test_guild: int=None) -> None:
self.test_guild = test_guild
super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
async def load_extensions(self) -> None:
''' Auto-loads all extensions present within the `./extensions` directory. '''
for file in os.listdir("./extensions"):
if file.endswith(".py"):
ext_name = file[:-3]
try:
await self.load_extension(f"extensions.{ext_name}")
except commands.errors.ExtensionError as err:
if isinstance(err, commands.errors.ExtensionNotFound):
logger.warning("Failed to load extension '%s'. Extension was not found.", ext_name)
if isinstance(err, commands.errors.ExtensionAlreadyLoaded):
logger.warning("Failed to load extension '%s'. Extension was already loaded.", ext_name)
if isinstance(err, commands.errors.NoEntryPointError):
logger.error("Failed to load extension '%s'. No entry point was found in the file.", ext_name, exc_info=err)
if isinstance(err, commands.errors.ExtensionFailed):
logger.error("Failed to load extension '%s'. Extension setup failed.", ext_name, exc_info=err)
else:
logger.info("Extension '%s' loaded successfully.", ext_name)
async def sync_command_tree(self) -> None:
''' Synchronizes the command tree with the guild used for testing. '''
guild = discord.Object(self.test_guild)
try:
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
logger.info("Slash commands synced to test guild %s", self.test_guild)
except discord.errors.Forbidden:
logger.error(
"Missing Access while syncing commands to guild %s. "
"Ensure the bot is invited to this server with scopes 'bot' and 'applications.commands', "
"and that `DISCORD_TEST_GUILD` is the correct server ID.",
self.test_guild,
)
except discord.HTTPException as err:
logger.warning("Failed to sync commands to guild %s: %s", self.test_guild, err)
async def setup_hook(self) -> None:
''' Setup done after login, prior to events being dispatched. '''
await self.load_extensions()
if await ping_api():
logger.info("Subsonic API is online.")
else:
logger.error("Subsonic API is unreachable.")
if self.test_guild:
await self.sync_command_tree()
async def on_ready(self) -> None:
''' Event called when the client is done preparing. '''
activity = discord.Activity(type=discord.ActivityType.playing, name=env.BOT_STATUS)
await self.change_presence(activity=activity)
logger.info(
"Logged as: %s | Connected Guilds: %s | Loaded Extensions: %s",
self.user,
len(self.guilds),
list(self.extensions),
)
logger.info("Bot status set to: '%s'", env.BOT_STATUS)
if __name__ == "__main__":
logs.setup_logging()
logger = logging.getLogger(__name__)
data.load_guild_properties_from_disk()
client = DiscodromeClient(test_guild=env.DISCORD_TEST_GUILD)
client.run(env.DISCORD_BOT_TOKEN, log_handler=None)
def exit_handler(signum, frame):
''' Function ran on application exit. '''
logger.debug("Beginning graceful shutdown...")
data.save_guild_properties_to_disk()
try:
loop = asyncio.get_event_loop()
loop.create_task(close_session())
except RuntimeError:
# If we can't get the event loop, create a new one as a fallback
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(close_session())
logger.info("Discodrome shutdown complete.")
# Register the exit handler
signal.signal(signal.SIGTERM, exit_handler)

473
extensions/music.py Normal file
View File

@@ -0,0 +1,473 @@
import discord
import logging
import asyncio
from discord import app_commands
from discord.ext import commands
from random import randint
import data
import copy
import subsonic
import ui
from discodrome import DiscodromeClient
logger = logging.getLogger(__name__)
class MusicCog(commands.Cog):
''' A Cog containing music playback commands '''
bot : DiscodromeClient
def __init__(self, bot: DiscodromeClient):
self.bot = bot
async def get_voice_client(self, interaction: discord.Interaction, *, should_connect: bool=False) -> discord.VoiceClient:
''' Returns a voice client instance for the current guild '''
# Get the voice client for the guild
voice_client = discord.utils.get(self.bot.voice_clients, guild=interaction.guild)
# Connect to a voice channel
if voice_client is None and should_connect:
try:
# Check if user is in a voice channel
if interaction.user.voice is None or interaction.user.voice.channel is None:
await ui.ErrMsg.user_not_in_voice_channel(interaction)
return None
# Check if we have permission to join the voice channel
permissions = interaction.user.voice.channel.permissions_for(interaction.guild.me)
if not permissions.connect or not permissions.speak:
logger.error("Missing permissions to connect or speak in voice channel")
await ui.ErrMsg.msg(interaction, "I don't have permission to join or speak in your voice channel.")
return None
# Add a small delay before connecting to avoid potential race conditions
await asyncio.sleep(1)
# Connect with timeout and retry logic
try:
voice_client = await interaction.user.voice.channel.connect(timeout=10.0, reconnect=True)
logger.info(f"Successfully connected to voice channel {interaction.user.voice.channel.id}")
except asyncio.TimeoutError:
logger.error("Timeout while connecting to voice channel")
await ui.ErrMsg.msg(interaction, "Timed out while trying to connect to voice channel. Please try again.")
return None
except discord.ClientException as e:
logger.error(f"Client exception when connecting to voice: {e}")
await ui.ErrMsg.msg(interaction, f"Error connecting to voice channel: {e}")
return None
except AttributeError as e:
logger.error(f"Attribute error when connecting to voice: {e}")
await ui.ErrMsg.cannot_connect_to_voice_channel(interaction)
except Exception as e:
logger.error(f"Unexpected error when connecting to voice: {e}")
await ui.ErrMsg.msg(interaction, f"An unexpected error occurred while connecting to voice: {e}")
return voice_client
@app_commands.command(name="play", description="Plays a specified track, album or playlist")
@app_commands.describe(querytype="Whether what you're searching is a track, album or playlist", query="Enter a search query")
@app_commands.choices(querytype=[
app_commands.Choice(name="Track", value="track"),
app_commands.Choice(name="Album", value="album"),
app_commands.Choice(name="Playlist", value="playlist"),
])
async def play(self, interaction: discord.Interaction, querytype: str=None, query: str=None) -> None:
''' Play a track matching the given title/artist query '''
# Check if user is in voice channel
if interaction.user.voice is None:
return await ui.ErrMsg.user_not_in_voice_channel(interaction)
# Get a valid voice channel connection
voice_client = await self.get_voice_client(interaction, should_connect=True)
# Don't attempt playback if the bot is already playing
if voice_client.is_playing() and query is None:
return await ui.ErrMsg.already_playing(interaction)
# Get the guild's player
player = data.guild_data(interaction.guild_id).player
# Check queue if no query is provided
if query is None:
# Display error if queue is empty & autoplay is disabled
if player.queue == [] and data.guild_properties(interaction.guild_id).autoplay_mode == data.AutoplayMode.NONE:
return await ui.ErrMsg.queue_is_empty(interaction)
# Begin playback of queue
await ui.SysMsg.starting_queue_playback(interaction)
await player.play_audio_queue(interaction, voice_client)
return
# Check querytype is not blank
if querytype is None:
return await ui.ErrMsg.msg(interaction, "Please provide a query type.")
# Check if the query is a track
if querytype == "track":
# Send our query to the subsonic API and retrieve a list of 1 song
songs = await subsonic.search(query, artist_count=0, album_count=0, song_count=1)
if songs == "Error":
await ui.ErrMsg.msg(interaction, f"An api error has occurred and has been logged to console. Please contact an administrator.")
return
# Display an error if the query returned no results
if len(songs) == 0:
await ui.ErrMsg.msg(interaction, f"No track found for **{query}**.")
return
# Add the first result to the queue and handle queue playback
player.queue.append(songs[0])
await ui.SysMsg.added_to_queue(interaction, songs[0])
elif querytype == "album":
# Send query to subsonic API and retrieve a list of 1 album
album = await subsonic.search_album(query)
if album == None:
await ui.ErrMsg.msg(interaction, f"No album found for **{query}**.")
return
# Add all songs from the album to the queue
for song in album.songs:
player.queue.append(song)
await ui.SysMsg.added_album_to_queue(interaction, album)
elif querytype == "playlist":
# Send query to subsonic API and retrieve a list of all playlists
playlists = await subsonic.get_user_playlists()
if playlists == None:
await ui.ErrMsg.msg(interaction, f"No playlists found.")
return
# Check if the specific playlist exists and get it's contents
playlist = None
playlist_id = None
for playlist in playlists:
if playlist["name"] == query:
playlist_id = playlist["id"]
break
if playlist_id == None:
await ui.ErrMsg.msg(interaction, f"No playlist found for **{query}**.")
return
else:
playlist = await subsonic.get_playlist(playlist_id)
if playlist == None:
# If we end up here then the following error message doesn't really cover it... It's more likely an error in this code
await ui.ErrMsg.msg(interaction, f"No playlist found for **{query}**.")
return
# Add all songs from the playlist to the queue
for song in playlist.songs:
player.queue.append(song)
await ui.SysMsg.added_playlist_to_queue(interaction, playlist)
await player.play_audio_queue(interaction, voice_client)
@play.error
async def play_error(self, ctx, error):
if isinstance(error, subsonic.APIError):
logging.error(f"An API error has occurred playing a track, code {error.code}: {error.message}")
await ui.ErrMsg.msg(ctx, "An API error has occurred and has been logged to console. Please contact an administrator.")
else:
logging.error(f"An error occurred while playing a track: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="stop", description="Stop playing the current track")
async def stop(self, interaction: discord.Interaction) -> None:
''' Disconnect from the active voice channel '''
player = data.guild_data(interaction.guild_id).player
if player.current_song is None:
ui.ErrMsg.not_playing(interaction)
# Get the voice client instance for the current guild
voice_client = await self.get_voice_client(interaction)
# Check if our voice client is connected
if voice_client is None:
await ui.ErrMsg.bot_not_in_voice_channel(interaction)
return
# Stop playback
voice_client.stop()
player.current_song = None
# Add current song back to the queue if exists
player.queue.insert(0, player.current_song)
# Display disconnect confirmation
await ui.SysMsg.stopping_queue_playback(interaction)
@stop.error
async def stop_error(self, ctx, error):
logging.error(f"An error occurred while stopping playback: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="queue", description="View the current queue")
async def show_queue(self, interaction: discord.Interaction) -> None:
''' Show the current queue '''
# Get the audio queue for the current guild
queue = data.guild_data(interaction.guild_id).player.queue
# Create a string to store the output of our queue
output = ""
# Add currently playing song to output if available
if data.guild_data(interaction.guild_id).player.current_song is not None:
song = data.guild_data(interaction.guild_id).player.current_song
output += f"**Now Playing:**\n{song.title} - *{song.artist}*\n{song.album} ({song.duration_printable})\n\n"
# Loop over our queue, adding each song into our output string
for i, song in enumerate(queue):
strtoadd = f"{i+1}. **{song.title}** - *{song.artist}*\n{song.album} ({song.duration_printable})\n\n"
if len(output+strtoadd) < 4083:
output += strtoadd
else:
remaining = len(queue) - i
output += f"**And {remaining} more...**"
break
# Check if our output string is empty & update it accordingly
if output == "":
output = "Queue is empty!"
# Show the user their queue
await ui.SysMsg.msg(interaction, "Queue", output)
@show_queue.error
async def show_queue_error(self, ctx, error):
logging.error(f"An error occurred while displaying the queue: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="clear", description="Clear the current queue")
async def clear_queue(self, interaction: discord.Interaction) -> None:
'''Clear the queue'''
queue = data.guild_data(interaction.guild_id).player.queue
queue.clear()
# Let the user know that the queue has been cleared
await ui.SysMsg.queue_cleared(interaction)
@clear_queue.error
async def clear_queue_error(self, ctx, error):
logging.error(f"An error occurred while clearing the queue: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="skip", description="Skip the current track")
async def skip(self, interaction: discord.Interaction) -> None:
''' Skip the current track '''
# Get the voice client instance
voice_client = await self.get_voice_client(interaction)
# Check if the bot is connected to a voice channel
if voice_client is None:
await ui.ErrMsg.bot_not_in_voice_channel(interaction)
return
# Check if the bot is playing music
if not voice_client.is_playing():
await ui.ErrMsg.not_playing(interaction)
return
await data.guild_data(interaction.guild_id).player.skip_track(interaction, voice_client)
@skip.error
async def skip_error(self, ctx, error):
logging.error(f"An error occurred while skipping a track: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="autoplay", description="Toggles autoplay")
@app_commands.describe(mode="Determines the method to use when autoplaying")
@app_commands.choices(mode=[
app_commands.Choice(name="None", value="none"),
app_commands.Choice(name="Random", value="random"),
app_commands.Choice(name="Similar", value="similar"),
])
async def autoplay(self, interaction: discord.Interaction, mode: app_commands.Choice[str]) -> None:
''' Toggles autoplay '''
logger.debug(f"Autoplay mode: {mode.value}")
# Update the autoplay properties
match mode.value:
case "none":
data.guild_properties(interaction.guild_id).autoplay_mode = data.AutoplayMode.NONE
case "random":
data.guild_properties(interaction.guild_id).autoplay_mode = data.AutoplayMode.RANDOM
case "similar":
data.guild_properties(interaction.guild_id).autoplay_mode = data.AutoplayMode.SIMILAR
# Display message indicating new status of autoplay
if mode.value == "none":
await ui.SysMsg.msg(interaction, f"Autoplay disabled by {interaction.user.display_name}")
else:
await ui.SysMsg.msg(interaction, f"Autoplay enabled by {interaction.user.display_name}", f"Autoplay mode: **{mode.name}**")
# If the bot is connected to a voice channel and autoplay is enabled, start queue playback
voice_client = await self.get_voice_client(interaction)
logger.debug(f"Voice client: {voice_client}")
if voice_client:
logger.debug(f"Is playing: {voice_client.is_playing()}")
if voice_client is not None and not voice_client.is_playing():
player = data.guild_data(interaction.guild_id).player
logger.debug(f"Queue: {player.queue}")
try:
logger.debug(f"Current song: {player.current_song.title}")
except AttributeError:
logger.debug("No current song")
logger.debug("Playing audio queue...")
await player.play_audio_queue(interaction, voice_client)
@autoplay.error
async def autoplay_error(self, ctx, error):
if isinstance(error, subsonic.APIError):
logging.error(f"An API error has occurred while toggling autoplay, code {error.code}: {error.message}")
await ui.ErrMsg.msg(ctx, "An API error has occurred and has been logged to console. Please contact an administrator.")
else:
logging.error(f"An error occurred while toggling autoplay: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="shuffle", description="Shuffles the current queue")
async def shuffle(self, interaction: discord.Interaction):
''' Randomize current queue using Fisher-Yates algorithm '''
temporaryqueue = copy.deepcopy(data.guild_data(interaction.guild_id).player.queue)
shuffledqueue = []
while len(temporaryqueue) > 0:
randomindex = randint(0, len(temporaryqueue) - 1)
shuffledqueue.append(temporaryqueue.pop(randomindex))
data.guild_data(interaction.guild_id).player.queue = shuffledqueue
await ui.SysMsg.msg(interaction, "Queue shuffled!")
@shuffle.error
async def shuffle_error(self, ctx, error):
logging.error(f"An error occurred while shuffling the queue: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="disco", description="Plays the artist's entire discography")
@app_commands.describe(artist="The artist to play")
async def disco(self, interaction: discord.Interaction, artist: str):
''' Play the artist's entire discography'''
# Get a valid voice channel connection
voice_client = await self.get_voice_client(interaction, should_connect=True)
# Get the guild's player
player = data.guild_data(interaction.guild_id).player
# Send our query to the subsonic API and retrieve list of albums in artist's discography
albums = await subsonic.get_artist_discography(artist)
if albums == None:
await ui.ErrMsg.msg(interaction, f"No discography found for **{artist}**.")
return
# Add all songs from the artist's discography to the queue
for album in albums:
for song in album.songs:
player.queue.append(song)
# Display a message that discography was added to the queue
await ui.SysMsg.added_discography_to_queue(interaction, artist, albums)
# Begin playback of queue
await player.play_audio_queue(interaction, voice_client)
@disco.error
async def disco_error(self, ctx, error):
if isinstance(error, subsonic.APIError):
logging.error(f"An API error has occurred while playing an artist's discography, code {error.code}: {error.message}")
await ui.ErrMsg.msg(ctx, "An API error has occurred and has been logged to console. Please contact an administrator.")
else:
logging.error(f"An error occurred while playing an artist's discography: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@app_commands.command(name="playlists", description="List all playlists")
async def list_playlists(self, interaction):
# Send query to subsonic API and retrieve a list of all playlists
playlists = await subsonic.get_user_playlists()
if playlists == None:
await ui.ErrMsg.msg(interaction, f"No playlists found.")
return
# Create a string to store the output
output = ""
# Loop over the list of playlists, adding each one into our output string
for i, playlist in enumerate(playlists):
strtoadd = f"{i+1}. **{playlist['name']}** \n{playlist['songCount']} songs - {(playlist['duration'] // 60):02d}m {(playlist['duration'] % 60):02d}s\n\n"
if len(output+strtoadd) < 4083:
output += strtoadd
else:
remaining = len(playlists) - i
output += f"**And {remaining} more...**"
break
# Check if our output string is empty & update it accordingly
if output == "":
output = "No playlists found."
# Show the user their queue
await ui.SysMsg.msg(interaction, "Available playlists", output)
@list_playlists.error
async def playlists_error(self, ctx, error):
if isinstance(error, subsonic.APIError):
logging.error(f"An API error has occurred while fetching playlists, code {error.code}: {error.message}")
await ui.ErrMsg.msg(ctx, "An API error has occurred and has been logged to console. Please contact an administrator.")
else:
logging.error(f"An error occurred while fetching playlists: {error}")
await ui.ErrMsg.msg(ctx, f"An unknown error has occurred and has been logged to console. Please contact an administrator. {error}")
@commands.Cog.listener()
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState) -> None:
''' Event called when a user's voice state changes '''
# Check if the bot is connected to a voice channel
voice_client = discord.utils.get(self.bot.voice_clients, guild=member.guild)
# Check if the bot is connected to a voice channel
if voice_client is None:
return
# Check if the bot is alone in the voice channel
if len(voice_client.channel.members) == 1:
logger.debug("Bot is alone in voice channel, waiting 10 seconds before disconnecting...")
# Wait for 10 seconds
await asyncio.sleep(10)
# Check again if there are still no users in the voice channel
if len(voice_client.channel.members) == 1:
# Disconnect the bot and clear the queue
await voice_client.disconnect()
player = data.guild_data(member.guild.id).player
player.queue.clear()
player.current_song = None
logger.info("The bot has disconnected and cleared the queue as there are no users in the voice channel.")
else:
logger.debug("Bot is no longer alone in voice channel, aborting disconnect...")
async def setup(bot: DiscodromeClient):
''' Setup function for the music.py cog '''
await bot.add_cog(MusicCog(bot))

9
extensions/owner.py Normal file
View File

@@ -0,0 +1,9 @@
'''An extention containing functionality exclusive to the bot owner'''
import logging
logger = logging.getLogger(__name__)
async def setup(bot):
'''Empty setup function for the owner.py cog'''
pass

261
player.py Normal file
View File

@@ -0,0 +1,261 @@
''' A player object that handles playback and data for its respective guild '''
import asyncio
import discord
import data
import ui
import logging
from subsonic import Song, APIError, get_random_songs, get_similar_songs, stream
logger = logging.getLogger(__name__)
# Default player data
_default_data: dict[str, any] = {
"current-song": None,
"current-position": 0,
"queue": [],
}
class Player():
''' Class that represents an audio player '''
def __init__(self) -> None:
self._data = _default_data
self._player_loop = None
@property
def current_song(self) -> Song:
'''The current song'''
return self._data["current-song"]
@current_song.setter
def current_song(self, song: Song) -> None:
self._data["current-song"] = song
@property
def current_position(self) -> int:
''' The current position for the current song, in seconds. '''
return self._data["current-position"]
@current_position.setter
def current_position(self, position: int) -> None:
''' Set the current position for the current song, in seconds. '''
self._data["current-position"] = position
@property
def queue(self) -> list[Song]:
''' The current audio queue. '''
return self._data["queue"]
@queue.setter
def queue(self, value: list) -> None:
self._data["queue"] = value
@property
def player_loop(self) -> asyncio.AbstractEventLoop:
''' The player loop '''
return self._player_loop
@player_loop.setter
def player_loop(self, loop: asyncio.AbstractEventLoop) -> None:
self._player_loop = loop
async def stream_track(self, interaction: discord.Interaction, song: Song, voice_client: discord.VoiceClient) -> None:
''' Streams a track from the Subsonic server to a connected voice channel, and updates guild data accordingly '''
# Make sure the voice client is available and connected
if voice_client is None:
await ui.ErrMsg.bot_not_in_voice_channel(interaction)
return
# Check if the voice client is still connected
if not voice_client.is_connected():
logger.error("Voice client is not connected")
await ui.ErrMsg.msg(interaction, "Voice connection was lost. Please try again.")
return
# Make sure the bot isn't already playing music
if voice_client.is_playing():
await ui.ErrMsg.already_playing(interaction)
return
# Get the stream from the Subsonic server, using the provided song's ID
ffmpeg_options = {"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
"options": "-filter:a volume=replaygain=track"}
try:
stream_url = await stream(song.song_id)
if not stream_url:
logger.error("Failed to get stream URL")
await ui.ErrMsg.msg(interaction, "Failed to get audio stream. Please try again.")
return
audio_src = discord.FFmpegOpusAudio(stream_url, **ffmpeg_options)
except APIError as err:
logger.error(f"API Error streaming song, Code {err.errorcode}: {err.message}")
await ui.ErrMsg.msg(interaction, f"API error while streaming song: {err.message}")
return
except Exception as e:
logger.error(f"Unexpected error getting audio stream: {e}")
await ui.ErrMsg.msg(interaction, "An error occurred while preparing the audio. Please try again.")
return
# Begin playing the song
loop = asyncio.get_event_loop()
self.player_loop = loop
# Handle playback finished
async def playback_finished(error):
if error:
logger.error(f"An error occurred while playing the audio: {error}")
# Check if the error is related to voice connection
if "Not connected to voice" in str(error):
logger.warning("Voice connection was lost during playback")
# Try to reconnect if possible
if interaction.user and interaction.user.voice and interaction.user.voice.channel:
try:
# Try to reconnect to the voice channel
if voice_client and not voice_client.is_connected():
await voice_client.connect(timeout=10.0, reconnect=True)
logger.info("Successfully reconnected to voice channel")
except Exception as e:
logger.error(f"Failed to reconnect to voice channel: {e}")
return
logger.debug("Playback finished.")
try:
# Only proceed if voice client is still connected
if voice_client and voice_client.is_connected():
future = asyncio.run_coroutine_threadsafe(self.play_audio_queue(interaction, voice_client), loop)
# Add a callback to handle any exceptions that occur during execution
future.add_done_callback(lambda f: logger.error(f"Error in play_audio_queue: {f.exception()}") if f.exception() else None)
else:
logger.warning("Voice client disconnected, cannot continue queue playback")
except Exception as e:
logger.error(f"Failed to schedule play_audio_queue: {e}")
# Try to play the audio with retry logic
max_attempts = 3
attempt = 0
while attempt < max_attempts:
try:
# Check again if voice client is still connected before playing
if not voice_client.is_connected():
logger.error("Voice client disconnected before playing")
await ui.ErrMsg.msg(interaction, "Voice connection was lost. Please try again.")
return
voice_client.play(audio_src, after=lambda e: loop.create_task(playback_finished(e)))
logger.info(f"Started playing: {song.title} by {song.artist}")
return # Success, exit the function
except discord.ClientException as e:
logger.error(f"Discord client exception while playing audio (attempt {attempt+1}): {e}")
attempt += 1
if attempt >= max_attempts:
await ui.ErrMsg.msg(interaction, "Failed to play audio after multiple attempts. Please try again.")
return
await asyncio.sleep(1) # Wait before retrying
except Exception as err:
logger.error(f"An error occurred while playing the audio: {err}")
await ui.ErrMsg.msg(interaction, "An error occurred while playing the audio. Please try again.")
return
async def handle_autoplay(self, interaction: discord.Interaction, prev_song_id: str=None) -> bool:
''' Handles populating the queue when autoplay is enabled '''
autoplay_mode = data.guild_properties(interaction.guild_id).autoplay_mode
queue = data.guild_data(interaction.guild_id).player.queue
logger.debug("Handling autoplay...")
logger.debug(f"Autoplay mode: {autoplay_mode}")
logger.debug(f"Queue: {queue}")
# If queue is notempty or autoplay is disabled, don't handle autoplay
if queue != [] or autoplay_mode is data.AutoplayMode.NONE:
return False
# If there was no previous song provided, we default back to selecting a random song
if prev_song_id is None:
autoplay_mode = data.AutoplayMode.RANDOM
logging.info("No previous song ID provided. Defaulting to random.")
songs = []
try:
match autoplay_mode:
case data.AutoplayMode.RANDOM:
songs = await get_random_songs(size=1)
case data.AutoplayMode.SIMILAR:
logger.debug(f"Prev song ID: {prev_song_id}")
songs = await get_similar_songs(song_id=prev_song_id, count=1)
except APIError as err:
logging.error(f"API Error fetching song for autoplay, Code {err.errorcode}: {err.message}")
logger.debug(f"Autoplay song: {songs}")
# If there's no match, throw an error
if len(songs) == 0:
await ui.ErrMsg.msg(interaction, "Failed to obtain a song for autoplay.")
return False
self.queue.append(songs[0])
return True
async def play_audio_queue(self, interaction: discord.Interaction, voice_client: discord.VoiceClient) -> None:
''' Plays the audio queue '''
# Check if the bot is connected to a voice channel; it's the caller's responsibility to open a voice channel
if voice_client is None:
await ui.ErrMsg.bot_not_in_voice_channel(interaction)
return
# Check if the bot is already playing something
if voice_client.is_playing():
return
# Check if the queue contains songs
if self.queue != []:
# Pop the first item from the queue and stream the track
song = self.queue.pop(0)
self.current_song = song
await ui.SysMsg.now_playing(interaction, song)
await self.stream_track(interaction, song, voice_client)
else:
logger.debug("Queue is empty.")
logger.debug("Current song: %s", self.current_song)
if self.current_song is not None:
prev_song_id = self.current_song.song_id
self.current_song = None
else:
prev_song_id = None
# Handle autoplay if queue is empty
if await self.handle_autoplay(interaction, prev_song_id=prev_song_id):
await self.play_audio_queue(interaction, voice_client)
return
# If the queue is empty, playback has ended; we should let the user know
await ui.SysMsg.playback_ended(interaction)
async def skip_track(self, interaction: discord.Interaction, voice_client: discord.VoiceClient) -> None:
''' Skips the current track and plays the next one in the queue '''
# Check if the bot is connected to a voice channel; it's the caller's responsibility to open a voice channel
if voice_client is None:
await ui.ErrMsg.bot_not_in_voice_channel(interaction)
return
logger.debug("Skipping track...")
# Check if the bot is already playing something
if voice_client.is_playing():
voice_client.stop()
await ui.SysMsg.skipping(interaction)
else:
await ui.ErrMsg.not_playing(interaction)

4
requirements.txt Normal file
View File

@@ -0,0 +1,4 @@
discord
pynacl
python-dotenv
requests

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
resources/discodrome.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

573
subsonic.py Normal file
View File

@@ -0,0 +1,573 @@
''' For interfacing with the Subsonic API '''
import logging
import os
import aiohttp
from pathlib import Path
from util import env
logger = logging.getLogger(__name__)
# Parameters for the Subsonic API
SUBSONIC_REQUEST_PARAMS = {
"u": env.SUBSONIC_USER,
"p": env.SUBSONIC_PASSWORD,
"v": "1.15.0",
"c": "discodrome",
"f": "json"
}
globalsession = None
async def get_session() -> aiohttp.ClientSession:
''' Get an aiohttp session '''
global globalsession
if globalsession is None:
globalsession = aiohttp.ClientSession()
return globalsession
async def close_session() -> None:
''' Close the aiohttp session '''
global globalsession
if globalsession is not None:
globalsession.close()
globalsession = None
class APIError(Exception):
''' Exception raised for errors in the Subsonic API '''
def __init__(self, errorcode: int, message: str) -> None:
self.errorcode = errorcode
self.message = message
super().__init__(self.message)
class Song():
''' Object representing a song returned from the Subsonic API '''
def __init__(self, json_object: dict) -> None:
#! Other properties exist in the initial json response but are currently unused by Discodrome and thus aren't supported here
self._id: str = json_object["id"] if "id" in json_object else ""
self._title: str = json_object["title"] if "title" in json_object else "Unknown Track"
self._album: str = json_object["album"] if "album" in json_object else "Unknown Album"
self._artist: str = json_object["artist"] if "artist" in json_object else "Unknown Artist"
self._cover_id: str = json_object["coverArt"] if "coverArt" in json_object else ""
self._duration: int = json_object["duration"] if "duration" in json_object else 0
@property
def song_id(self) -> str:
''' The song's id '''
return self._id
@property
def title(self) -> str:
''' The song's title '''
return self._title
@property
def album(self) -> str:
''' The album containing the song '''
return self._album
@property
def artist(self) -> str:
''' The song's artist '''
return self._artist
@property
def cover_id(self) -> str:
''' The id of the cover art used by the song '''
return self._cover_id
@property
def duration(self) -> int:
''' The total duration of the song '''
return self._duration
@property
def duration_printable(self) -> str:
''' The total duration of the song as a human readable string in the format `mm:ss` '''
return f"{(self._duration // 60):02d}:{(self._duration % 60):02d}"
class Album():
''' Object representing an album returned from subsonic API '''
def __init__(self, json_object: dict) -> None:
self._id: str = json_object["id"] if "id" in json_object else ""
self._name: str = json_object["name"] if "name" in json_object else "Unknown Album"
self._artist: str = json_object["artist"] if "artist" in json_object else "Unknown Artist"
self._cover_id: str = json_object["coverArt"] if "coverArt" in json_object else ""
self._song_count: int = json_object["songCount"] if "songCount" in json_object else 0
self._duration: int = json_object["duration"] if "duration" in json_object else 0
self._year: int = json_object["year"] if "year" in json_object else 0
self._songs: list[Song] = []
for song in json_object["song"]:
self._songs.append(Song(song))
@property
def album_id(self) -> str:
''' The album's id '''
return self._id
@property
def name(self) -> str:
''' The album's name '''
return self._name
@property
def artist(self) -> str:
''' The album's artist '''
return self._artist
@property
def cover_id(self) -> str:
''' The id of the cover art used by the album '''
return self._cover_id
@property
def song_count(self) -> int:
''' The number of songs in the album '''
return self._song_count
@property
def duration(self) -> int:
''' The total duration of the album '''
return self._duration
@property
def duration_printable(self) -> str:
''' The total duration of the album as a human readable string in the format `mm:ss` '''
return f"{(self._duration // 60):02d}:{(self._duration % 60):02d}"
@property
def year(self) -> int:
''' The year the album was released '''
return self._year
@property
def songs(self) -> list[Song]:
''' The songs in the album '''
return self._songs
class Playlist():
''' Object representing a playlist returned from subsonic API '''
def __init__(self, json_object: dict) -> None:
self._id: str = json_object["id"] if "id" in json_object else ""
self._name: str = json_object["name"] if "name" in json_object else "Unknown Album"
self._cover_id: str = json_object["coverArt"] if "coverArt" in json_object else ""
self._song_count: int = json_object["songCount"] if "songCount" in json_object else 0
self._duration: int = json_object["duration"] if "duration" in json_object else 0
self._songs: list[Song] = []
for song in json_object["entry"]:
self._songs.append(Song(song))
@property
def playlist_id(self) -> str:
''' The playlist's id '''
return self._id
@property
def name(self) -> str:
''' The playlist's name '''
return self._name
@property
def cover_id(self) -> str:
''' The id of the cover art used by the playlist '''
return self._cover_id
@property
def song_count(self) -> int:
''' The number of songs in the playlist '''
return self._song_count
@property
def duration(self) -> int:
''' The total duration of the playlist '''
return self._duration
@property
def duration_printable(self) -> str:
''' The total duration of the playlist as a human readable string in the format `mm:ss` '''
return f"{(self._duration // 60):02d}:{(self._duration % 60):02d}"
@property
def songs(self) -> list[Song]:
''' The songs in the playlist '''
return self._songs
async def ping_api() -> bool:
''' Send a ping request to the subsonic API '''
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/ping.view", params=SUBSONIC_REQUEST_PARAMS) as response:
response.raise_for_status()
ping_data = await response.json()
if await check_subsonic_error(ping_data):
return False
logger.debug("Ping Response: %s", ping_data)
return True
async def check_subsonic_error(response: dict[str, any]) -> bool:
''' Checks and logs error codes returned by the subsonic API. Returns true if an error is present '''
logging.debug("Checking for subsonic error...")
if isinstance(response, aiohttp.ClientResponse):
try:
response = await response.json()
except Exception as e:
return False
if response["subsonic-response"]["status"] == "ok":
logging.debug("No error found.")
return False
err_code = response["subsonic-response"]["error"]["code"]
match err_code:
case 0:
err_msg = "Generic Error."
raise APIError(err_code, err_msg)
case 10:
err_msg = "Required Parameter Missing."
raise APIError(err_code, err_msg)
case 20:
err_msg = "Incompatible Subsonic REST protocol version. Client must upgrade."
raise APIError(err_code, err_msg)
case 30:
err_msg = "Incompatible Subsonic REST protocol version. Server must upgrade."
raise APIError(err_code, err_msg)
case 40:
err_msg = "Wrong username or password."
raise APIError(err_code, err_msg)
case 41:
err_msg = "Token authentication not supported for LDAP users."
raise APIError(err_code, err_msg)
case 50:
err_msg = "User is not authorized for the given operation."
raise APIError(err_code, err_msg)
case 60:
err_msg = "The trial period for the Subsonic server is over."
raise APIError(err_code, err_msg)
case 70:
err_msg = "The requested data was not found."
case _:
err_msg = "Unknown Error Code."
raise APIError(err_code, err_msg)
logger.warning("Subsonic API request responded with error code %s: %s", err_code, err_msg)
return True
async def search(query: str, *, artist_count: int=00, artist_offset: int=0, album_count: int=0, album_offset: int=0, song_count: int=1, song_offset: int=0) -> list[Song]:
''' Send a search request to the subsonic API '''
# Sanitize special characters in the user's query
#parsed_query = urlParse.quote(query, safe='')
search_params = {
"query": query, #todo: fix parsed query
"artistCount": str(artist_count),
"artistOffset": str(artist_offset),
"albumCount": str(album_count),
"albumOffset": str(album_offset),
"songCount": str(song_count),
"songOffset": str(song_offset)
}
params = SUBSONIC_REQUEST_PARAMS | search_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/search3.view", params=params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return []
logger.debug("Search Response: %s", search_data)
results: list[Song] = []
try:
for item in search_data["subsonic-response"]["searchResult3"]["song"]:
results.append(Song(item))
except KeyError:
return []
return results
async def search_album(query: str) -> list[Album]:
''' Send a search request to the subsonic API to return 1 album and all its songs '''
# Sanitize special characters in the user's query
#parsed_query = urlParse.quote(query, safe='')
search_params = {
"query": query,
"artistCount": "0",
"albumCount": "1",
"albumOffset": "0",
"songCount": "0",
"songOffset": "0"
}
params = SUBSONIC_REQUEST_PARAMS | search_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/search3.view", params=params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return None
try:
albumid = search_data["subsonic-response"]["searchResult3"]["album"][0]["id"]
except Exception as e:
return None
logger.debug("Album ID: %s", albumid)
album_params = {
"id": albumid
}
album_params = SUBSONIC_REQUEST_PARAMS | album_params
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getAlbum.view", params=album_params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return None
logger.debug("Search Response: %s", search_data)
try:
album = Album(search_data["subsonic-response"]["album"])
except Exception as e:
logger.error("Failed to parse album data: %s", e)
return None
return album
async def get_user_playlists() -> list[int]:
''' Retrive metadata of all playlists the Subsonic user is authorised to play '''
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getPlaylists.view", params=SUBSONIC_REQUEST_PARAMS) as response:
response.raise_for_status()
query_data = await response.json()
if await check_subsonic_error(query_data):
return None
logger.debug("Playlists query response: %s", query_data)
playlists = query_data["subsonic-response"]["playlists"]["playlist"]
return playlists
async def get_playlist(id: str) -> Playlist:
''' Retrive the contents of a specific playlist '''
playlist_params = {
"id": id
}
params = SUBSONIC_REQUEST_PARAMS | playlist_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getPlaylist.view", params=params) as response:
response.raise_for_status()
playlist = await response.json()
if await check_subsonic_error(playlist):
return None
logger.debug("Playlist query response: %s", playlist)
try:
playlist = Playlist(playlist["subsonic-response"]["playlist"])
except Exception as e:
logger.error("Failed to parse playlist data: %s", e)
return None
return playlist
async def get_artist_id(query: str) -> str:
''' Send a search request to the subsonic API to return the id of an artist '''
search_params = {
"query": query,
"artistCount": "1",
"albumCount": "0",
"albumOffset": "0",
"songCount": "0",
"songOffset": "0"
}
params = SUBSONIC_REQUEST_PARAMS | search_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/search3.view", params=params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return None
artistid = search_data["subsonic-response"]["searchResult3"]["artist"][0]["id"]
logger.debug("Artist ID: %s", artistid)
return artistid
async def get_artist_discography(query: str) -> Album:
''' Send a search request to the subsonic API to return all albums by an artist '''
artistid = await get_artist_id(query)
artist_params = {
"id": artistid
}
artist_params = SUBSONIC_REQUEST_PARAMS | artist_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getArtist.view", params=artist_params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return None
logger.debug("Search Response: %s", search_data)
albums = search_data["subsonic-response"]["artist"]["album"]
album_list : list[Album] = []
for albuminfo in albums:
albumid = albuminfo["id"]
album_params = {
"id": albumid
}
album_params = SUBSONIC_REQUEST_PARAMS | album_params
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getAlbum.view", params=album_params) as response:
response.raise_for_status()
album = await response.json()
if await check_subsonic_error(album):
return None
logger.debug("Search Response: %s", album)
album = Album(album["subsonic-response"]["album"])
album_list.append(album)
return album_list
async def get_album_art_file(cover_id: str, size: int=300) -> str:
''' Request album art from the subsonic API '''
target_path = f"cache/{cover_id}.jpg"
# Check if the cover art is already cached (TODO: Check for last-modified date?)
if os.path.exists(target_path):
return target_path
cover_params = {
"id": cover_id,
"size": str(size)
}
params = SUBSONIC_REQUEST_PARAMS | cover_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getCoverArt", params=params) as response:
logging.debug("Response: %s", response.content)
if await check_subsonic_error(response) or response.status != 200:
return "resources/cover_not_found.jpg"
file = Path(target_path)
file.parent.mkdir(exist_ok=True, parents=True)
file.write_bytes(await response.read())
return target_path
async def get_random_songs(size: int=None, genre: str=None, from_year: int=None, to_year: int=None, music_folder_id: str=None) -> list[Song]:
''' Request random songs from the subsonic API '''
logger.debug("Requesting random song...")
search_params: dict[str, any] = {}
# Handle Optional params
if size is not None:
search_params["size"] = size
if genre is not None:
search_params["genre"] = genre
if from_year is not None:
search_params["fromYear"] = from_year
if to_year is not None:
search_params["toYear"] = to_year
if music_folder_id is not None:
search_params["musicFolderId"] = music_folder_id
params = SUBSONIC_REQUEST_PARAMS | search_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getRandomSongs.view", params=params) as response:
response.raise_for_status()
search_data = await response.json()
if await check_subsonic_error(search_data):
return []
logger.debug("Search Response: %s", search_data)
results: list[Song] = []
for item in search_data["subsonic-response"]["randomSongs"]["song"]:
results.append(Song(item))
return results
async def get_similar_songs(song_id: str, count: int=1) -> list[Song]:
''' Request similar songs from the subsonic API '''
logger.debug("Requesting similar song...")
logger.debug("Song id: %s", song_id)
if song_id is None:
return []
search_params = {
"id": song_id,
"count": count
}
params = SUBSONIC_REQUEST_PARAMS | search_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/getSimilarSongs.view", params=params) as response:
response.raise_for_status()
search_data = await response.json()
logging.debug("Json Response: %s", search_data)
subsonic_error = await check_subsonic_error(search_data)
logger.debug("Subsonic error: %s", subsonic_error)
if subsonic_error:
logger.debug("Subsonic error. Returning empty list.")
return []
results: list[Song] = []
if search_data["subsonic-response"]["similarSongs"] == {}:
logging.debug("No similar songs found. Returning empty list.")
return []
logger.debug("Similar songs: %s", search_data["subsonic-response"]["similarSongs"]["song"])
for item in search_data["subsonic-response"]["similarSongs"]["song"]:
results.append(Song(item))
logger.debug("Similar songs: %s", results)
return results
async def stream(stream_id: str):
''' Send a stream request to the subsonic API '''
stream_params = {
"id": stream_id
# TODO: handle other params
}
params = SUBSONIC_REQUEST_PARAMS | stream_params
session = await get_session()
async with await session.get(f"{env.SUBSONIC_SERVER}/rest/stream.view", params=params, timeout=20) as response:
response.raise_for_status()
if response.content_type == "text/xml":
logger.error("Failed to stream song: %s", await response.text())
return None
return str(response.url)

253
ui.py Normal file
View File

@@ -0,0 +1,253 @@
import discord
import logging
import asyncio
from subsonic import Song, Album, Playlist, get_album_art_file
logger = logging.getLogger(__name__)
class SysMsg:
''' A class for sending system messages '''
@staticmethod
async def msg(interaction: discord.Interaction, header: str, message: str=None, thumbnail: str=None, *, ephemeral: bool=False) -> None:
''' Generic message function. Creates a message formatted as an embed '''
# Check if interaction is still valid
if interaction is None or interaction.guild is None:
logger.warning("Cannot send message: interaction is no longer valid")
return
# Handle message over character limit
if message is not None and len(message) > 4096:
message = message[:4093] + "..."
embed = discord.Embed(color=discord.Color(0x50C470), title=header, description=message)
file = discord.utils.MISSING
# Attach a thumbnail if one was provided (as a local file)
if thumbnail is not None:
try:
file = discord.File(thumbnail, filename="image.png")
embed.set_thumbnail(url="attachment://image.png")
except Exception as e:
logger.error(f"Failed to attach thumbnail: {e}")
# Continue without the thumbnail
# Attempt to send the message, up to 3 times
attempt = 0
while attempt < 3:
try:
# Check if the interaction response is already done
if interaction.response.is_done():
# Use followup
await interaction.followup.send(file=file, embed=embed, ephemeral=ephemeral)
return
else:
# Use initial response
await interaction.response.send_message(file=file, embed=embed, ephemeral=ephemeral)
return
except discord.NotFound:
logger.warning("Attempt %d at sending a system message failed (NotFound)...", attempt+1)
attempt += 1
# Short delay before retrying
await asyncio.sleep(0.5)
except discord.HTTPException as e:
logger.warning("Attempt %d at sending a system message failed (HTTPException: %s)...", attempt+1, e)
attempt += 1
await asyncio.sleep(0.5)
except Exception as e:
logger.error("Unexpected error when sending system message: %s", e)
attempt += 1
await asyncio.sleep(0.5)
# If we've exhausted all attempts, log a more detailed error
logger.error("Failed to send system message after %d attempts. Header: %s", attempt, header)
@staticmethod
async def now_playing(interaction: discord.Interaction, song: Song) -> None:
''' Sends a message containing the currently playing song '''
cover_art = await get_album_art_file(song.cover_id)
desc = f"**{song.title}** - *{song.artist}*\n{song.album} ({song.duration_printable})"
await __class__.msg(interaction, "Now Playing:", desc, cover_art)
@staticmethod
async def playback_ended(interaction: discord.Interaction) -> None:
''' Sends a message indicating playback has ended '''
await __class__.msg(interaction, "Playback ended")
@staticmethod
async def disconnected(interaction: discord.Interaction) -> None:
''' Sends a message indicating the bot disconnected from voice channel '''
await __class__.msg(interaction, "Disconnected from voice channel")
@staticmethod
async def starting_queue_playback(interaction: discord.Interaction) -> None:
''' Sends a message indicating queue playback has started '''
await __class__.msg(interaction, "Started queue playback")
@staticmethod
async def stopping_queue_playback(interaction: discord.Interaction) -> None:
''' Sends a message indicating queue playback has stopped '''
await __class__.msg(interaction, "Stopped queue playback")
@staticmethod
async def added_to_queue(interaction: discord.Interaction, song: Song) -> None:
''' Sends a message indicating the selected song was added to queue '''
desc = f"**{song.title}** - *{song.artist}*\n{song.album} ({song.duration_printable})"
cover_art = await get_album_art_file(song.cover_id)
await __class__.msg(interaction, f"{interaction.user.display_name} added track to queue", desc, cover_art)
@staticmethod
async def added_album_to_queue(interaction: discord.Interaction, album: Album) -> None:
''' Sends a message indicating the selected album was added to queue '''
desc = f"**{album.name}** - *{album.artist}*\n{album.song_count} songs ({album.duration} seconds)"
cover_art = await get_album_art_file(album.cover_id)
await __class__.msg(interaction, f"{interaction.user.display_name} added album to queue", desc, cover_art)
@staticmethod
async def added_playlist_to_queue(interaction: discord.Interaction, playlist: Playlist) -> None:
''' Sends a message indicating the selected playlist was added to queue '''
desc = f"**{playlist.name}**\n{playlist.song_count} songs ({playlist.duration} seconds)"
cover_art = await get_album_art_file(playlist.cover_id)
await __class__.msg(interaction, f"{interaction.user.display_name} added playlist to queue", desc, cover_art)
@staticmethod
async def added_discography_to_queue(interaction: discord.Interaction, artist: str, albums: list[Album]) -> None:
''' Sends a message indicating the selected artist's discography was added to queue '''
desc = f"**{artist}**\n{len(albums)} albums\n\n"
cover_art = await get_album_art_file(albums[0].cover_id)
for counter in range(len(albums)):
album = albums[counter]
desc += f"**{str(counter+1)}. {album.name}**\n{album.song_count} songs ({album.duration} seconds)\n\n"
await __class__.msg(interaction, f"{interaction.user.display_name} added discography to queue", desc, cover_art)
@staticmethod
async def queue_cleared(interaction: discord.Interaction) -> None:
''' Sends a message indicating a user cleared the queue '''
await __class__.msg(interaction, f"{interaction.user.display_name} cleared the queue")
@staticmethod
async def skipping(interaction: discord.Interaction) -> None:
''' Sends a message indicating the current song was skipped '''
await __class__.msg(interaction, "Skipped track", ephemeral=True)
class ErrMsg:
''' A class for sending error messages '''
@staticmethod
async def msg(interaction: discord.Interaction, message: str) -> None:
''' Generic message function. Creates an error message formatted as an embed '''
# Check if interaction is still valid
if interaction is None or interaction.guild is None:
logger.warning("Cannot send error message: interaction is no longer valid")
return
embed = discord.Embed(color=discord.Color(0x50C470), title="Error", description=message)
# Attempt to send the error message, up to 3 times
attempt = 0
while attempt < 3:
try:
if interaction.response.is_done():
await interaction.followup.send(embed=embed, ephemeral=True)
return
else:
await interaction.response.send_message(embed=embed, ephemeral=True)
return
except discord.NotFound:
logger.warning("Attempt %d at sending an error message failed (NotFound)...", attempt+1)
attempt += 1
# Short delay before retrying
await asyncio.sleep(0.5)
except discord.HTTPException as e:
logger.warning("Attempt %d at sending an error message failed (HTTPException: %s)...", attempt+1, e)
attempt += 1
await asyncio.sleep(0.5)
except Exception as e:
logger.error("Unexpected error when sending error message: %s", e)
attempt += 1
await asyncio.sleep(0.5)
# If we've exhausted all attempts, log a more detailed error
logger.error("Failed to send error message after %d attempts. Message: %s", attempt, message)
@staticmethod
async def user_not_in_voice_channel(interaction: discord.Interaction) -> None:
''' Sends an error message indicating user is not in a voice channel '''
await __class__.msg(interaction, "You are not connected to a voice channel.")
@staticmethod
async def bot_not_in_voice_channel(interaction: discord.Interaction) -> None:
''' Sends an error message indicating bot is connect to a voice channel '''
await __class__.msg(interaction, "Not currently connected to a voice channel.")
@staticmethod
async def cannot_connect_to_voice_channel(interaction: discord.Interaction) -> None:
''' Sends an error message indicating bot is unable to connect to a voice channel '''
await __class__.msg(interaction, "Cannot connect to voice channel.")
@staticmethod
async def queue_is_empty(interaction: discord.Interaction) -> None:
''' Sends an error message indicating the queue is empty '''
await __class__.msg(interaction, "Queue is empty.")
@staticmethod
async def already_playing(interaction: discord.Interaction) -> None:
''' Sends an error message indicating that music is already playing '''
await __class__.msg(interaction, "Already playing.")
@staticmethod
async def not_playing(interaction: discord.Interaction) -> None:
''' Sends an error message indicating nothing is playing '''
await __class__.msg(interaction, "No track is playing.")
# Methods for parsing data to Discord structures
def parse_search_as_track_selection_embed(results: list[Song], query: str, page_num: int) -> discord.Embed:
''' Takes search results obtained from the Subsonic API and parses them into a Discord embed suitable for track selection '''
options_str = ""
# Loop over the provided search results
for song in results:
# Trim displayed tags to fit neatly within the embed
tr_title = song.title
tr_artist = song.artist
tr_album = (song.album[:68] + "...") if len(song.album) > 68 else song.album
# Only trim the longest tag on the first line
top_str_length = len(song.title + " - " + song.artist)
if top_str_length > 71:
if tr_title > tr_artist:
tr_title = song.title[:(68 - top_str_length)] + '...'
else:
tr_artist = song.artist[:(68 - top_str_length)] + '...'
# Add each of the results to our output string
options_str += f"**{tr_title}** - *{tr_artist}* \n*{tr_album}* ({song.duration_printable})\n\n"
# Add the current page number to our results
options_str += f"Current page: {page_num}"
# Return an embed that displays our output string
return discord.Embed(color=discord.Color.orange(), title=f"Results for: {query}", description=options_str)
def parse_search_as_track_selection_options(results: list[Song]) -> list[discord.SelectOption]:
''' Takes search results obtained from the Subsonic API and parses them into a Discord selection list for tracks '''
select_options = []
for i, song in enumerate(results):
select_option = discord.SelectOption(label=f"{song.title}", description=f"by {song.artist}", value=i)
select_options.append(select_option)
return select_options

16
util/env.py Normal file
View File

@@ -0,0 +1,16 @@
import os
from typing import Final
from dotenv import load_dotenv
load_dotenv(os.path.relpath("data.env"))
DISCORD_BOT_TOKEN: Final[str] = os.getenv("DISCORD_BOT_TOKEN")
DISCORD_TEST_GUILD: Final[str] = os.getenv("DISCORD_TEST_GUILD")
DISCORD_OWNER_ID: Final[int] = int(os.getenv("DISCORD_OWNER_ID"))
SUBSONIC_SERVER: Final[str] = os.getenv("SUBSONIC_SERVER")
SUBSONIC_USER: Final[str] = os.getenv("SUBSONIC_USER")
SUBSONIC_PASSWORD: Final[str] = os.getenv("SUBSONIC_PASSWORD")
BOT_STATUS: Final[str] = os.getenv("BOT_STATUS")

89
util/logs.py Normal file
View File

@@ -0,0 +1,89 @@
'''Collection of utility functions related to logging.'''
import logging
import logging.handlers
import os
import sys
from typing import TextIO
def is_docker() -> bool:
'''Checks if the application is being run within a Docker container.'''
path = '/proc/self/cgroup'
return os.path.exists('/.dockerenv') or (os.path.isfile(path) and any('docker' in line for line in open(path, encoding='utf-8')))
def stream_supports_color(stream: TextIO) -> bool:
'''Checks if the provided `TextIO` stream supports color.'''
is_a_tty = hasattr(stream, 'isatty') and stream.isatty()
if 'PYCHARM_HOSTED' in os.environ or os.environ.get('TERM_PROGRAM') == 'vscode':
return is_a_tty
if sys.platform != 'win32':
return is_a_tty or is_docker()
return is_a_tty and ('ANSICON' in os.environ or 'WT_SESSION' in os.environ)
class ColorFormatter(logging.Formatter):
'''A logging formatter that applies colored formatting to logs.'''
LEVEL_COLORS = [
(logging.DEBUG, '\x1b[40;1m'),
(logging.INFO, '\x1b[34;1m'),
(logging.WARNING, '\x1b[33;1m'),
(logging.ERROR, '\x1b[31m'),
(logging.CRITICAL, '\x1b[41m'),
]
FORMATS = {
level: logging.Formatter(
f'\x1b[30;1m%(asctime)s\x1b[0m {color}%(levelname)-8s\x1b[0m \x1b[35m%(name)s\x1b[0m %(message)s',
'%Y-%m-%d %H:%M:%S',
)
for level, color in LEVEL_COLORS
}
def format(self, record: logging.LogRecord) -> str:
formatter = self.FORMATS.get(record.levelno)
if formatter is None:
formatter = self.FORMATS[logging.DEBUG]
if record.exc_info:
text = formatter.formatException(record.exc_info)
record.exc_text = f'\x1b[31m{text}\x1b[0m'
output = formatter.format(record)
record.exc_text = None
return output
def setup_logging(main_log_level: int=logging.INFO, file_log_level: int=logging.INFO, stream_log_level: int=logging.INFO) -> None:
'''Sets up logging handlers for both console and file logging.'''
logger = logging.getLogger()
logger.setLevel(main_log_level)
dt_fmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
file_max_size = 10 * 1024 * 1024 # 10mb
file_handler = logging.handlers.RotatingFileHandler(filename='bot.log', encoding='utf-8', maxBytes=file_max_size, backupCount=1)
file_handler.setLevel(file_log_level)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setLevel(stream_log_level)
if stream_supports_color(stream_handler.stream):
formatter = ColorFormatter()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.addHandler(file_handler)