├── .README └── preview-server.png ├── .deepsource.toml ├── .devcontainer ├── Dockerfile ├── devcontainer.json └── post.sh ├── .github └── workflows │ ├── docker-build-and-push.yml │ ├── docker-build.yml │ ├── pylint.yml │ └── spellcheck.yml ├── .gitignore ├── .pyspelling.yml ├── .vscode └── extensions.json ├── LICENSE.txt ├── Makefile ├── README.md ├── pyproject.toml ├── spellcheck_wordlist.txt └── src ├── Dockerfile ├── Dockerfile.nvidia ├── compile.py ├── docker-compose.nvidia.yml ├── docker-compose.yml ├── requirements.txt └── youcube ├── __main__.py ├── yc_colours.py ├── yc_download.py ├── yc_logging.py ├── yc_magic.py ├── yc_spotify.py ├── yc_utils.py └── youcube.py /.README/preview-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CC-YouCube/server/0bfbd3f4dc5398b39b306711f9c40692ede227f5/.README/preview-server.png -------------------------------------------------------------------------------- /.deepsource.toml: -------------------------------------------------------------------------------- 1 | version = 1 2 | 3 | [[analyzers]] 4 | name = "python" 5 | enabled = true 6 | 7 | [analyzers.meta] 8 | runtime_version = "3.x.x" 9 | 10 | [[analyzers]] 11 | name = "docker" 12 | enabled = true 13 | 14 | [analyzers.meta] 15 | dockerfile_paths = ["src/Dockerfile"] -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ghcr.io/commandcracker/ffmpeg:latest AS ffmpeg 2 | 3 | FROM ffmpeg as sanjuuni 4 | 5 | ENV SANJUUNI_VERSION=0.4 6 | 7 | ARG SANJUUNI_SHA512SUM="952a6c608d167f37faad53ee7f2e0de8090a02bf73b6455fae7c6b6f648dd6a188e7749fe26caeee85126b2a38d7391389c19afb0100e9962dc551188b9de6ae *sanjuuni.tar.gz" 8 | 9 | RUN set -eux; \ 10 | apk add --no-cache --update opencl-dev g++ zlib-dev poco-dev make; \ 11 | wget --output-document=sanjuuni.tar.gz https://github.com/MCJack123/sanjuuni/archive/${SANJUUNI_VERSION}.tar.gz; \ 12 | echo "${SANJUUNI_SHA512SUM}" | sha512sum -c -; \ 13 | mkdir --parents sanjuuni; \ 14 | tar --extract --directory sanjuuni --strip-components=1 --file=sanjuuni.tar.gz; \ 15 | rm sanjuuni.tar.gz; 16 | 17 | WORKDIR /sanjuuni 18 | 19 | RUN set -eux; \ 20 | ./configure; \ 21 | make 22 | 23 | FROM mcr.microsoft.com/vscode/devcontainers/base:alpine-3.17 24 | 25 | RUN set -eux; \ 26 | apk add --no-cache --update \ 27 | # python 28 | python3 py3-pip gcc libc-dev \ 29 | # ffmpeg requirements 30 | libgcc libstdc++ ca-certificates libcrypto1.1 libssl1.1 libgomp expat \ 31 | # sanjuuni requirements 32 | poco opencl \ 33 | # utils 34 | make; \ 35 | pip install --no-cache-dir --upgrade pip; \ 36 | # python-is-python3 37 | ln -sf python3 /usr/bin/python 38 | 39 | # add ffmpeg 40 | COPY --from=ffmpeg /usr/local /usr/local 41 | 42 | # add sanjuuni 43 | COPY --from=sanjuuni /sanjuuni/sanjuuni /usr/local/bin 44 | 45 | # Use ffmpeg libs 46 | ENV LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64 47 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "dockerFile": "Dockerfile", 3 | "customizations": { 4 | "vscode": { 5 | "extensions": [ 6 | "donjayamanne.python-extension-pack", 7 | "ms-azuretools.vscode-docker", 8 | "carlos-algms.make-task-provider", 9 | "ms-vscode.makefile-tools", 10 | "charliermarsh.ruff" 11 | ] 12 | } 13 | }, 14 | "postCreateCommand": "ash .devcontainer/post.sh" 15 | } -------------------------------------------------------------------------------- /.devcontainer/post.sh: -------------------------------------------------------------------------------- 1 | #!/bin/ash 2 | pip install --no-cache-dir --use-pep517 -r src/requirements.txt; 3 | pip install -U autopep8; 4 | sudo make install-pylint; 5 | sudo make install-pyspelling; 6 | -------------------------------------------------------------------------------- /.github/workflows/docker-build-and-push.yml: -------------------------------------------------------------------------------- 1 | name: Build and publish Docker image 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [main] 7 | paths: 8 | - "src/**" 9 | 10 | env: 11 | REGISTRY: ghcr.io 12 | IMAGE_NAME: ${{ github.repository }} 13 | 14 | jobs: 15 | build-and-publish-alpine: 16 | runs-on: ubuntu-latest 17 | permissions: 18 | contents: read 19 | packages: write 20 | 21 | steps: 22 | - name: Checkout 🛎️ 23 | uses: actions/checkout@v3 24 | 25 | - name: Login to container registry 🔐 26 | uses: docker/login-action@v2 27 | with: 28 | registry: ${{ env.REGISTRY }} 29 | username: ${{ github.actor }} 30 | password: ${{ secrets.GITHUB_TOKEN }} 31 | 32 | - name: Extract metadata 🏷️ 33 | id: meta 34 | uses: docker/metadata-action@v4 35 | with: 36 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 37 | 38 | - name: 🔨 Build and Publish alpine 🚀 39 | uses: docker/build-push-action@v3 40 | with: 41 | context: src 42 | push: true 43 | tags: ${{ env.REGISTRY }}/cc-youcube/youcube:latest,${{ env.REGISTRY }}/cc-youcube/youcube:alpine 44 | labels: ${{ steps.meta.outputs.labels }} 45 | 46 | build-and-publish-nvidia: 47 | runs-on: ubuntu-latest 48 | permissions: 49 | contents: read 50 | packages: write 51 | 52 | steps: 53 | - name: Checkout 🛎️ 54 | uses: actions/checkout@v3 55 | 56 | - name: Login to container registry 🔐 57 | uses: docker/login-action@v2 58 | with: 59 | registry: ${{ env.REGISTRY }} 60 | username: ${{ github.actor }} 61 | password: ${{ secrets.GITHUB_TOKEN }} 62 | 63 | - name: Extract metadata 🏷️ 64 | id: meta 65 | uses: docker/metadata-action@v4 66 | with: 67 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 68 | 69 | - name: 🔨 Build and Publish nvidia 🚀 70 | uses: docker/build-push-action@v3 71 | with: 72 | file: src/Dockerfile.nvidia 73 | context: src 74 | push: true 75 | tags: ${{ env.REGISTRY }}/cc-youcube/youcube:ubuntu-nvidia 76 | labels: ${{ steps.meta.outputs.labels }} 77 | -------------------------------------------------------------------------------- /.github/workflows/docker-build.yml: -------------------------------------------------------------------------------- 1 | name: Build Docker image 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches-ignore: [main] 7 | paths: 8 | - "src/**" 9 | pull_request: 10 | paths: 11 | - "src/**" 12 | 13 | jobs: 14 | build-alpine-image: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout 🛎️ 19 | uses: actions/checkout@v3 20 | 21 | - name: Build alpine image 🔨 22 | uses: docker/build-push-action@v4 23 | with: 24 | context: src 25 | 26 | build-nvidia-image: 27 | runs-on: ubuntu-latest 28 | 29 | steps: 30 | - name: Checkout 🛎️ 31 | uses: actions/checkout@v3 32 | 33 | - name: Build nvidia image 🔨 34 | uses: docker/build-push-action@v4 35 | with: 36 | file: src/Dockerfile.nvidia 37 | context: src 38 | -------------------------------------------------------------------------------- /.github/workflows/pylint.yml: -------------------------------------------------------------------------------- 1 | name: Pylint 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | paths: 7 | - "src/**.py" 8 | pull_request: 9 | paths: 10 | - "src/**.py" 11 | 12 | jobs: 13 | pylint: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Checkout 🛎️ 18 | uses: actions/checkout@v3 19 | 20 | - name: Set up Python 🧰 21 | uses: actions/setup-python@v4 22 | with: 23 | python-version: "3" 24 | 25 | - name: Install dependencies 🧰 26 | run: | 27 | python -m pip install --upgrade pip 28 | pip install -r src/requirements.txt 29 | pip install pylint 30 | 31 | - name: Pylint ✅ 32 | run: pylint $(git ls-files '*.py') 33 | -------------------------------------------------------------------------------- /.github/workflows/spellcheck.yml: -------------------------------------------------------------------------------- 1 | name: Spellcheck 2 | # Currently, only python is spellchecked 3 | 4 | on: 5 | workflow_dispatch: 6 | push: 7 | paths: 8 | - "src/**.py" 9 | pull_request: 10 | paths: 11 | - "src/**.py" 12 | 13 | jobs: 14 | spellcheck: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout 🛎️ 19 | uses: actions/checkout@v3 20 | 21 | - name: Spellcheck ✅ 22 | uses: rojopolis/spellcheck-github-actions@0.30.0 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.dfpwm 3 | *.32vid 4 | dictionary.dic 5 | *.pyc 6 | *.env 7 | *.egg-info 8 | dist 9 | venv -------------------------------------------------------------------------------- /.pyspelling.yml: -------------------------------------------------------------------------------- 1 | spellchecker: aspell 2 | 3 | matrix: 4 | - name: python 5 | aspell: 6 | lang: en 7 | d: en_US 8 | sources: 9 | - "**/*.py" 10 | pipeline: 11 | - pyspelling.filters.python: 12 | strings: false 13 | comments: true 14 | dictionary: 15 | wordlists: 16 | - ./spellcheck_wordlist.txt 17 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "donjayamanne.python-extension-pack", 4 | "ms-azuretools.vscode-docker", 5 | "carlos-algms.make-task-provider", 6 | "ms-vscode.makefile-tools", 7 | "charliermarsh.ruff" 8 | ] 9 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #!make 2 | 3 | run: 4 | python src/youcube/youcube.py 5 | 6 | docker-build: 7 | docker build -t youcube:latest src/. 8 | 9 | docker-build-nvidia: 10 | docker build -t youcube:nvidia src/. --file src/Dockerfile.nvidia 11 | 12 | pylint: 13 | pylint src/youcube/*.py 14 | 15 | pyspelling: 16 | pyspelling 17 | 18 | cleanup: 19 | ifeq ($(OS), Windows_NT) 20 | del /s /q src\youcube\data src\data src\youcube\__pycache__ src\__pycache__ 21 | else 22 | rm src/youcube/data src/data src/youcube/__pycache__ src/__pycache__ -Rv || true 23 | endif 24 | 25 | install-pylint: 26 | pip install pylint 27 | 28 | install-pyspelling: 29 | pip install pyspelling 30 | 31 | install-requirements: 32 | ifeq ($(OS), Windows_NT) 33 | pip install -r src\requirements.txt 34 | else 35 | pip install -r src/requirements.txt 36 | endif 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YouCube Server 2 | 3 | [![Python Version: 3.7+]](https://www.python.org/downloads/) 4 | [![Python Lint Workflow Status]](https://github.com/CC-YouCube/server/actions/workflows/pylint.yml) 5 | 6 | ![preview] 7 | 8 | YouCube has a some public servers, which you can use if you don't want to host your own server. \ 9 | The client has the public servers set by default, so you can just run the client, and you're good to go. \ 10 | Moor Information about the servers can be seen on the [doc]. 11 | 12 | ## Requirements 13 | 14 | - [yt-dlp/FFmpeg] / [FFmpeg 5.1+] 15 | - [sanjuuni] 16 | - [Python 3.7+] 17 | - [sanic] 18 | - [yt-dlp] 19 | - [ujson] (Optional) 20 | - [spotipy] 21 | 22 | You can install the required packages with [pip] by running: 23 | 24 | ```shell 25 | pip install -r src/requirements.txt 26 | ``` 27 | 28 | ## Starting the Server 29 | 30 | ```bash 31 | python src/youcube.py 32 | ``` 33 | 34 | ## Environment variables 35 | 36 | Environment variables you can use to configure the server: 37 | 38 | | Variable | Default | Description | 39 | | ----------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------ | 40 | | `HOST` | `0.0.0.0` | The host where the web server runs on. | 41 | | `PORT` | `5000` | The port where the web server should run on | 42 | | `FFMPEG_PATH` | `ffmpeg` | Path to the FFmpeg executable | 43 | | `SANJUUNI_PATH` | `sanjuuni` | Path to the Sanjuuni executable | 44 | | `NO_COLOR` | `False` | Disable colored output | 45 | | `LOGLEVEL` | `DEBUG` | Python Log level of the main logger | 46 | | `DISABLE_OPENCL` | `False` | Disables sanjuuni GPU acceleration | 47 | | `NO_FAST` | `False` | Disable Sanic worker processes maximization | 48 | | `SPOTIPY_CLIENT_ID` | | The Client ID from your [spotify application] | 49 | | `SPOTIPY_CLIENT_SECRET` | | The Client Secret from your [spotify application] | 50 | | `DATA_CACHE_CLEANUP_INTERVAL` | `300` | Time interval (in seconds) for the data cache cleaner to wait before checking for outdated cache entries. | 51 | | `DATA_CACHE_CLEANUP_AFTER` | `3600` | Time threshold (in seconds) for considering a cache entry outdated. Cache entries older than this will be removed. | 52 | 53 | And [Sanic Builtin values]. 54 | 55 | ## Docker Compose 56 | 57 | ```yml 58 | --- 59 | services: 60 | youcube: 61 | image: ghcr.io/cc-youcube/youcube:latest 62 | restart: always 63 | hostname: youcube 64 | ports: 65 | - 5000:5000 66 | ... 67 | ``` 68 | 69 | [spotify application]: https://developer.spotify.com/dashboard/applications 70 | [pip]: https://pip.pypa.io/en/stable/installation 71 | [yt-dlp/FFmpeg]: https://github.com/yt-dlp/FFmpeg-Builds 72 | [FFmpeg 5.1+]: https://ffmpeg.org 73 | [sanjuuni]: https://github.com/MCJack123/sanjuuni 74 | [Python 3.7+]: https://www.python.org/downloads 75 | [sanic]: https://sanic.dev 76 | [yt-dlp]: https://pypi.org/project/yt-dlp 77 | [ujson]: https://pypi.org/project/ujson 78 | [spotipy]: https://pypi.org/project/spotipy 79 | [doc]: https://youcube.madefor.cc/api 80 | [preview]: .README/preview-server.png 81 | [Python Version: 3.7+]: https://img.shields.io/badge/Python-3.7+-green?style=for-the-badge&logo=Python&logoColor=white 82 | [Python Lint Workflow Status]: https://img.shields.io/github/actions/workflow/status/CC-YouCube/server/pylint.yml?branch=main&label=Python%20Lint&logo=github&style=for-the-badge 83 | [Sanic Builtin values]: https://sanic.dev/en/guide/running/configuration.md#builtin-values 84 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "setuptools-scm"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "youcube-server" 7 | version = "1.0.0" 8 | authors = [{ name = "Commandcracker" }] 9 | description = "A server which provides a WebSocket API for YouCube clients" 10 | readme = "README.md" 11 | requires-python = ">=3.7" 12 | keywords = ["youtube", "youcube", "computercraft", "minecraft"] 13 | license = { text = "GPL-3.0" } 14 | classifiers = [ 15 | "Programming Language :: Python :: 3", 16 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 17 | "Natural Language :: English", 18 | "Topic :: Multimedia :: Video", 19 | "Topic :: Multimedia :: Sound/Audio :: Players", 20 | ] 21 | # Required for pulling dependencies from requirements.txt 22 | dynamic = ["dependencies"] 23 | 24 | [project.urls] 25 | Homepage = "https://youcube.madefor.cc" 26 | Repository = "https://github.com/CC-YouCube/server" 27 | Documentation = "https://youcube.madefor.cc/guides/server/installation/" 28 | 29 | [tool.setuptools.dynamic] 30 | # Pull dependencies from requirements.txt 31 | dependencies = { file = ["src/requirements.txt"] } 32 | 33 | [tool.setuptools.packages.find] 34 | where = ["src"] # list of folders that contain the packages (["."] by default) 35 | include = [ 36 | "youcube*", 37 | ] # package names should match these glob patterns (["*"] by default) 38 | 39 | [tool.autopep8] 40 | ignore = "E701" 41 | -------------------------------------------------------------------------------- /spellcheck_wordlist.txt: -------------------------------------------------------------------------------- 1 | # Python Libraries/Frameworks 2 | uvloop 3 | pypy 4 | sanic 5 | asyncio 6 | ThreadSaveAsyncioEventWithReturnValue 7 | pylint 8 | Popen 9 | ffmpeg 10 | subprocess 11 | utils 12 | spotipy 13 | 14 | # Web Development 15 | websocket 16 | YouCube 17 | Spotify 18 | html 19 | dev 20 | 21 | # Programming Keywords 22 | str 23 | env 24 | untrusted 25 | usr 26 | utf 27 | Handels 28 | fulltitle 29 | FIXME 30 | api 31 | TODO 32 | async 33 | fixme 34 | bestaudio 35 | worstaudio 36 | worstvideo 37 | vid 38 | ws 39 | formatter 40 | msg 41 | init 42 | docstring 43 | chunkindex 44 | url 45 | linecache 46 | commandcracker 47 | io 48 | ansi 49 | Ansi 50 | subprocesses 51 | Whitespace 52 | pyc 53 | dfpwm 54 | SpellCheckingInspection 55 | noinspection 56 | getLogger 57 | localtrace 58 | isinstance 59 | responsing 60 | toplevel 61 | 62 | # URLs 63 | https 64 | wikipedia 65 | stackoverflow 66 | github 67 | dlp 68 | geeksforgeeks 69 | www 70 | metalink 71 | 72 | # Video Streaming 73 | yc 74 | yt 75 | dl 76 | youtube 77 | 78 | # Other 79 | f'Attachment 80 | WIP 81 | xml 82 | -------------------------------------------------------------------------------- /src/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ghcr.io/commandcracker/ffmpeg:latest AS ffmpeg 2 | 3 | FROM ffmpeg AS sanjuuni 4 | 5 | ENV SANJUUNI_VERSION=49cb275d4ef64d2bee3d5d2cbc5baf47787bedc2 6 | 7 | ARG SANJUUNI_SHA512SUM="22c85f9a5c16c0acb4dde971b64f53e765a8d607065e7a25115103925124e33a0680da3790e85c4343b7d320a0170b6ae096ec7f2b48b22582cf96681fd3a78c *sanjuuni.tar.gz" 8 | 9 | SHELL ["/bin/ash", "-eo", "pipefail", "-c"] 10 | 11 | RUN set -eux; \ 12 | apk add --no-cache --update \ 13 | g++ \ 14 | zlib-dev \ 15 | poco-dev \ 16 | make; \ 17 | wget -q --output-document=sanjuuni.tar.gz https://github.com/MCJack123/sanjuuni/archive/${SANJUUNI_VERSION}.tar.gz; \ 18 | echo "${SANJUUNI_SHA512SUM}" | sha512sum -c -; \ 19 | mkdir --parents sanjuuni; \ 20 | tar --extract --directory sanjuuni --strip-components=1 --file=sanjuuni.tar.gz; \ 21 | rm sanjuuni.tar.gz; 22 | 23 | WORKDIR /sanjuuni 24 | 25 | RUN set -eux; \ 26 | ./configure; \ 27 | make 28 | 29 | FROM ghcr.io/commandcracker/alpine-pypy3.10-pip:3.20.1-pypy-7.3.14-pip-24.1.1 AS builder 30 | 31 | WORKDIR / 32 | 33 | COPY requirements.txt . 34 | COPY youcube ./youcube 35 | COPY compile.py . 36 | 37 | RUN set -eux; \ 38 | apk add --no-cache --update build-base; \ 39 | pip install --no-cache-dir -U setuptools -r requirements.txt; \ 40 | python3 compile.py; \ 41 | pip uninstall pip -y 42 | 43 | FROM alpine:3.20.1 44 | 45 | WORKDIR /opt/server 46 | 47 | RUN set -eux; \ 48 | apk add --no-cache --update \ 49 | # CVE-2024-5535 TODO: remove when base image is updated 50 | openssl \ 51 | # pypy requirements 52 | libffi libbz2 \ 53 | # sanjuuni requirements 54 | poco \ 55 | # ffmpeg requirements 56 | libgcc \ 57 | libstdc++ \ 58 | ca-certificates \ 59 | libgomp \ 60 | expat; \ 61 | apk add --no-cache --repository=http://dl-cdn.alpinelinux.org/alpine/v3.18/community libssl1.1=1.1.1u-r1 libcrypto1.1=1.1.1u-r1; \ 62 | chown 1000:1000 /opt/server/ 63 | 64 | COPY --from=builder /opt/pypy /opt/pypy 65 | # add ffmpeg 66 | COPY --from=ffmpeg /usr/local /usr/local 67 | # add sanjuuni 68 | COPY --from=sanjuuni /sanjuuni/sanjuuni /usr/local/bin 69 | 70 | ENV \ 71 | # Make sure, that the container is accessible from outside 72 | HOST=0.0.0.0 \ 73 | # Make sure we use the virtualenv: 74 | PATH="/opt/pypy/bin:$PATH" \ 75 | # Use ffmpeg libs 76 | LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64 \ 77 | # yt-dlp cache dir 78 | XDG_CACHE_HOME="/opt/server/.yt-dlp-cache" \ 79 | # FIXME: Add UVLOOP support for alpine pypy 80 | SANIC_NO_UVLOOP=true 81 | 82 | USER 1000:1000 83 | 84 | COPY --from=builder /youcube/__pycache__ /opt/server 85 | 86 | ENTRYPOINT ["python3", "youcube.pyc"] 87 | -------------------------------------------------------------------------------- /src/Dockerfile.nvidia: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env dockerfile-shebang 2 | 3 | FROM ghcr.io/commandcracker/ubuntu-ffmpeg:latest AS ffmpeg 4 | 5 | FROM ffmpeg AS sanjuuni 6 | 7 | ENV SANJUUNI_VERSION=49cb275d4ef64d2bee3d5d2cbc5baf47787bedc2 8 | 9 | ARG SANJUUNI_SHA512SUM="22c85f9a5c16c0acb4dde971b64f53e765a8d607065e7a25115103925124e33a0680da3790e85c4343b7d320a0170b6ae096ec7f2b48b22582cf96681fd3a78c *sanjuuni.tar.gz" 10 | 11 | SHELL ["/bin/bash", "-o", "pipefail", "-c"] 12 | 13 | RUN set -eux; \ 14 | apt-get update; \ 15 | apt-get install -y --no-install-recommends \ 16 | ocl-icd-opencl-dev \ 17 | wget \ 18 | clang \ 19 | make \ 20 | libpoco-dev; \ 21 | wget --progress=dot:giga --output-document=sanjuuni.tar.gz https://github.com/MCJack123/sanjuuni/archive/${SANJUUNI_VERSION}.tar.gz; \ 22 | echo "${SANJUUNI_SHA512SUM}" | sha512sum -c -; \ 23 | mkdir --parents sanjuuni; \ 24 | tar --extract --directory sanjuuni --strip-components=1 --file=sanjuuni.tar.gz 25 | 26 | WORKDIR /sanjuuni 27 | 28 | RUN set -eux; \ 29 | ./configure; \ 30 | make 31 | 32 | FROM ffmpeg 33 | 34 | WORKDIR /youcube 35 | 36 | COPY --from=sanjuuni /sanjuuni/sanjuuni /usr/local/bin 37 | 38 | COPY requirements.txt . 39 | COPY --chown=1000:1000 youcube/*.py /youcube 40 | 41 | SHELL ["/bin/bash", "-o", "pipefail", "-c"] 42 | 43 | # hadolint ignore=SC1091 44 | RUN set -eux; \ 45 | apt-get update; \ 46 | apt-get install -y --no-install-recommends \ 47 | libpoco-dev \ 48 | python3-pip \ 49 | ocl-icd-libopencl1; \ 50 | pip install --break-system-packages --no-cache-dir -r requirements.txt; \ 51 | rm requirements.txt __main__.py; \ 52 | chown 1000:1000 /youcube/; \ 53 | mkdir -p /etc/OpenCL/vendors; \ 54 | echo "libnvidia-opencl.so.1" > /etc/OpenCL/vendors/nvidia.icd 55 | 56 | ENV \ 57 | NVIDIA_VISIBLE_DEVICES=all \ 58 | NVIDIA_DRIVER_CAPABILITIES=compute,utility \ 59 | # Make sure, that the container is accessible from outside 60 | HOST=0.0.0.0 \ 61 | # yt-dlp cache dir 62 | XDG_CACHE_HOME="/youcube/.yt-dlp-cache" 63 | 64 | USER 1000:1000 65 | 66 | ENTRYPOINT ["python3", "youcube.py"] 67 | -------------------------------------------------------------------------------- /src/compile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Compiles YC to pyc files 6 | """ 7 | 8 | from os import rename 9 | from os.path import isdir, join 10 | from pathlib import Path 11 | from py_compile import compile as py_compile 12 | 13 | 14 | def main() -> None: 15 | """Starts the compilation""" 16 | blacklist = ["__main__.py"] 17 | 18 | for path in Path("youcube").rglob("*.py"): 19 | if not isdir(path) and path.name not in blacklist: 20 | compile_path = py_compile(path, optimize=2) 21 | new_name = Path( 22 | join(Path(compile_path).parent, path.name.replace(".py", ".pyc")) 23 | ) 24 | rename(compile_path, new_name) 25 | print(path, "->", new_name) 26 | 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /src/docker-compose.nvidia.yml: -------------------------------------------------------------------------------- 1 | --- 2 | services: 3 | youcube: 4 | build: 5 | context: . 6 | dockerfile: Dockerfile.nvidia 7 | image: youcube:nvidia 8 | restart: always 9 | hostname: youcube 10 | ports: 11 | - 5000:5000 12 | #env_file: .env 13 | runtime: nvidia 14 | ... 15 | -------------------------------------------------------------------------------- /src/docker-compose.yml: -------------------------------------------------------------------------------- 1 | --- 2 | services: 3 | youcube: 4 | build: . 5 | image: youcube 6 | restart: always 7 | hostname: youcube 8 | ports: 9 | - 5000:5000 10 | #env_file: .env 11 | ... 12 | -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | sanic~=25.3.0 2 | #uvloop~=0.21.0; platform_system != "Windows" 3 | yt-dlp~=2025.4.30 4 | #orjson~=3.10.18 5 | spotipy~=2.25.1 6 | -------------------------------------------------------------------------------- /src/youcube/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Runs the main function 6 | """ 7 | 8 | # Built-in modules 9 | from youcube import main 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /src/youcube/yc_colours.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Colors using ANSI escape codes 6 | https://en.wikipedia.org/wiki/ANSI_escape_code 7 | """ 8 | 9 | # pylint: disable=too-few-public-methods 10 | 11 | 12 | class Foreground: 13 | """ 14 | [3-bit and 4-bit](https://en.wikipedia.org/wiki/ANSI_escape_code#3-bit_and_4-bit) 15 | """ 16 | 17 | BLACK = "\033[30m" 18 | RED = "\033[31m" 19 | GREEN = "\033[32m" 20 | YELLOW = "\033[33m" 21 | BLUE = "\033[34m" 22 | MAGENTA = "\033[35m" 23 | CYAN = "\033[36m" 24 | WHITE = "\033[37m" 25 | 26 | BRIGHT_BLACK = "\033[90m" 27 | BRIGHT_RED = "\033[91m" 28 | BRIGHT_GREEN = "\033[92m" 29 | BRIGHT_YELLOW = "\033[93m" 30 | BRIGHT_BLUE = "\033[94m" 31 | BRIGHT_MAGENTA = "\033[95m" 32 | BRIGHT_CYAN = "\033[96m" 33 | BRIGHT_WHITE = "\033[97m" 34 | 35 | DEFAULT = "\033[39m" 36 | 37 | 38 | RESET = "\033[m" 39 | -------------------------------------------------------------------------------- /src/youcube/yc_download.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Download Functionality of YC 6 | """ 7 | 8 | # Built-in modules 9 | from asyncio import run_coroutine_threadsafe 10 | from os import getenv, listdir 11 | from os.path import abspath, dirname, join 12 | from tempfile import TemporaryDirectory 13 | 14 | # Local modules 15 | from yc_colours import RESET, Foreground 16 | from yc_logging import NO_COLOR, YTDLPLogger, logger 17 | from yc_magic import run_with_live_output 18 | from yc_spotify import SpotifyURLProcessor 19 | from yc_utils import ( 20 | cap_width_and_height, 21 | create_data_folder_if_not_present, 22 | get_audio_name, 23 | get_video_name, 24 | is_audio_already_downloaded, 25 | is_video_already_downloaded, 26 | remove_ansi_escape_codes, 27 | remove_whitespace, 28 | ) 29 | 30 | # optional pip modules 31 | try: 32 | from orjson import dumps 33 | except ModuleNotFoundError: 34 | from json import dumps 35 | 36 | # pip modules 37 | from sanic import Websocket 38 | from yt_dlp import YoutubeDL 39 | 40 | # pylint settings 41 | # pylint: disable=pointless-string-statement 42 | # pylint: disable=fixme 43 | # pylint: disable=too-many-locals 44 | # pylint: disable=too-many-arguments 45 | # pylint: disable=too-many-branches 46 | 47 | DATA_FOLDER = join(dirname(abspath(__file__)), "data") 48 | FFMPEG_PATH = getenv("FFMPEG_PATH", "ffmpeg") 49 | SANJUUNI_PATH = getenv("SANJUUNI_PATH", "sanjuuni") 50 | DISABLE_OPENCL = bool(getenv("DISABLE_OPENCL")) 51 | 52 | 53 | def download_video( 54 | temp_dir: str, media_id: str, resp: Websocket, loop, width: int, height: int 55 | ): 56 | """ 57 | Converts the downloaded video to 32vid 58 | """ 59 | run_coroutine_threadsafe( 60 | resp.send( 61 | dumps({"action": "status", "message": "Converting video to 32vid ..."}) 62 | ), 63 | loop, 64 | ) 65 | 66 | if NO_COLOR: 67 | prefix = "[Sanjuuni]" 68 | else: 69 | prefix = f"{Foreground.BRIGHT_YELLOW}[Sanjuuni]{RESET} " 70 | 71 | def handler(line): 72 | logger.debug("%s%s", prefix, line) 73 | run_coroutine_threadsafe( 74 | resp.send(dumps({"action": "status", "message": line})), loop 75 | ) 76 | 77 | returncode = run_with_live_output( 78 | [ 79 | SANJUUNI_PATH, 80 | "--width=" + str(width), 81 | "--height=" + str(height), 82 | "-i", 83 | join(temp_dir, listdir(temp_dir)[0]), 84 | "--raw", 85 | "-o", 86 | join(DATA_FOLDER, get_video_name(media_id, width, height)), 87 | "--disable-opencl" if DISABLE_OPENCL else "", 88 | ], 89 | handler, 90 | ) 91 | 92 | if returncode != 0: 93 | logger.warning("Sanjuuni exited with %s", returncode) 94 | run_coroutine_threadsafe( 95 | resp.send(dumps({"action": "error", "message": "Faild to convert video!"})), 96 | loop, 97 | ) 98 | 99 | 100 | def download_audio(temp_dir: str, media_id: str, resp: Websocket, loop): 101 | """ 102 | Converts the downloaded audio to dfpwm 103 | """ 104 | run_coroutine_threadsafe( 105 | resp.send( 106 | dumps({"action": "status", "message": "Converting audio to dfpwm ..."}) 107 | ), 108 | loop, 109 | ) 110 | 111 | if NO_COLOR: 112 | prefix = "[FFmpeg]" 113 | else: 114 | prefix = f"{Foreground.BRIGHT_GREEN}[FFmpeg]{RESET} " 115 | 116 | def handler(line): 117 | logger.debug("%s%s", prefix, line) 118 | # TODO: send message to resp 119 | 120 | returncode = run_with_live_output( 121 | [ 122 | FFMPEG_PATH, 123 | "-i", 124 | join(temp_dir, listdir(temp_dir)[0]), 125 | "-f", 126 | "dfpwm", 127 | "-ar", 128 | "48000", 129 | "-ac", 130 | "1", 131 | join(DATA_FOLDER, get_audio_name(media_id)), 132 | ], 133 | handler, 134 | ) 135 | 136 | if returncode != 0: 137 | logger.warning("FFmpeg exited with %s", returncode) 138 | run_coroutine_threadsafe( 139 | resp.send(dumps({"action": "error", "message": "Faild to convert audio!"})), 140 | loop, 141 | ) 142 | 143 | 144 | def download( 145 | url: str, 146 | resp: Websocket, 147 | loop, 148 | width: int, 149 | height: int, 150 | spotify_url_processor: SpotifyURLProcessor, 151 | ) -> (dict[str, any], list): 152 | """ 153 | Downloads and converts the media from the give URL 154 | """ 155 | 156 | is_video = width is not None and height is not None 157 | 158 | # cap height and width 159 | if width and height: 160 | width, height = cap_width_and_height(width, height) 161 | 162 | def my_hook(info): 163 | """https://github.com/yt-dlp/yt-dlp#adding-logger-and-progress-hook""" 164 | if info.get("status") == "downloading": 165 | run_coroutine_threadsafe( 166 | resp.send( 167 | dumps( 168 | { 169 | "action": "status", 170 | "message": remove_ansi_escape_codes( 171 | f"download {remove_whitespace(info.get('_percent_str'))} " 172 | f"ETA {info.get('_eta_str')}" 173 | ), 174 | } 175 | ) 176 | ), 177 | loop, 178 | ) 179 | 180 | # FIXME: Cleanup on Exception 181 | with TemporaryDirectory(prefix="youcube-") as temp_dir: 182 | yt_dl_options = { 183 | "format": "worst[ext=mp4]/worst" if is_video else "worstaudio/worst", 184 | "outtmpl": join(temp_dir, "%(id)s.%(ext)s"), 185 | "default_search": "auto", 186 | "restrictfilenames": True, 187 | "extract_flat": "in_playlist", 188 | "progress_hooks": [my_hook], 189 | "logger": YTDLPLogger(), 190 | } 191 | 192 | yt_dl = YoutubeDL(yt_dl_options) 193 | 194 | run_coroutine_threadsafe( 195 | resp.send( 196 | dumps( 197 | {"action": "status", "message": "Getting resource information ..."} 198 | ) 199 | ), 200 | loop, 201 | ) 202 | 203 | playlist_videos = [] 204 | 205 | if spotify_url_processor: 206 | # Spotify FIXME: The first media key is sometimes duplicated 207 | processed_url = spotify_url_processor.auto(url) 208 | if processed_url: 209 | if isinstance(processed_url, list): 210 | url = spotify_url_processor.auto(processed_url[0]) 211 | processed_url.pop(0) 212 | playlist_videos = processed_url 213 | else: 214 | url = processed_url 215 | 216 | data = yt_dl.extract_info(url, download=False) 217 | 218 | if data.get("extractor") == "generic": 219 | data["id"] = "g" + data.get("webpage_url_domain") + data.get("id") 220 | 221 | """ 222 | If the data is a playlist, we need to get the first video and return it, 223 | also, we need to grep all video in the playlist to provide support. 224 | """ 225 | if data.get("_type") == "playlist": 226 | for video in data.get("entries"): 227 | playlist_videos.append(video.get("id")) 228 | 229 | playlist_videos.pop(0) 230 | 231 | data = data["entries"][0] 232 | 233 | """ 234 | If the video is extract from a playlist, 235 | the video is extracted flat, 236 | so we need to get missing information by running the extractor again. 237 | """ 238 | if data.get("extractor") == "youtube" and ( 239 | data.get("view_count") is None or data.get("like_count") is None 240 | ): 241 | data = yt_dl.extract_info(data.get("id"), download=False) 242 | 243 | media_id = data.get("id") 244 | 245 | if data.get("is_live"): 246 | return {"action": "error", "message": "Livestreams are not supported"} 247 | 248 | create_data_folder_if_not_present() 249 | 250 | audio_downloaded = is_audio_already_downloaded(media_id) 251 | video_downloaded = is_video_already_downloaded(media_id, width, height) 252 | 253 | if not audio_downloaded or (not video_downloaded and is_video): 254 | run_coroutine_threadsafe( 255 | resp.send( 256 | dumps({"action": "status", "message": "Downloading resource ..."}) 257 | ), 258 | loop, 259 | ) 260 | 261 | yt_dl.process_ie_result(data, download=True) 262 | 263 | # TODO: Thread audio & video download 264 | 265 | if not audio_downloaded: 266 | download_audio(temp_dir, media_id, resp, loop) 267 | 268 | if not video_downloaded and is_video: 269 | download_video(temp_dir, media_id, resp, loop, width, height) 270 | 271 | out = { 272 | "action": "media", 273 | "id": media_id, 274 | # "fulltitle": data.get("fulltitle"), 275 | "title": data.get("title"), 276 | "like_count": data.get("like_count"), 277 | "view_count": data.get("view_count"), 278 | # "upload_date": data.get("upload_date"), 279 | # "tags": data.get("tags"), 280 | # "description": data.get("description"), 281 | # "categories": data.get("categories"), 282 | # "channel_name": data.get("channel"), 283 | # "channel_id": data.get("channel_id") 284 | } 285 | 286 | # Only return playlist_videos if there are videos in playlist_videos 287 | if len(playlist_videos) > 0: 288 | out["playlist_videos"] = playlist_videos 289 | 290 | files = [] 291 | files.append(get_audio_name(media_id)) 292 | if is_video: 293 | files.append(get_video_name(media_id, width, height)) 294 | 295 | return out, files 296 | -------------------------------------------------------------------------------- /src/youcube/yc_logging.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Everything logging related 6 | """ 7 | 8 | # Built-in modules 9 | from logging import ( 10 | CRITICAL, 11 | DEBUG, 12 | ERROR, 13 | INFO, 14 | WARNING, 15 | Formatter, 16 | Logger, 17 | LogRecord, 18 | StreamHandler, 19 | getLogger, 20 | ) 21 | from os import getenv 22 | 23 | # local modules 24 | from yc_colours import RESET, Foreground 25 | 26 | LOGLEVEL = getenv("LOGLEVEL") or DEBUG 27 | NO_COLOR = getenv("NO_COLOR") or False 28 | # Don't call "getLogger" every time we need the logger 29 | logger = getLogger("__main__") 30 | 31 | 32 | class ColordFormatter(Formatter): 33 | """Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629""" 34 | 35 | # noinspection SpellCheckingInspection 36 | def __init__(self, fmt=None, datefmt="%H:%M:%S") -> None: 37 | super().__init__() 38 | self.fmt = fmt 39 | self.datefmt = datefmt 40 | self.formats = { 41 | DEBUG: f"{Foreground.BRIGHT_BLACK}{self.fmt}{RESET}", 42 | INFO: f"{Foreground.BRIGHT_WHITE}{self.fmt}{RESET}", 43 | WARNING: f"{Foreground.BRIGHT_YELLOW}{self.fmt}{RESET}", 44 | ERROR: f"{Foreground.BRIGHT_RED}{self.fmt}{RESET}", 45 | CRITICAL: f"{Foreground.RED}{self.fmt}{RESET}", 46 | } 47 | 48 | def format(self, record: LogRecord) -> str: 49 | log_fmt = self.formats.get(record.levelno) 50 | formatter = Formatter(log_fmt, datefmt=self.datefmt) 51 | return formatter.format(record) 52 | 53 | 54 | class YTDLPLogger: 55 | """https://github.com/yt-dlp/yt-dlp#adding-logger-and-progress-hook""" 56 | 57 | def __init__(self) -> None: 58 | if NO_COLOR: 59 | self.prefix = "[yt-dlp] " 60 | else: 61 | self.prefix = f"{Foreground.BRIGHT_MAGENTA}[yt-dlp]{RESET} " 62 | 63 | def debug(self, msg: str) -> None: 64 | """Pass msg to the main logger""" 65 | 66 | # For compatibility with youtube-dl, both debug and info are passed into debug 67 | # You can distinguish them by the prefix '[debug] ' 68 | if msg.startswith("[debug] "): 69 | pass 70 | else: 71 | self.info(msg) 72 | 73 | def info(self, msg: str) -> None: 74 | """Pass msg to the main logger""" 75 | logger.debug("%s%s", self.prefix, msg) 76 | 77 | def warning(self, msg: str) -> None: 78 | """Pass msg to the main logger""" 79 | logger.warning("%s%s", self.prefix, msg) 80 | 81 | def error(self, msg: str) -> None: 82 | """Pass msg to the main logger""" 83 | logger.error("%s%s", self.prefix, msg) 84 | 85 | 86 | def setup_logging() -> Logger: 87 | """Sets the main logger up""" 88 | logger.setLevel(LOGLEVEL) 89 | 90 | # noinspection SpellCheckingInspection 91 | if NO_COLOR: 92 | formatter = Formatter(fmt="[%(asctime)s %(levelname)s] [YouCube] %(message)s") 93 | else: 94 | formatter = ColordFormatter( 95 | # pylint: disable-next=line-too-long 96 | fmt=f"[%(asctime)s %(levelname)s] {Foreground.BRIGHT_WHITE}[You{Foreground.RED}Cube]{RESET} %(message)s" 97 | ) 98 | 99 | logging_handler = StreamHandler() 100 | logging_handler.setFormatter(formatter) 101 | logger.addHandler(logging_handler) 102 | 103 | return logger 104 | -------------------------------------------------------------------------------- /src/youcube/yc_magic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Black Magic with threads, asyncio and subprocesses 6 | """ 7 | 8 | # Built-in modules 9 | from asyncio import Event 10 | from subprocess import PIPE, Popen 11 | from sys import settrace 12 | from threading import Thread 13 | from types import FrameType 14 | from typing import Any, Callable 15 | 16 | 17 | class ThreadSaveAsyncioEventWithReturnValue(Event): 18 | """ 19 | Thread-save version of asyncio.Event with result / Return value 20 | """ 21 | 22 | def __init__(self) -> None: 23 | super().__init__() 24 | self.result = None 25 | 26 | # pylint: disable-next=fixme 27 | # TODO: clear() method 28 | 29 | def set(self): 30 | # pylint: disable-next=fixme 31 | # FIXME: The _loop attribute is not documented as public api! 32 | self._loop.call_soon_threadsafe(super().set) 33 | 34 | 35 | def run_with_thread_save_asyncio_event_with_return_value( 36 | event: ThreadSaveAsyncioEventWithReturnValue, func: Callable[[], Any], *args 37 | ) -> None: 38 | """ 39 | Runs a function and calls a ThreadSaveAsyncioEventWithReturnValue 40 | This function is meant to run in a thread 41 | """ 42 | result = func(*args) 43 | event.result = result 44 | event.set() 45 | 46 | 47 | async def run_function_in_thread_from_async_function( 48 | func: Callable[[], Any], *args 49 | ) -> object: 50 | """ 51 | Runs a function in a thread from an async function 52 | """ 53 | event = ThreadSaveAsyncioEventWithReturnValue() 54 | Thread( 55 | target=run_with_thread_save_asyncio_event_with_return_value, 56 | args=(event, func, *args), 57 | ).start() 58 | await event.wait() 59 | return event.result 60 | 61 | 62 | class KillableThread(Thread): 63 | """ 64 | A Thread that can be canceled by running kill on it 65 | https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/ 66 | """ 67 | 68 | def __init__(self, *args, **keywords) -> None: 69 | Thread.__init__(self, *args, **keywords) 70 | self.killed = False 71 | 72 | def start(self) -> None: 73 | # pylint: disable-next=attribute-defined-outside-init 74 | self.__run_backup = self.run 75 | self.run = self.__run 76 | Thread.start(self) 77 | 78 | def __run(self) -> None: 79 | settrace(self.globaltrace) 80 | self.__run_backup() 81 | self.run = self.__run_backup 82 | 83 | # pylint: disable-next=unused-argument 84 | def globaltrace(self, frame: FrameType, event: str, arg: Any) -> None: 85 | """ 86 | Allows calling "localtrace" from global 87 | """ 88 | if event == "call": 89 | return self.localtrace 90 | return None 91 | 92 | # pylint: disable-next=unused-argument 93 | def localtrace(self, frame: FrameType, event: str, arg: Any) -> None: 94 | """ 95 | Uses trace to check if the Thread needs to be killed 96 | """ 97 | if self.killed and event == "line": 98 | raise SystemExit() 99 | return self.localtrace 100 | 101 | def kill(self) -> None: 102 | """Kills the Thread""" 103 | self.killed = True 104 | 105 | 106 | def run_with_live_output(cmd: list, handler: Callable[[str], None]) -> int: 107 | """ 108 | Runs a subprocess and allows handling output live 109 | """ 110 | with Popen(cmd, stdout=PIPE, stderr=PIPE) as process: 111 | 112 | def live_output(): 113 | line = [] 114 | while True: 115 | read = process.stderr.read(1) 116 | if read in (b"\r", b"\n"): # handle \n and \r as new line characters 117 | if len(line) != 0: # ignore empty line 118 | handler("".join(line)) 119 | line.clear() 120 | else: 121 | line.append(read.decode("utf-8")) 122 | 123 | thread = KillableThread(target=live_output) 124 | thread.start() 125 | 126 | process.wait() 127 | thread.kill() 128 | 129 | return process.returncode 130 | 131 | 132 | # pylint: disable=unused-argument 133 | -------------------------------------------------------------------------------- /src/youcube/yc_spotify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Spotify support module 6 | """ 7 | 8 | 9 | # Built-in modules 10 | from enum import Enum 11 | from logging import getLogger 12 | from os import getenv 13 | from re import match as re_match 14 | from typing import Union 15 | 16 | # pip modules 17 | from spotipy import MemoryCacheHandler, SpotifyClientCredentials 18 | from spotipy.client import Spotify 19 | 20 | 21 | # pylint: disable=missing-function-docstring 22 | # pylint: disable=missing-class-docstring 23 | 24 | 25 | class SpotifyTypes(Enum): 26 | TRACK = "track" 27 | ARTIST = "artist" 28 | ALBUM = "album" 29 | PLAYLIST = "playlist" 30 | SHOW = "show" 31 | EPISODE = "episode" 32 | USER = "user" 33 | 34 | 35 | class SpotifyURLProcessor: 36 | def __init__(self, spotify: Spotify = None, spotify_market: str = "US") -> None: 37 | self.spotify = spotify 38 | self.spotify_market = spotify_market 39 | 40 | def spotify_track(self, spotify_id: str) -> str: 41 | track: dict = self.spotify.track(spotify_id) 42 | 43 | artists = track["artists"][0]["name"] 44 | name = track["name"] 45 | 46 | return f"{artists} - {name}" 47 | 48 | def spotify_playlist(self, spotify_id: str) -> list: 49 | playlist_tracks = self.spotify.playlist_items(spotify_id) 50 | playlist = [] 51 | for item in playlist_tracks["items"]: 52 | track = item.get("track") 53 | if track: 54 | playlist.append(track.get("uri")) 55 | 56 | return playlist 57 | 58 | def spotify_album_tracks(self, spotify_id: str) -> list: 59 | album_tracks = self.spotify.album_tracks(spotify_id) 60 | playlist = [] 61 | 62 | for track in album_tracks["items"]: 63 | playlist.append(track.get("uri")) 64 | 65 | return playlist 66 | 67 | def spotify_artist(self, spotify_id: str) -> list: 68 | top_tracks = self.spotify.artist_top_tracks(spotify_id) 69 | playlist = [] 70 | 71 | for track in top_tracks["tracks"]: 72 | playlist.append(track.get("uri")) 73 | 74 | return playlist 75 | 76 | def spotify_show(self, spotify_id: str) -> list: 77 | episodes = self.spotify.show_episodes(spotify_id, market=self.spotify_market) 78 | playlist = [] 79 | 80 | for track in episodes["items"]: 81 | playlist.append(track.get("uri")) 82 | 83 | return playlist 84 | 85 | def spotify_episode(self, spotify_id: str) -> str: 86 | episode = self.spotify.episode(spotify_id, market=self.spotify_market) 87 | 88 | publisher = episode.get("show").get("publisher") 89 | name = episode.get("show").get("name") 90 | episode_name = episode.get("name") 91 | 92 | return f"{publisher} - {name} - {episode_name}" 93 | 94 | def spotify_user(self, spotify_id: str) -> list: 95 | """ 96 | Get first playlist of user and return all items 97 | """ 98 | playlists = self.spotify.user_playlists(spotify_id) 99 | return self.spotify_playlist(playlists.get("items")[0].get("id")) 100 | 101 | # pylint: disable-next=inconsistent-return-statements 102 | def auto(self, url: str) -> Union[str, list]: 103 | type_function_map = { 104 | SpotifyTypes.ALBUM: self.spotify_album_tracks, 105 | SpotifyTypes.TRACK: self.spotify_track, 106 | SpotifyTypes.PLAYLIST: self.spotify_playlist, 107 | SpotifyTypes.ARTIST: self.spotify_artist, 108 | SpotifyTypes.SHOW: self.spotify_show, 109 | SpotifyTypes.EPISODE: self.spotify_episode, 110 | SpotifyTypes.USER: self.spotify_user, 111 | } 112 | 113 | # pylint: disable=protected-access 114 | for match in [ 115 | re_match(Spotify._regex_spotify_uri, url), 116 | re_match(Spotify._regex_spotify_url, url), 117 | ]: 118 | # pylint: enable=protected-access 119 | if match: 120 | group = match.groupdict() 121 | 122 | match_type = group.get("type") 123 | match_id = group.get("id") 124 | 125 | for spotify_type, func in type_function_map.items(): 126 | if spotify_type.value == match_type: 127 | return func(match_id) 128 | 129 | 130 | def main() -> None: 131 | logger = getLogger(__name__) 132 | 133 | # Spotify 134 | spotify_client_id = getenv("SPOTIPY_CLIENT_ID") 135 | spotify_client_secret = getenv("SPOTIPY_CLIENT_SECRET") 136 | spotipy = None 137 | 138 | if spotify_client_id and spotify_client_secret: 139 | logger.info("Spotipy Enabled") 140 | spotipy = Spotify( 141 | auth_manager=SpotifyClientCredentials( 142 | client_id=spotify_client_id, 143 | client_secret=spotify_client_secret, 144 | cache_handler=MemoryCacheHandler(), 145 | ) 146 | ) 147 | else: 148 | logger.info("Spotipy Disabled") 149 | spotify_url_processor = SpotifyURLProcessor(spotipy) 150 | 151 | test_urls = [ 152 | "https://open.spotify.com/album/2Kh43m04B1UkVcpcRa1Zug", 153 | "https://42", 154 | "https://open.spotify.com/playlist/1Ze30K0U9OYtQZsQS1vIPj", 155 | "https://open.spotify.com/artist/64tJ2EAv1R6UaZqc4iOCyj", 156 | "https://open.spotify.com/episode/0UCTRy5frRHxD6SktX9dbV", 157 | "https://open.spotify.com/show/5fA3Ze7Ni75iXAEZaEkJIu", 158 | "https://open.spotify.com/user/besdkg6w64xf0rt713643tgvt", 159 | "https://open.spotify.com/playlist/5UrcnHexRYVEprv5DJBPER", 160 | ] 161 | 162 | # pylint: disable-next=import-outside-toplevel 163 | from yc_colours import Foreground 164 | 165 | for url in test_urls: 166 | print(Foreground.BLUE + url + Foreground.WHITE, spotify_url_processor.auto(url)) 167 | 168 | 169 | if __name__ == "__main__": 170 | main() 171 | -------------------------------------------------------------------------------- /src/youcube/yc_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Utils for string manipulation, data management etc. 6 | """ 7 | 8 | # Built-in modules 9 | from os import mkdir 10 | from os.path import abspath, dirname, exists, join 11 | from re import RegexFlag 12 | from re import compile as re_compile 13 | from typing import Tuple 14 | 15 | 16 | def remove_whitespace(string: str) -> str: 17 | """ 18 | Removes all Spaces / Whitespace from a string 19 | """ 20 | return string.replace(" ", "") 21 | 22 | 23 | # Only compile "ansi_escape_codes" once 24 | ansi_escape_codes = re_compile( 25 | r""" 26 | \x1B # ESC 27 | (?: # 7-bit C1 Fe (except CSI) 28 | [@-Z\\-_] 29 | | # or [ for CSI, followed by a control sequence 30 | \[ 31 | [0-?]* # Parameter bytes 32 | [ -/]* # Intermediate bytes 33 | [@-~] # Final byte 34 | ) 35 | """, 36 | RegexFlag.VERBOSE, 37 | ) 38 | 39 | 40 | def remove_ansi_escape_codes(text: str) -> str: 41 | """ 42 | Remove all Ansi Escape codes 43 | (7-bit C1 ANSI sequences) 44 | """ 45 | return ansi_escape_codes.sub("", text) 46 | 47 | 48 | def cap_width(width: int) -> int: 49 | """Caps the width""" 50 | return min(width, 328) 51 | 52 | 53 | def cap_height(height: int) -> int: 54 | """Caps the height""" 55 | return min(height, 243) 56 | 57 | 58 | def cap_width_and_height(width: int, height: int) -> Tuple[int, int]: 59 | """Caps the width and height""" 60 | return cap_width(width), cap_height(height) 61 | 62 | 63 | VIDEO_FORMAT = "32vid" 64 | AUDIO_FORMAT = "dfpwm" 65 | DATA_FOLDER = join(dirname(abspath(__file__)), "data") 66 | 67 | 68 | def get_video_name(media_id: str, width: int, height: int) -> str: 69 | """Returns the file name of the requested video""" 70 | return f"{media_id}({width}x{height}).{VIDEO_FORMAT}" 71 | 72 | 73 | def get_audio_name(media_id: str) -> str: 74 | """Returns the file name of the requested audio""" 75 | return f"{media_id}.{AUDIO_FORMAT}" 76 | 77 | 78 | def get_video_path(media_id: str, width: int, height: int) -> str: 79 | """Returns the relative path to the requested video""" 80 | return join(DATA_FOLDER, get_video_name(media_id, width, height)) 81 | 82 | 83 | def get_audio_path(media_id: str) -> str: 84 | """Returns the relative path to the requested audio""" 85 | return join(DATA_FOLDER, get_audio_name(media_id)) 86 | 87 | 88 | def create_data_folder_if_not_present(): 89 | """Creates the data folder if it does not exist""" 90 | if not exists(DATA_FOLDER): 91 | mkdir(DATA_FOLDER) 92 | 93 | 94 | def is_audio_already_downloaded(media_id: str) -> bool: 95 | """Returns True if the given audio is already downloaded""" 96 | return exists(get_audio_path(media_id)) 97 | 98 | 99 | def is_video_already_downloaded(media_id: str, width: int, height: int) -> bool: 100 | """Returns True if the given video is already downloaded""" 101 | return exists(get_video_path(media_id, width, height)) 102 | 103 | 104 | # Only compile "allowed_characters" once 105 | allowed_characters = re_compile("^[a-zA-Z0-9-._]*$") 106 | 107 | 108 | def is_save(string: str) -> bool: 109 | """Returns True if the given string does not contain special characters""" 110 | return bool(allowed_characters.match(string)) 111 | -------------------------------------------------------------------------------- /src/youcube/youcube.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | YouCube Server 6 | """ 7 | 8 | # built-in modules 9 | from asyncio import get_event_loop 10 | from base64 import b64encode 11 | from datetime import datetime 12 | from multiprocessing import Manager 13 | from os import getenv, remove 14 | from os.path import exists, join 15 | from shutil import which 16 | from time import sleep 17 | from typing import Any, List, Tuple, Type, Union 18 | 19 | # optional pip module 20 | try: 21 | from orjson import JSONDecodeError, dumps 22 | from orjson import loads as load_json 23 | except ModuleNotFoundError: 24 | from json import dumps 25 | from json import loads as load_json 26 | from json.decoder import JSONDecodeError 27 | 28 | try: 29 | from types import UnionType 30 | except ImportError: 31 | UnionType = Union[int, str] 32 | 33 | 34 | # pip modules 35 | from sanic import Request, Sanic, Websocket 36 | from sanic.compat import open_async 37 | from sanic.exceptions import SanicException 38 | from sanic.handlers import ErrorHandler 39 | from sanic.response import raw, text 40 | from spotipy import MemoryCacheHandler, SpotifyClientCredentials 41 | from spotipy.client import Spotify 42 | 43 | # local modules 44 | from yc_colours import RESET, Foreground 45 | from yc_download import DATA_FOLDER, FFMPEG_PATH, SANJUUNI_PATH, download 46 | from yc_logging import NO_COLOR, setup_logging 47 | from yc_magic import run_function_in_thread_from_async_function 48 | from yc_spotify import SpotifyURLProcessor 49 | from yc_utils import cap_width_and_height, get_audio_name, get_video_name, is_save 50 | 51 | VERSION = "0.0.0-poc.1.0.2" 52 | API_VERSION = "0.0.0-poc.1.0.0" # https://commandcracker.github.io/YouCube/ 53 | 54 | # one dfpwm chunk is 16 bits 55 | CHUNK_SIZE = 16 56 | 57 | """ 58 | CHUNKS_AT_ONCE should not be too big, [CHUNK_SIZE * 1024] 59 | because then the CC Computer cant decode the string fast enough! 60 | Also, it should not be too small because then the client 61 | would need to send thousands of WS messages 62 | and that would also slow everything down! [CHUNK_SIZE * 1] 63 | """ 64 | CHUNKS_AT_ONCE = CHUNK_SIZE * 256 65 | 66 | 67 | FRAMES_AT_ONCE = 10 68 | 69 | # pylint settings 70 | # pylint: disable=pointless-string-statement 71 | # pylint: disable=fixme 72 | # pylint: disable=multiple-statements 73 | 74 | """ 75 | Ubuntu nvida support fix and maby alpine support ? 76 | us async base64 ? 77 | use HTTP (and Streaming) 78 | Add uvloop support https://github.com/CC-YouCube/server/issues/6 79 | """ 80 | 81 | """ 82 | 1 dfpwm chunk = 16 83 | MAX_DOWNLOAD = 16 * 1024 * 1024 = 16777216 84 | WEBSOCKET_MESSAGE = 128 * 1024 = 131072 85 | (MAX_DOWNLOAD = 128 * WEBSOCKET_MESSAGE) 86 | 87 | the speaker can accept a maximum of 128 x 1024 samples 16KiB 88 | 89 | playAudio 90 | This accepts a list of audio samples as amplitudes between -128 and 127. 91 | These are stored in an internal buffer and played back at 48kHz. 92 | If this buffer is full, this function will return false. 93 | """ 94 | 95 | """Related CC-Tweaked issues 96 | Streaming HTTP response https://github.com/cc-tweaked/CC-Tweaked/issues/1181 97 | Speaker Networks https://github.com/cc-tweaked/CC-Tweaked/issues/1488 98 | Pocket computers do not have many usecases without network access 99 | https://github.com/cc-tweaked/CC-Tweaked/issues/1406 100 | Speaker limit to 8 https://github.com/cc-tweaked/CC-Tweaked/issues/1313 101 | Some way to notify player through pocket computer with modem 102 | https://github.com/cc-tweaked/CC-Tweaked/issues/1148 103 | Memory limits for computers https://github.com/cc-tweaked/CC-Tweaked/issues/1580 104 | """ 105 | 106 | """TODO: Add those: 107 | AudioDevices: 108 | - Speaker Note (Sound) https://tweaked.cc/peripheral/speaker.html 109 | - Notblock https://www.youtube.com/watch?v=XY5UvTxD9dA 110 | - Create Steam whistles https://www.youtube.com/watch?v=dgZ4F7U19do 111 | https://github.com/danielathome19/MIDIToComputerCraft/tree/master 112 | 113 | Video Formats: 114 | - 32vid binary https://github.com/MCJack123/sanjuuni 115 | - qtv https://github.com/Axisok/qtccv 116 | 117 | Audio Formats: 118 | - DFPWM ffmpeg fallback ? https://github.com/asiekierka/pixmess/blob/master/scraps/aucmp.py 119 | - PCM 120 | - NBS https://github.com/Xella37/NBS-Tunes-CC 121 | - MIDI https://github.com/OpenPrograms/Sangar-Programs/blob/master/midi.lua 122 | - XM https://github.com/MCJack123/tracc 123 | 124 | Audio u. Video preview / thumbnail: 125 | - NFP https://tweaked.cc/library/cc.image.nft.html 126 | - bimg https://github.com/SkyTheCodeMaster/bimg 127 | - as 1 qtv frame 128 | - as 1 32vid frame 129 | """ 130 | 131 | logger = setup_logging() 132 | # TODO: change sanic logging format 133 | 134 | 135 | async def get_vid(vid_file: str, tracker: int) -> List[str]: 136 | """Returns given line of 32vid file""" 137 | async with await open_async(file=vid_file, mode="r", encoding="utf-8") as file: 138 | await file.seek(tracker) 139 | lines = [] 140 | for _unused in range(FRAMES_AT_ONCE): 141 | lines.append((await file.readline())[:-1]) # remove \n 142 | 143 | return lines 144 | 145 | 146 | async def getchunk(media_file: str, chunkindex: int) -> bytes: 147 | """Returns a chunk of the given media file""" 148 | async with await open_async(file=media_file, mode="rb") as file: 149 | await file.seek(chunkindex * CHUNKS_AT_ONCE) 150 | return await file.read(CHUNKS_AT_ONCE) 151 | 152 | 153 | # pylint: enable=redefined-outer-name 154 | 155 | 156 | def assert_resp( 157 | __obj_name: str, 158 | __obj: Any, 159 | __class_or_tuple: Union[ 160 | Type, UnionType, Tuple[Union[Type, UnionType, Tuple[Any, ...]], ...] 161 | ], 162 | ) -> Union[dict, None]: 163 | """ 164 | "assert" / isinstance that returns a dict that can be send as a ws response 165 | """ 166 | if not isinstance(__obj, __class_or_tuple): 167 | return { 168 | "action": "error", 169 | "message": f"{__obj_name} must be a {__class_or_tuple.__name__}", 170 | } 171 | return None 172 | 173 | 174 | # pylint: disable=duplicate-code 175 | spotify_client_id = getenv("SPOTIPY_CLIENT_ID") 176 | spotify_client_secret = getenv("SPOTIPY_CLIENT_SECRET") 177 | # pylint: disable-next=invalid-name 178 | spotipy = None 179 | 180 | if spotify_client_id and spotify_client_secret: 181 | spotipy = Spotify( 182 | auth_manager=SpotifyClientCredentials( 183 | client_id=spotify_client_id, 184 | client_secret=spotify_client_secret, 185 | cache_handler=MemoryCacheHandler(), 186 | ) 187 | ) 188 | 189 | # pylint: disable-next=invalid-name 190 | spotify_url_processor = None 191 | if spotipy: 192 | spotify_url_processor = SpotifyURLProcessor(spotipy) 193 | 194 | # pylint: enable=duplicate-code 195 | 196 | 197 | class Actions: 198 | """ 199 | Default set of actions 200 | Every action needs to be called with a message and needs to return a dict response 201 | """ 202 | 203 | # pylint: disable=missing-function-docstring 204 | 205 | @staticmethod 206 | async def request_media(message: dict, resp: Websocket, request: Request): 207 | loop = get_event_loop() 208 | # get "url" 209 | url = message.get("url") 210 | if error := assert_resp("url", url, str): 211 | return error 212 | # TODO: assert_resp width and height 213 | out, files = await run_function_in_thread_from_async_function( 214 | download, 215 | url, 216 | resp, 217 | loop, 218 | message.get("width"), 219 | message.get("height"), 220 | spotify_url_processor, 221 | ) 222 | for file in files: 223 | request.app.shared_ctx.data[file] = datetime.now() 224 | return out 225 | 226 | @staticmethod 227 | async def get_chunk(message: dict, _unused, request: Request): 228 | # get "chunkindex" 229 | chunkindex = message.get("chunkindex") 230 | if error := assert_resp("chunkindex", chunkindex, int): 231 | return error 232 | 233 | # get "id" 234 | media_id = message.get("id") 235 | if error := assert_resp("media_id", media_id, str): 236 | return error 237 | 238 | if is_save(media_id): 239 | file_name = get_audio_name(message.get("id")) 240 | file = join(DATA_FOLDER, file_name) 241 | 242 | request.app.shared_ctx.data[file_name] = datetime.now() 243 | chunk = await getchunk(file, chunkindex) 244 | 245 | return {"action": "chunk", "chunk": b64encode(chunk).decode("ascii")} 246 | logger.warning("User tried to use special Characters") 247 | return {"action": "error", "message": "You dare not use special Characters"} 248 | 249 | @staticmethod 250 | async def get_vid(message: dict, _unused, request: Request): 251 | # get "line" 252 | tracker = message.get("tracker") 253 | if error := assert_resp("tracker", tracker, int): 254 | return error 255 | 256 | # get "id" 257 | media_id = message.get("id") 258 | if error := assert_resp("id", media_id, str): 259 | return error 260 | 261 | # get "width" 262 | width = message.get("width") 263 | if error := assert_resp("width", width, int): 264 | return error 265 | 266 | # get "height" 267 | height = message.get("height") 268 | if error := assert_resp("height", height, int): 269 | return error 270 | 271 | # cap height and width 272 | width, height = cap_width_and_height(width, height) 273 | 274 | if is_save(media_id): 275 | file_name = get_video_name(message.get("id"), width, height) 276 | file = join(DATA_FOLDER, file_name) 277 | 278 | request.app.shared_ctx.data[file_name] = datetime.now() 279 | 280 | return {"action": "vid", "lines": await get_vid(file, tracker)} 281 | 282 | return {"action": "error", "message": "You dare not use special Characters"} 283 | 284 | @staticmethod 285 | async def handshake(*_unused): 286 | return { 287 | "action": "handshake", 288 | "server": {"version": VERSION}, 289 | "api": {"version": API_VERSION}, 290 | "capabilities": {"video": ["32vid"], "audio": ["dfpwm"]}, 291 | } 292 | 293 | # pylint: enable=missing-function-docstring 294 | 295 | 296 | class CustomErrorHandler(ErrorHandler): 297 | """Error handler for sanic""" 298 | 299 | def default(self, request: Request, exception: Union[SanicException, Exception]): 300 | """handles errors that have no error handlers assigned""" 301 | 302 | if isinstance(exception, SanicException) and exception.status_code == 426: 303 | # TODO: Respond with nice html that tells the user how to install YC 304 | return text( 305 | "You cannot access a YouCube server directly. " 306 | "You need the YouCube client. " 307 | "See https://youcube.madefor.cc/guides/client/installation/" 308 | ) 309 | 310 | return super().default(request, exception) 311 | 312 | 313 | app = Sanic("youcube") 314 | app.error_handler = CustomErrorHandler() 315 | # FIXME: The Client is not Responsing to Websocket pings 316 | app.config.WEBSOCKET_PING_INTERVAL = 0 317 | # FIXME: Add UVLOOP support for alpine pypy 318 | if getenv("SANIC_NO_UVLOOP"): 319 | app.config.USE_UVLOOP = False 320 | 321 | actions = {} 322 | 323 | # add all actions from default action set 324 | for method in dir(Actions): 325 | if not method.startswith("__"): 326 | actions[method] = getattr(Actions, method) 327 | 328 | 329 | DATA_CACHE_CLEANUP_INTERVAL = int(getenv("DATA_CACHE_CLEANUP_INTERVAL", "300")) 330 | DATA_CACHE_CLEANUP_AFTER = int(getenv("DATA_CACHE_CLEANUP_AFTER", "3600")) 331 | 332 | 333 | def data_cache_cleaner(data: dict): 334 | """ 335 | Checks for outdated cache entries every DATA_CACHE_CLEANUP_INTERVAL (default 300) Seconds and 336 | deletes them if they have not been used for DATA_CACHE_CLEANUP_AFTER (default 3600) Seconds. 337 | """ 338 | try: 339 | while True: 340 | sleep(DATA_CACHE_CLEANUP_INTERVAL) 341 | for file_name, last_used in data.items(): 342 | if ( 343 | datetime.now() - last_used 344 | ).total_seconds() > DATA_CACHE_CLEANUP_AFTER: 345 | file_path = join(DATA_FOLDER, file_name) 346 | if exists(file_path): 347 | remove(file_path) 348 | logger.debug('Deleted "%s"', file_name) 349 | data.pop(file_name) 350 | 351 | except KeyboardInterrupt: 352 | pass 353 | 354 | 355 | # pylint: disable=redefined-outer-name 356 | @app.main_process_ready 357 | async def ready(app: Sanic, _): 358 | """See https://sanic.dev/en/guide/basics/listeners.html""" 359 | if DATA_CACHE_CLEANUP_INTERVAL > 0 and DATA_CACHE_CLEANUP_AFTER > 0: 360 | app.manager.manage( 361 | "Data-Cache-Cleaner", data_cache_cleaner, {"data": app.shared_ctx.data} 362 | ) 363 | 364 | 365 | @app.main_process_start 366 | async def main_start(app: Sanic): 367 | """See https://sanic.dev/en/guide/basics/listeners.html""" 368 | app.shared_ctx.data = Manager().dict() 369 | 370 | if which(FFMPEG_PATH) is None: 371 | logger.warning("FFmpeg not found.") 372 | 373 | if which(SANJUUNI_PATH) is None: 374 | logger.warning("Sanjuuni not found.") 375 | 376 | if spotipy: 377 | logger.info("Spotipy Enabled") 378 | else: 379 | logger.info("Spotipy Disabled") 380 | 381 | 382 | @app.route("/dfpwm//") 383 | async def stream_dfpwm(_request: Request, media_id: str, chunkindex: int): 384 | """WIP HTTP mode""" 385 | return raw(await getchunk(join(DATA_FOLDER, get_audio_name(media_id)), chunkindex)) 386 | 387 | 388 | @app.route("/32vid////") # , stream=True 389 | async def stream_32vid( 390 | _request: Request, media_id: str, width: int, height: int, tracker: int 391 | ): 392 | """WIP HTTP mode""" 393 | return raw( 394 | "\n".join( 395 | await get_vid(join(DATA_FOLDER, get_video_name(media_id, width, height)), tracker) 396 | ) 397 | ) 398 | 399 | 400 | """" 401 | from sanic import response 402 | @app.route("/dfpwm/") 403 | async def stream_dfpwm(request: Request, id: str): 404 | file_name = get_audio_name(id) 405 | file = join(DATA_FOLDER, get_audio_name(id)) 406 | return await response.file_stream( 407 | file, 408 | chunk_size=CHUNKS_AT_ONCE, 409 | mime_type="application/metalink4+xml", 410 | headers={ 411 | "Content-Disposition": f'Attachment; filename="{file_name}"', 412 | "Content-Type": "application/metalink4+xml", 413 | }, 414 | ) 415 | 416 | @app.route("/32vid///", stream=True) 417 | async def stream_32vid(request: Request, id: str, width: int, height: int): 418 | file_name = get_video_name(id, width, height) 419 | file = join( 420 | DATA_FOLDER, 421 | file_name 422 | ) 423 | return await response.file_stream( 424 | file, 425 | chunk_size=10, 426 | mime_type="application/metalink4+xml", 427 | headers={ 428 | "Content-Disposition": f'Attachment; filename="{file_name}"', 429 | "Content-Type": "application/metalink4+xml", 430 | }, 431 | ) 432 | """ 433 | # pylint: enable=redefined-outer-name 434 | 435 | 436 | @app.websocket("/") 437 | # pylint: disable-next=invalid-name 438 | async def wshandler(request: Request, ws: Websocket): 439 | """Handels web-socket requests""" 440 | if NO_COLOR: 441 | prefix = f"[{request.client_ip}] " 442 | else: 443 | prefix = f"{Foreground.BLUE}[{request.client_ip}]{RESET} " 444 | 445 | logger.info("%sConnected!", prefix) 446 | 447 | logger.debug("%sMy headers are: %s", prefix, request.headers) 448 | 449 | while True: 450 | message = await ws.recv() 451 | logger.debug("%sMessage: %s", prefix, message) 452 | 453 | try: 454 | message: dict = load_json(message) 455 | except JSONDecodeError: 456 | logger.debug("%sFaild to parse Json", prefix) 457 | await ws.send(dumps({"action": "error", "message": "Faild to parse Json"})) 458 | 459 | if message.get("action") in actions: 460 | response = await actions[message.get("action")](message, ws, request) 461 | await ws.send(dumps(response)) 462 | 463 | 464 | def main() -> None: 465 | """ 466 | Run all needed services 467 | """ 468 | port = int(getenv("PORT", "5000")) 469 | host = getenv("HOST", "127.0.0.1") 470 | fast = not getenv("NO_FAST") 471 | 472 | app.run(host=host, port=port, fast=fast, access_log=True) 473 | 474 | 475 | if __name__ == "__main__": 476 | main() 477 | --------------------------------------------------------------------------------