├── .github └── workflows │ ├── autoupdate-yt-dlp.yml │ ├── issue-handler.yml │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── gunicorn_config.py ├── requirements.txt ├── src ├── Syncify.py ├── static │ ├── logo.png │ ├── script.js │ ├── style.css │ ├── syncify.png │ └── syncify_full_logo.png └── templates │ └── base.html └── thewicklowwolf-init.sh /.github/workflows/autoupdate-yt-dlp.yml: -------------------------------------------------------------------------------- 1 | name: autoupdate-yt-dlp 2 | 3 | on: 4 | workflow_dispatch: 5 | schedule: 6 | - cron: '00 23 * * *' 7 | 8 | jobs: 9 | autoupdate-yt-dlp: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v4 15 | with: 16 | token: ${{ secrets.PAT_TOKEN }} 17 | 18 | - name: Set up Python 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: '3.12' 22 | 23 | - name: Install pipenv 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install pipenv 27 | 28 | - name: Install yt-dlp and get version 29 | id: check_version 30 | run: | 31 | pipenv install yt-dlp 32 | latest_version=$(pipenv run pip show yt-dlp | grep Version | cut -d' ' -f2) 33 | current_version=$(grep -oP "(?<=yt_dlp\[default\]==)\d+(\.\d+)+" requirements.txt || echo "0.0.0") 34 | echo "LATEST_VERSION=$latest_version" >> $GITHUB_ENV 35 | echo "CURRENT_VERSION=$current_version" >> $GITHUB_ENV 36 | 37 | - name: Compare versions and update requirements.txt if necessary 38 | if: ${{ env.LATEST_VERSION != env.CURRENT_VERSION }} 39 | run: | 40 | latest_version=${{ env.LATEST_VERSION }} 41 | sed -i "s/^yt_dlp\[default\].*/yt_dlp\[default\]==$latest_version/" requirements.txt 42 | git config --global user.email "yt-dlp@autoupdate" 43 | git config --global user.name "yt-dlp-autoupdate" 44 | git add requirements.txt 45 | git commit -m "Update yt-dlp version to $latest_version" 46 | git push 47 | -------------------------------------------------------------------------------- /.github/workflows/issue-handler.yml: -------------------------------------------------------------------------------- 1 | name: Close Non-Bug Issues 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | issues: 7 | types: [opened] 8 | 9 | jobs: 10 | close-issue-if-not-bug: 11 | runs-on: ubuntu-latest 12 | env: 13 | GH_TOKEN: ${{ secrets.PAT_TOKEN }} 14 | steps: 15 | - name: Check if the issue contains "bug" 16 | id: check_bug 17 | env: 18 | BODY: ${{ github.event.issue.body }} 19 | TITLE: ${{ github.event.issue.title }} 20 | run: | 21 | # Check if the title or body contains "bug" 22 | if echo "$TITLE" | grep -qi 'bug' || echo "$BODY" | grep -qi 'bug'; then 23 | echo "This is a bug-related issue. Keeping it open." 24 | echo "is_bug=true" >> $GITHUB_ENV 25 | else 26 | echo "This is not a bug-related issue. Closing it." 27 | echo "is_bug=false" >> $GITHUB_ENV 28 | fi 29 | 30 | - name: Close issue and add comment if not bug 31 | if: env.is_bug == 'false' 32 | env: 33 | COMMENT: | 34 | ### Issue 35 | - **Feature Request:** 36 | If this is a feature request, unfortunately no new features are planned at present. The goal of this project is to keep the feature set as minimal as possible. Consider forking this repository and creating your own image to suit your requirements. 37 | **PRs** are open, but only for essential changes/features. 38 | 39 | - **Specific Issues:** 40 | If you're experiencing an issue, please check through previous issues first, as it may have already been addressed. 41 | If it hasn’t been covered, you'll need to clone this repository and run it locally to investigate the issue further. There are plenty of resources available to help you get familiar with Docker and the code used here, so please ensure you explore those fully. 42 | Please also note that this project may not work across all setups and systems. 43 | 44 | - **Genuine Bugs:** 45 | If you believe you've found a genuine bug that affects the main functionality, please raise an issue with detailed logs and a specific bug report. It would also be greatly appreciated if you can suggest a possible solution. 46 | 47 | Thanks, and best of luck! 48 | 49 | --- 50 | 51 | It can be frustrating when an **issue** gets closed automatically, but this process helps keep track of actionable bugs. 52 | **Feature requests** are only considered if the requester contributes code or takes significant steps toward implementing the feature themselves. Without this commitment or partial coding effort, the request will not be considered. Thank you for your understanding! 53 | 54 | --- 55 | 56 | **NOTE:** THIS IS AN AUTOMATICALLY GENERATED COMMENT. 57 | 58 | run: | 59 | gh issue close ${{ github.event.issue.number }} --comment "$COMMENT" --repo ${{ github.repository }} 60 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - main 8 | paths-ignore: 9 | - '**/*.md' 10 | 11 | jobs: 12 | bump-version-and-create-release-tag: 13 | runs-on: ubuntu-latest 14 | env: 15 | GH_TOKEN: ${{ secrets.PAT_TOKEN }} 16 | outputs: 17 | new_version: ${{ steps.increment_version.outputs.new_version }} 18 | 19 | steps: 20 | - name: Checkout repository 21 | uses: actions/checkout@v4 22 | with: 23 | token: ${{ secrets.PAT_TOKEN }} 24 | 25 | - name: Fetch and list tags 26 | run: | 27 | git fetch --tags 28 | echo "Tags:" 29 | git tag --list 30 | 31 | - name: Get current version 32 | id: get_version 33 | run: | 34 | VERSION=$(git tag --list | sed 's/^v//' | awk -F. '{ if (NF == 2) printf("%s.0.%s\n", $1, $2); else print $0 }' | sort -V | tail -n 1 | sed 's/^/v/') 35 | echo "CURRENT_VERSION=$VERSION" >> $GITHUB_ENV 36 | echo "Current version: $VERSION" 37 | 38 | - name: Increment version 39 | id: increment_version 40 | run: | 41 | NEW_VERSION=$(echo ${{ env.CURRENT_VERSION }} | awk -F. '{printf("%d.%d.%d", $1, $2, $3+1)}') 42 | echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV 43 | echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_OUTPUT 44 | echo "New version: $NEW_VERSION" 45 | 46 | - name: Create new Git tag 47 | run: | 48 | git config --global user.name 'github-actions[bot]' 49 | git config --global user.email 'github-actions[bot]@users.noreply.github.com' 50 | git tag -a v${{ env.NEW_VERSION }} -m "Release version ${{ env.NEW_VERSION }}" 51 | git push origin --tags 52 | 53 | - name: Create release 54 | run: | 55 | gh release create "v${{ env.NEW_VERSION }}" \ 56 | --repo="${GITHUB_REPOSITORY}" \ 57 | --title="v${{ env.NEW_VERSION }}" \ 58 | --generate-notes 59 | 60 | build-docker-image: 61 | runs-on: ubuntu-latest 62 | needs: bump-version-and-create-release-tag 63 | steps: 64 | - name: Checkout 65 | uses: actions/checkout@v4 66 | 67 | - name: Set up QEMU 68 | uses: docker/setup-qemu-action@v3 69 | 70 | - name: Set up Docker Buildx 71 | uses: docker/setup-buildx-action@v3 72 | 73 | - name: Login to Docker Hub 74 | uses: docker/login-action@v3 75 | with: 76 | username: ${{ secrets.DOCKERHUB_USERNAME }} 77 | password: ${{ secrets.DOCKERHUB_TOKEN }} 78 | 79 | - name: Convert repository name to lowercase 80 | id: lowercase_repo 81 | run: | 82 | REPO_NAME=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') 83 | echo "REPO_NAME=$REPO_NAME" >> $GITHUB_ENV 84 | 85 | - name: Build and push 86 | uses: docker/build-push-action@v5 87 | with: 88 | context: . 89 | platforms: linux/amd64,linux/arm64 90 | file: ./Dockerfile 91 | push: true 92 | build-args: | 93 | RELEASE_VERSION=${{ needs.bump-version-and-create-release-tag.outputs.new_version }} 94 | tags: | 95 | ${{ env.REPO_NAME }}:${{ needs.bump-version-and-create-release-tag.outputs.new_version }} 96 | ${{ env.REPO_NAME }}:latest 97 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .cache 2 | .idea 3 | config/ 4 | downloads/ 5 | venv/ 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.12-alpine 2 | 3 | # Set build arguments 4 | ARG RELEASE_VERSION 5 | ENV RELEASE_VERSION=${RELEASE_VERSION} 6 | 7 | # Install ffmpeg and su-exec 8 | RUN apk update && apk add --no-cache ffmpeg su-exec 9 | 10 | # Create directories and set permissions 11 | COPY . /syncify 12 | WORKDIR /syncify 13 | 14 | # Install requirements 15 | RUN pip install --no-cache-dir -r requirements.txt 16 | 17 | # Make the script executable 18 | RUN chmod +x thewicklowwolf-init.sh 19 | 20 | # Expose port 21 | EXPOSE 5000 22 | 23 | # Start the app 24 | ENTRYPOINT ["./thewicklowwolf-init.sh"] 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Build Status](https://github.com/TheWicklowWolf/Syncify/actions/workflows/main.yml/badge.svg) 2 | ![Docker Pulls](https://img.shields.io/docker/pulls/thewicklowwolf/syncify.svg) 3 | 4 | 5 | logo 6 | 7 | 8 | Syncify is a tool for synchronising and fetching content from Spotify or YouTube playlists via yt-dlp. 9 | 10 | 11 | ## Run using docker-compose 12 | 13 | ```yaml 14 | services: 15 | syncify: 16 | image: thewicklowwolf/syncify:latest 17 | container_name: syncify 18 | volumes: 19 | - /path/to/config:/syncify/config 20 | - /data/media/syncify:/syncify/downloads 21 | - /etc/localtime:/etc/localtime:ro 22 | ports: 23 | - 5000:5000 24 | environment: 25 | - thread_limit=1 26 | - crop_album_art=false 27 | restart: unless-stopped 28 | ``` 29 | 30 | 31 | ## Configuration via environment variables 32 | 33 | Certain values can be set via environment variables: 34 | 35 | * __PUID__: The user ID to run the app with. Defaults to `1000`. 36 | * __PGID__: The group ID to run the app with. Defaults to `1000`. 37 | * __thread_limit__: Max number of threads to use. Defaults to `1`. 38 | * __crop_album_art__: Set this to `true` to force the creation of square album art instead of using the 16:9 aspect ratio from YouTube. Defaults to `false`. 39 | 40 | 41 | ## Sync Schedule 42 | 43 | Use a comma-separated list of hours to search for new tracks (e.g. `2, 20` will initiate a search at 2 AM and 8 PM). 44 | > Note: There is a deadband of up to 10 minutes from the scheduled start time. 45 | 46 | 47 | ## Cookies (optional) 48 | To utilize a cookies file with yt-dlp, follow these steps: 49 | 50 | * Generate Cookies File: Open your web browser and use a suitable extension (e.g. cookies.txt for Firefox) to extract cookies for a user on YT. 51 | 52 | * Save Cookies File: Save the obtained cookies into a file named `cookies.txt` and put it into the config folder. 53 | 54 | 55 | --- 56 | 57 | ![image](https://github.com/TheWicklowWolf/Syncify/assets/111055425/025365a6-095f-4110-9c28-4be2921d6f47) 58 | 59 | --- 60 | 61 | ![SyncifyDark](https://github.com/TheWicklowWolf/Syncify/assets/111055425/0ef9bb70-77c4-4da5-95b5-889839b63b84) 62 | 63 | --- 64 | 65 | 66 | https://hub.docker.com/r/thewicklowwolf/syncify 67 | -------------------------------------------------------------------------------- /gunicorn_config.py: -------------------------------------------------------------------------------- 1 | bind = "0.0.0.0:5000" 2 | workers = 1 3 | threads = 4 4 | timeout = 120 5 | worker_class = "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" 6 | 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | gunicorn 2 | gevent 3 | gevent-websocket 4 | flask 5 | flask_socketio 6 | spotipy 7 | spotipy_anon 8 | yt_dlp[default]==2025.5.22 9 | plexapi 10 | ytmusicapi 11 | requests 12 | thefuzz 13 | -------------------------------------------------------------------------------- /src/Syncify.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sys 4 | import json 5 | import time 6 | import logging 7 | import tempfile 8 | import datetime 9 | import threading 10 | import concurrent.futures 11 | from urllib.parse import urlparse, parse_qs 12 | from flask import Flask, render_template 13 | from flask_socketio import SocketIO 14 | from ytmusicapi import YTMusic 15 | import yt_dlp 16 | from plexapi.server import PlexServer 17 | import spotipy 18 | from spotipy.oauth2 import SpotifyClientCredentials 19 | from spotipy_anon import SpotifyAnon 20 | import requests 21 | from thefuzz import fuzz 22 | 23 | 24 | class DataHandler: 25 | YOUTUBE_LINK_PREFIX = "https://www.youtube.com/watch?v=" 26 | 27 | def __init__(self): 28 | logging.basicConfig(level=logging.WARNING, format="%(asctime)s %(message)s", datefmt="%d/%m/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)]) 29 | self.logger = logging.getLogger() 30 | 31 | app_name_text = os.path.basename(__file__).replace(".py", "") 32 | release_version = os.environ.get("RELEASE_VERSION", "unknown") 33 | self.logger.warning(f"{'*' * 50}\n") 34 | self.logger.warning(f"{app_name_text} Version: {release_version}\n") 35 | self.logger.warning(f"{'*' * 50}") 36 | 37 | self.config_folder = "config" 38 | self.download_folder = "downloads" 39 | self.media_server_addresses = "Plex: http://192.168.1.2:32400, Jellyfin: http://192.168.1.2:8096" 40 | self.media_server_tokens = "Plex: abc, Jellyfin: xyz" 41 | self.media_server_library_name = "Music" 42 | self.spotify_client_id = "" 43 | self.spotify_client_secret = "" 44 | self.thread_limit = int(os.environ.get("thread_limit", 1)) 45 | self.media_server_scan_req_flag = False 46 | self.crop_album_art = os.getenv("crop_album_art", "false").lower() 47 | 48 | if not os.path.exists(self.config_folder): 49 | os.makedirs(self.config_folder) 50 | if not os.path.exists(self.download_folder): 51 | os.makedirs(self.download_folder) 52 | 53 | self.sync_start_times = [0] 54 | self.settings_config_file = os.path.join(self.config_folder, "settings_config.json") 55 | 56 | self.sync_list = [] 57 | self.sync_list_config_file = os.path.join(self.config_folder, "sync_list.json") 58 | 59 | if os.path.exists(self.settings_config_file): 60 | self.load_from_file() 61 | 62 | if os.path.exists(self.sync_list_config_file): 63 | self.load_sync_list_from_file() 64 | 65 | full_cookies_path = os.path.join(self.config_folder, "cookies.txt") 66 | self.cookies_path = full_cookies_path if os.path.exists(full_cookies_path) else None 67 | self.sync_in_progress_flag = False 68 | 69 | task_thread = threading.Thread(target=self.schedule_checker) 70 | task_thread.daemon = True 71 | task_thread.start() 72 | 73 | def load_from_file(self): 74 | try: 75 | with open(self.settings_config_file, "r") as json_file: 76 | ret = json.load(json_file) 77 | self.sync_start_times = ret["sync_start_times"] 78 | self.media_server_addresses = ret["media_server_addresses"] 79 | self.media_server_tokens = ret["media_server_tokens"] 80 | self.media_server_library_name = ret["media_server_library_name"] 81 | self.spotify_client_id = ret["spotify_client_id"] 82 | self.spotify_client_secret = ret["spotify_client_secret"] 83 | 84 | except Exception as e: 85 | self.logger.error(f"Error Loading Config: {str(e)}") 86 | 87 | def save_to_file(self): 88 | try: 89 | with open(self.settings_config_file, "w") as json_file: 90 | json.dump( 91 | { 92 | "sync_start_times": self.sync_start_times, 93 | "media_server_addresses": self.media_server_addresses, 94 | "media_server_tokens": self.media_server_tokens, 95 | "media_server_library_name": self.media_server_library_name, 96 | "spotify_client_id": self.spotify_client_id, 97 | "spotify_client_secret": self.spotify_client_secret, 98 | }, 99 | json_file, 100 | indent=4, 101 | ) 102 | 103 | except Exception as e: 104 | self.logger.error(f"Error Saving Config: {str(e)}") 105 | 106 | def load_sync_list_from_file(self): 107 | try: 108 | with open(self.sync_list_config_file, "r") as json_file: 109 | self.sync_list = json.load(json_file) 110 | 111 | except Exception as e: 112 | self.logger.error(f"Error Loading Playlists: {str(e)}") 113 | 114 | def save_sync_list_to_file(self): 115 | try: 116 | with open(self.sync_list_config_file, "w") as json_file: 117 | json.dump(self.sync_list, json_file, indent=4) 118 | 119 | except Exception as e: 120 | self.logger.error(f"Error Saving Playlists: {str(e)}") 121 | 122 | def schedule_checker(self): 123 | self.logger.warning("Starting periodic checks every 10 minutes to monitor sync start times.") 124 | self.logger.warning(f"Current scheduled hours to start sync (in 24-hour format): {self.sync_start_times}") 125 | 126 | while True: 127 | current_time = datetime.datetime.now().time() 128 | within_sync_window = any(datetime.time(t, 0, 0) <= current_time <= datetime.time(t, 59, 59) for t in self.sync_start_times) 129 | 130 | if within_sync_window and self.sync_in_progress_flag: 131 | self.logger.warning(f"In Sync Window but sync already in progress.") 132 | self.logger.warning(f"Checking again in 10 minutes.") 133 | time.sleep(600) 134 | 135 | elif within_sync_window and not self.sync_in_progress_flag: 136 | self.logger.warning(f"Time to Start Sync - as in a time window {self.sync_start_times}") 137 | self.master_queue() 138 | self.logger.warning("Big sleep for 1 Hour - Sync Done") 139 | time.sleep(3600) 140 | self.logger.warning(f"Checking every 10 minutes as not in sync time window {self.sync_start_times}") 141 | 142 | else: 143 | time.sleep(600) 144 | 145 | def spotify_extractor(self, link): 146 | sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=self.spotify_client_id, client_secret=self.spotify_client_secret)) 147 | sp_anon = spotipy.Spotify(auth_manager=SpotifyAnon()) 148 | 149 | track_list = [] 150 | 151 | if "album" in link: 152 | album_info = sp.album(link) 153 | album_name = album_info["name"] 154 | album = sp.album_tracks(link) 155 | for item in album["items"]: 156 | try: 157 | track_title = item["name"] 158 | artists = [artist["name"] for artist in item["artists"]] 159 | artists_str = ", ".join(artists) 160 | track_list.append({"Artist": artists_str, "Title": track_title, "Status": "Queued", "Folder": album_name}) 161 | 162 | except Exception as e: 163 | self.logger.error(f"Error Parsing Item in Album: {str(item)} - {str(e)}") 164 | 165 | else: 166 | try: 167 | playlist = sp.playlist(link) 168 | 169 | except Exception as e: 170 | self.logger.error(f"Error using authenticated account to get playlist: {str(e)}.") 171 | self.logger.info(f"Attempting to use anonymous authentication...") 172 | playlist = sp_anon.playlist(link) 173 | 174 | playlist_name = playlist["name"] 175 | number_of_tracks = playlist["tracks"]["total"] 176 | fields = "items(track(name,artists(name)),added_at)" 177 | 178 | offset = 0 179 | limit = 100 180 | all_items = [] 181 | while offset < number_of_tracks: 182 | try: 183 | results = sp.playlist_items(link, fields=fields, limit=limit, offset=offset) 184 | 185 | except Exception as e: 186 | self.logger.error(f"Error using authenticated account to get playlist: {str(e)}.") 187 | self.logger.info(f"Attempting to use anonymous authentication...") 188 | results = sp_anon.playlist_items(link, fields=fields, limit=limit, offset=offset) 189 | 190 | all_items.extend(results["items"]) 191 | offset += limit 192 | 193 | all_items_sorted = sorted(all_items, key=lambda x: x["added_at"], reverse=False) 194 | for item in all_items_sorted: 195 | try: 196 | track = item["track"] 197 | track_title = track["name"] 198 | artists = [artist["name"] for artist in track["artists"]] 199 | artists_str = ", ".join(artists) 200 | track_list.append({"Artist": artists_str, "Title": track_title, "Status": "Queued", "Folder": playlist_name}) 201 | 202 | except Exception as e: 203 | self.logger.error(f"Error Parsing Item in Playlist: {str(item)} - {str(e)}") 204 | 205 | return track_list 206 | 207 | def youtube_extractor(self, link): 208 | self.ytmusic = YTMusic() 209 | track_list = [] 210 | playlist_id = parse_qs(urlparse(link).query).get("list", [None])[0] 211 | if playlist_id: 212 | playlist = self.ytmusic.get_playlist(playlist_id) 213 | playlist_name = playlist["title"] 214 | 215 | for track in playlist["tracks"]: 216 | track_title = track["title"] 217 | artist_str = ", ".join([a["name"] for a in track["artists"]]) 218 | track_list.append({"Artist": artist_str, "Title": track_title, "Status": "Queued", "Folder": playlist_name, "VideoID": track["videoId"]}) 219 | else: 220 | self.logger.error("Unsupported youtube playlist url! It must have a list= query params.") 221 | 222 | return track_list 223 | 224 | def find_youtube_link(self, artist, title): 225 | try: 226 | first_result = None 227 | 228 | self.ytmusic = YTMusic() 229 | search_results = self.ytmusic.search(query=f"{artist} - {title}", filter="songs", limit=5) 230 | 231 | cleaned_artist = self.string_cleaner(artist).lower() 232 | cleaned_title = self.string_cleaner(title).lower() 233 | for item in search_results: 234 | cleaned_youtube_title = self.string_cleaner(item["title"]).lower() 235 | if cleaned_title in cleaned_youtube_title: 236 | first_result = self.YOUTUBE_LINK_PREFIX + item["videoId"] 237 | break 238 | else: 239 | # Try again but check for a partial match 240 | for item in search_results: 241 | cleaned_youtube_title = self.string_cleaner(item["title"]).lower() 242 | cleaned_youtube_artists = ", ".join(self.string_cleaner(x["name"]).lower() for x in item["artists"]) 243 | 244 | title_ratio = 100 if all(word in cleaned_title for word in cleaned_youtube_title.split()) else fuzz.ratio(cleaned_title, cleaned_youtube_title) 245 | artist_ratio = 100 if cleaned_artist in cleaned_youtube_artists else fuzz.ratio(cleaned_artist, cleaned_youtube_artists) 246 | 247 | if title_ratio >= 90 and artist_ratio >= 90: 248 | first_result = self.YOUTUBE_LINK_PREFIX + item["videoId"] 249 | break 250 | else: 251 | # Default to first result if Top result is not found 252 | first_result = self.YOUTUBE_LINK_PREFIX + search_results[0]["videoId"] 253 | 254 | # Search for Top result specifically 255 | top_search_results = self.ytmusic.search(query=cleaned_title, limit=5) 256 | cleaned_youtube_title = self.string_cleaner(top_search_results[0]["title"]).lower() 257 | if "Top result" in top_search_results[0]["category"] and top_search_results[0]["resultType"] == "song" or top_search_results[0]["resultType"] == "video": 258 | cleaned_youtube_artists = ", ".join(self.string_cleaner(x["name"]).lower() for x in top_search_results[0]["artists"]) 259 | title_ratio = 100 if cleaned_title in cleaned_youtube_title else fuzz.ratio(cleaned_title, cleaned_youtube_title) 260 | artist_ratio = 100 if cleaned_artist in cleaned_youtube_artists else fuzz.ratio(cleaned_artist, cleaned_youtube_artists) 261 | if (title_ratio >= 90 and artist_ratio >= 40) or (title_ratio >= 40 and artist_ratio >= 90): 262 | first_result = self.YOUTUBE_LINK_PREFIX + top_search_results[0]["videoId"] 263 | 264 | except Exception as e: 265 | self.logger.error(f"Error Finding YouTube Link: {str(e)}") 266 | 267 | finally: 268 | return first_result 269 | 270 | def get_download_list(self, playlist): 271 | try: 272 | song_list_to_download = [] 273 | playlist_name = playlist["Name"] 274 | playlist_link = playlist["Link"] 275 | if "youtube" in playlist_link: 276 | playlist_tracks = self.youtube_extractor(playlist_link) 277 | else: 278 | playlist_tracks = self.spotify_extractor(playlist_link) 279 | 280 | playlist_folder = playlist_name 281 | playlist_folder_full_path = os.path.join(self.download_folder, playlist_folder) 282 | 283 | if not os.path.exists(playlist_folder_full_path): 284 | os.makedirs(playlist_folder_full_path) 285 | 286 | raw_directory_list = os.listdir(playlist_folder_full_path) 287 | directory_list = self.string_cleaner(raw_directory_list) 288 | 289 | with concurrent.futures.ThreadPoolExecutor(max_workers=self.thread_limit) as executor: 290 | futures = [] 291 | for song in playlist_tracks: 292 | full_file_name = f'{song["Title"]} - {song["Artist"]}' 293 | cleaned_full_file_name = self.string_cleaner(full_file_name) 294 | if cleaned_full_file_name not in directory_list: 295 | song_artist = song["Artist"] 296 | song_title = song["Title"] 297 | if song.get("VideoID"): 298 | song_actual_link = self.YOUTUBE_LINK_PREFIX + song["VideoID"] 299 | song_list_to_download.append({"title": cleaned_full_file_name, "link": song_actual_link, "playlist_folder": playlist_folder}) 300 | self.logger.warning(f"Added Song to Download List: {cleaned_full_file_name} : {song_actual_link}") 301 | else: 302 | future = executor.submit(self.find_youtube_link, song_artist, song_title) 303 | futures.append((future, cleaned_full_file_name)) 304 | self.logger.warning(f"Searching for Song: {cleaned_full_file_name}") 305 | else: 306 | self.logger.warning(f"File Already in folder: {cleaned_full_file_name}") 307 | 308 | for future, file_name in futures: 309 | song_actual_link = future.result() 310 | if song_actual_link: 311 | song_list_to_download.append({"title": file_name, "link": song_actual_link, "playlist_folder": playlist_folder}) 312 | self.logger.warning(f"Added Song to Download List: {file_name} : {song_actual_link}") 313 | else: 314 | self.logger.error(f"No Link Found for: {file_name}") 315 | 316 | except Exception as e: 317 | self.logger.error(f"Error Getting Download List: {str(e)}") 318 | 319 | finally: 320 | return song_list_to_download 321 | 322 | def download_queue(self, song_list, playlist): 323 | try: 324 | with concurrent.futures.ThreadPoolExecutor(max_workers=self.thread_limit) as executor: 325 | futures = [] 326 | for song in song_list: 327 | future = executor.submit(self.download_song, song, playlist) 328 | futures.append(future) 329 | 330 | concurrent.futures.wait(futures) 331 | 332 | except Exception as e: 333 | self.logger.error(f"Error in Download Queue: {str(e)}") 334 | 335 | def download_song(self, song, playlist): 336 | temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) 337 | self.media_server_scan_req_flag = True 338 | 339 | link = song["link"] 340 | title = song["title"] 341 | playlist_folder = song["playlist_folder"] 342 | sleep = playlist["Sleep"] if playlist["Sleep"] else 0 343 | full_file_path = os.path.join(playlist_folder, title) 344 | 345 | ydl_opts = { 346 | "logger": self.logger, 347 | "ffmpeg_location": "/usr/bin/ffmpeg", 348 | "format": "bestaudio", 349 | "outtmpl": f"{full_file_path}.%(ext)s", 350 | "paths": {"home": self.download_folder, "temp": temp_dir.name}, 351 | "quiet": False, 352 | "progress_hooks": [self.progress_callback], 353 | "writethumbnail": True, 354 | "updatetime": False, 355 | "postprocessors": [ 356 | { 357 | "key": "FFmpegExtractAudio", 358 | "preferredcodec": "mp3", 359 | "preferredquality": "0", 360 | }, 361 | { 362 | "key": "EmbedThumbnail", 363 | }, 364 | { 365 | "key": "FFmpegMetadata", 366 | }, 367 | ], 368 | } 369 | 370 | if self.crop_album_art == "true": 371 | ydl_opts["postprocessor_args"] = {"thumbnailsconvertor+ffmpeg_o": ["-c:v", "mjpeg", "-vf", "crop='if(gt(ih,iw),iw,ih)':'if(gt(iw,ih),ih,iw)'"]} 372 | 373 | if self.cookies_path: 374 | ydl_opts["cookiefile"] = self.cookies_path 375 | 376 | try: 377 | yt_downloader = yt_dlp.YoutubeDL(ydl_opts) 378 | self.logger.warning(f"yt_dlp - Starting Download of: {link}") 379 | 380 | yt_downloader.download([link]) 381 | self.logger.warning(f"yt_dlp - Finished Download of: {link}") 382 | 383 | time.sleep(sleep) 384 | 385 | except Exception as e: 386 | self.logger.error(f"Error downloading song: {link}. Error message: {e}") 387 | 388 | finally: 389 | temp_dir.cleanup() 390 | 391 | def progress_callback(self, d): 392 | if d["status"] == "finished": 393 | self.logger.warning("Download complete") 394 | self.logger.warning("Processing File...") 395 | 396 | elif d["status"] == "downloading": 397 | self.logger.warning(f'Downloaded {d["_percent_str"]} of {d["_total_bytes_str"]} at {d["_speed_str"]}') 398 | 399 | def master_queue(self): 400 | try: 401 | self.sync_in_progress_flag = True 402 | self.media_server_scan_req_flag = False 403 | self.logger.warning("Sync Task started...") 404 | for playlist in self.sync_list: 405 | logging.warning(f'Looking for Playlist Songs on YouTube: {playlist["Name"]}') 406 | song_list = self.get_download_list(playlist) 407 | 408 | logging.warning(f'Starting Downloading List: {playlist["Name"]}') 409 | self.download_queue(song_list, playlist) 410 | 411 | logging.warning(f'Finished Downloading List: {playlist["Name"]}') 412 | 413 | playlist["Song_Count"] = len(os.listdir(os.path.join(self.download_folder, playlist["Name"]))) 414 | logging.warning(f'Files in Directory: {str(playlist["Song_Count"])}') 415 | 416 | playlist["Last_Synced"] = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S") 417 | 418 | self.save_sync_list_to_file() 419 | data = {"sync_list": self.sync_list} 420 | socketio.emit("Update", data) 421 | 422 | if self.media_server_scan_req_flag == True and self.media_server_tokens: 423 | self.sync_media_servers() 424 | else: 425 | self.logger.warning("Media Server Sync not required") 426 | 427 | except Exception as e: 428 | self.logger.error(f"Error in Master Queue: {str(e)}") 429 | self.logger.warning("Finished: Incomplete") 430 | 431 | else: 432 | self.logger.warning("Finished: Complete") 433 | 434 | finally: 435 | self.sync_in_progress_flag = False 436 | 437 | def add_playlist(self, playlist): 438 | self.sync_list.extend(playlist) 439 | 440 | def sync_media_servers(self): 441 | media_servers = self.convert_string_to_dict(self.media_server_addresses) 442 | media_tokens = self.convert_string_to_dict(self.media_server_tokens) 443 | 444 | if "Plex" in media_servers and "Plex" in media_tokens: 445 | try: 446 | token = media_tokens.get("Plex") 447 | address = media_servers.get("Plex") 448 | self.logger.warning("Attempting Plex Sync") 449 | media_server_server = PlexServer(address, token) 450 | library_section = media_server_server.library.section(self.media_server_library_name) 451 | library_section.update() 452 | self.logger.warning(f"Plex Library scan for '{self.media_server_library_name}' started.") 453 | 454 | except Exception as e: 455 | self.logger.warning(f"Plex Library scan failed: {str(e)}") 456 | 457 | if "Jellyfin" in media_tokens and "Jellyfin" in media_tokens: 458 | try: 459 | token = media_tokens.get("Jellyfin") 460 | address = media_servers.get("Jellyfin") 461 | self.logger.warning("Attempting Jellyfin Sync") 462 | url = f"{address}/Library/Refresh?api_key={token}" 463 | response = requests.post(url) 464 | if response.status_code == 204: 465 | self.logger.warning("Jellyfin Library refresh request successful.") 466 | else: 467 | self.logger.warning(f"Jellyfin Error: {response.status_code}, {response.text}") 468 | 469 | except Exception as e: 470 | self.logger.warning(f"Jellyfin Library scan failed: {str(e)}") 471 | 472 | def string_cleaner(self, input_string): 473 | if isinstance(input_string, str): 474 | raw_string = re.sub(r'[\/:*?"<>|]', " ", input_string) 475 | temp_string = re.sub(r"\s+", " ", raw_string) 476 | cleaned_string = temp_string.strip() 477 | return cleaned_string 478 | 479 | elif isinstance(input_string, list): 480 | cleaned_strings = [] 481 | for string in input_string: 482 | file_name_without_extension, file_extension = os.path.splitext(string) 483 | raw_string = re.sub(r'[\/:*?"<>|]', " ", file_name_without_extension) 484 | temp_string = re.sub(r"\s+", " ", raw_string) 485 | cleaned_string = temp_string.strip() 486 | cleaned_strings.append(cleaned_string) 487 | return cleaned_strings 488 | 489 | def convert_string_to_dict(self, raw_string): 490 | result = {} 491 | if not raw_string: 492 | return result 493 | 494 | pairs = raw_string.split(",") 495 | for pair in pairs: 496 | key_value = pair.split(":", 1) 497 | if len(key_value) == 2: 498 | key, value = key_value 499 | result[key.strip()] = value.strip() 500 | 501 | return result 502 | 503 | def manual_start(self): 504 | self.logger.warning("Manual Sync Requested.") 505 | 506 | if self.sync_in_progress_flag == True: 507 | self.logger.warning(f"Sync already in progress.") 508 | 509 | else: 510 | self.logger.warning("Manual Sync Started.") 511 | task_thread = threading.Thread(target=self.master_queue, daemon=True) 512 | task_thread.start() 513 | 514 | 515 | app = Flask(__name__) 516 | app.secret_key = "secret_key" 517 | socketio = SocketIO(app) 518 | 519 | data_handler = DataHandler() 520 | 521 | 522 | @app.route("/") 523 | def home(): 524 | return render_template("base.html") 525 | 526 | 527 | @socketio.on("connect") 528 | def connection(): 529 | data = {"sync_list": data_handler.sync_list} 530 | socketio.emit("Update", data) 531 | 532 | 533 | @socketio.on("loadSettings") 534 | def loadSettings(): 535 | data = { 536 | "sync_start_times": data_handler.sync_start_times, 537 | "media_server_addresses": data_handler.media_server_addresses, 538 | "media_server_tokens": data_handler.media_server_tokens, 539 | "media_server_library_name": data_handler.media_server_library_name, 540 | "spotify_client_id": data_handler.spotify_client_id, 541 | "spotify_client_secret": data_handler.spotify_client_secret, 542 | } 543 | socketio.emit("settingsLoaded", data) 544 | 545 | 546 | @socketio.on("save_playlist_settings") 547 | def save_playlist_settings(data): 548 | try: 549 | playlist_to_be_saved = data["playlist"] 550 | playlist_name = playlist_to_be_saved["Name"] 551 | for playlist in data_handler.sync_list: 552 | if playlist["Name"] == playlist_name: 553 | playlist.update(playlist_to_be_saved) 554 | break 555 | else: 556 | data_handler.sync_list.append(playlist_to_be_saved) 557 | 558 | data_handler.save_sync_list_to_file() 559 | 560 | except Exception as e: 561 | data_handler.logger.error(f"Error Saving Playlist Settings: {str(e)}") 562 | 563 | 564 | @socketio.on("updateSettings") 565 | def updateSettings(data): 566 | try: 567 | data_handler.media_server_addresses = data["media_server_addresses"] 568 | data_handler.media_server_tokens = data["media_server_tokens"] 569 | data_handler.media_server_library_name = data["media_server_library_name"] 570 | data_handler.spotify_client_id = data["spotify_client_id"] 571 | data_handler.spotify_client_secret = data["spotify_client_secret"] 572 | 573 | if data["sync_start_times"] == "": 574 | data_handler.sync_start_times = [] 575 | 576 | else: 577 | raw_sync_start_times = [int(re.sub(r"\D", "", start_time.strip())) for start_time in data["sync_start_times"].split(",")] 578 | temp_sync_start_times = [0 if x < 0 or x > 23 else x for x in raw_sync_start_times] 579 | cleaned_sync_start_times = sorted(list(set(temp_sync_start_times))) 580 | data_handler.sync_start_times = cleaned_sync_start_times 581 | 582 | except Exception as e: 583 | data_handler.logger.error(f"Error Parsing Schedule: {str(e)}") 584 | data_handler.sync_start_times = [0] 585 | 586 | finally: 587 | data_handler.logger.warning(f"Sync Times: {str(data_handler.sync_start_times)}") 588 | data_handler.save_to_file() 589 | 590 | 591 | @socketio.on("add_playlist") 592 | def add_playlist(data): 593 | data_handler.add_playlist(data) 594 | 595 | 596 | @socketio.on("save_playlists") 597 | def save_playlists(data): 598 | data_handler.sync_list = data["Saved_sync_list"] 599 | data_handler.save_sync_list_to_file() 600 | 601 | 602 | @socketio.on("manual_start") 603 | def manual_start(): 604 | data_handler.manual_start() 605 | 606 | 607 | if __name__ == "__main__": 608 | socketio.run(app, host="0.0.0.0", port=5000) 609 | -------------------------------------------------------------------------------- /src/static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheWicklowWolf/Syncify/43e83e19e2d367d9676c63b331255533a6e19b4c/src/static/logo.png -------------------------------------------------------------------------------- /src/static/script.js: -------------------------------------------------------------------------------- 1 | 2 | var config_modal = document.getElementById('config-modal'); 3 | var save_message = document.getElementById("save-message"); 4 | var save_changes_button = document.getElementById("save-changes-button"); 5 | const manual_start_button = document.getElementById("manual-start-button"); 6 | var save_sync_list = document.getElementById("save-sync-list"); 7 | var save_sync_list_msg = document.getElementById("save-sync-list-msg"); 8 | var sync_start_times = document.getElementById("sync_start_times"); 9 | var media_server_addresses = document.getElementById("media_server_addresses"); 10 | var media_server_tokens = document.getElementById("media_server_tokens"); 11 | var media_server_library_name = document.getElementById("media_server_library_name"); 12 | var spotify_client_id = document.getElementById("spotify_client_id"); 13 | var spotify_client_secret = document.getElementById("spotify_client_secret"); 14 | var playlists = []; 15 | var socket = io(); 16 | 17 | function renderPlaylists() { 18 | var syncList = document.getElementById("sync-list"); 19 | syncList.innerHTML = ""; 20 | playlists.forEach((playlist, index) => { 21 | var row = document.createElement("tr"); 22 | row.innerHTML = ` 23 | ${playlist.Name} 24 | ${playlist.Last_Synced} 25 | ${playlist.Song_Count} 26 | 27 | 28 | 29 | `; 30 | var deleteButton = createDeleteButton(index); 31 | row.querySelector("td:last-child").appendChild(deleteButton); 32 | syncList.appendChild(row); 33 | }); 34 | } 35 | 36 | function removePlaylist(index) { 37 | playlists.splice(index, 1); 38 | renderPlaylists(); 39 | createEditModalsAndListeners(); 40 | } 41 | 42 | function createDeleteButton(index) { 43 | var deleteButton = document.createElement("button"); 44 | deleteButton.className = "btn btn-sm btn-warning custom-button-width"; 45 | deleteButton.textContent = "Delete"; 46 | deleteButton.addEventListener("click", function () { 47 | removePlaylist(index); 48 | }); 49 | return deleteButton; 50 | } 51 | 52 | function updated_info(response) { 53 | playlists = response.sync_list; 54 | renderPlaylists(); 55 | createEditModalsAndListeners(); 56 | } 57 | 58 | function createEditModalsAndListeners() { 59 | playlists.forEach((playlist, index) => { 60 | var editModal = document.createElement("div"); 61 | editModal.innerHTML = ` 62 | 94 | `; 95 | document.body.appendChild(editModal); 96 | }); 97 | } 98 | 99 | function savePlaylistSettings(index) { 100 | playlists[index].Name = document.getElementById(`playlistName${index}`).value; 101 | playlists[index].Link = document.getElementById(`playlistLink${index}`).value; 102 | playlists[index].Sleep = parseInt(document.getElementById(`playlistSleep${index}`).value, 10); 103 | socket.emit("save_playlist_settings", { "playlist": playlists[index] }); 104 | var save_message_playlist_edit = document.getElementById(`save-message-playlist-edit${index}`); 105 | save_message_playlist_edit.style.display = "block"; 106 | setTimeout(function () { 107 | save_message_playlist_edit.style.display = "none"; 108 | }, 1000); 109 | renderPlaylists(); 110 | } 111 | 112 | socket.on("Update", updated_info); 113 | 114 | document.getElementById("add-playlist").addEventListener("click", function () { 115 | playlists.push({ Name: "New Playlist", Link: "", Sleep: 0, Last_Synced: "Never", Song_Count: 0 }); 116 | renderPlaylists(); 117 | createEditModalsAndListeners(); 118 | }); 119 | 120 | config_modal.addEventListener('show.bs.modal', function (event) { 121 | socket.emit("loadSettings"); 122 | function handleSettingsLoaded(settings) { 123 | sync_start_times.value = settings.sync_start_times.join(', '); 124 | media_server_addresses.value = settings.media_server_addresses; 125 | media_server_tokens.value = settings.media_server_tokens; 126 | media_server_library_name.value = settings.media_server_library_name; 127 | spotify_client_id.value = settings.spotify_client_id; 128 | spotify_client_secret.value = settings.spotify_client_secret; 129 | socket.off("settingsLoaded", handleSettingsLoaded); 130 | } 131 | socket.on("settingsLoaded", handleSettingsLoaded); 132 | }); 133 | 134 | save_changes_button.addEventListener("click", () => { 135 | socket.emit("updateSettings", { 136 | "sync_start_times": sync_start_times.value, 137 | "media_server_addresses": media_server_addresses.value, 138 | "media_server_tokens": media_server_tokens.value, 139 | "media_server_library_name": media_server_library_name.value, 140 | "spotify_client_id": spotify_client_id.value, 141 | "spotify_client_secret": spotify_client_secret.value, 142 | }); 143 | save_message.style.display = "block"; 144 | save_message.textContent = "Settings saved successfully."; 145 | setTimeout(function () { 146 | save_message.style.display = "none"; 147 | }, 1000); 148 | }); 149 | 150 | save_sync_list.addEventListener("click", () => { 151 | socket.emit("save_playlists", { "Saved_sync_list": playlists }); 152 | save_sync_list_msg.style.display = "inline"; 153 | save_sync_list_msg.textContent = "Saved!"; 154 | setTimeout(function () { 155 | save_sync_list_msg.textContent = ""; 156 | save_message.style.display = "none"; 157 | }, 3000); 158 | }); 159 | 160 | manual_start_button.addEventListener("click", () => { 161 | socket.emit("manual_start"); 162 | save_message.style.display = "block"; 163 | save_message.textContent = "Manual Start Initiated."; 164 | setTimeout(function () { 165 | save_message.style.display = "none"; 166 | }, 1000); 167 | }); 168 | 169 | const themeSwitch = document.getElementById('themeSwitch'); 170 | const savedTheme = localStorage.getItem('theme'); 171 | const savedSwitchPosition = localStorage.getItem('switchPosition'); 172 | 173 | if (savedSwitchPosition) { 174 | themeSwitch.checked = savedSwitchPosition === 'true'; 175 | } 176 | 177 | if (savedTheme) { 178 | document.documentElement.setAttribute('data-bs-theme', savedTheme); 179 | } 180 | 181 | themeSwitch.addEventListener('click', () => { 182 | if (document.documentElement.getAttribute('data-bs-theme') === 'dark') { 183 | document.documentElement.setAttribute('data-bs-theme', 'light'); 184 | } else { 185 | document.documentElement.setAttribute('data-bs-theme', 'dark'); 186 | } 187 | localStorage.setItem('theme', document.documentElement.getAttribute('data-bs-theme')); 188 | localStorage.setItem('switchPosition', themeSwitch.checked); 189 | }); 190 | -------------------------------------------------------------------------------- /src/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | #logo{ 7 | max-width: 40px; 8 | max-height: 40px; 9 | } 10 | 11 | .container{ 12 | max-height: 77.5vh; 13 | overflow-y: auto; 14 | } 15 | 16 | .custom-button-width{ 17 | width: 60px !important; 18 | } 19 | 20 | ::-webkit-scrollbar { 21 | width: 12px; 22 | } 23 | 24 | ::-webkit-scrollbar-track { 25 | background: #ffffff; 26 | border-radius: 10px; 27 | } 28 | 29 | ::-webkit-scrollbar-thumb { 30 | background: #007bffa4; 31 | border-radius: 10px; 32 | } 33 | 34 | ::-webkit-scrollbar-thumb:hover { 35 | background: #007bff; 36 | } 37 | 38 | ::-webkit-scrollbar-corner { 39 | background: #f1f1f1; 40 | } 41 | 42 | @media screen and (max-width: 600px) { 43 | h1{ 44 | margin-bottom: 0.1rem!important; 45 | } 46 | .custom-button-width{ 47 | width: 55px !important; 48 | } 49 | .table{ 50 | text-align: center; 51 | } 52 | th, td { 53 | vertical-align: middle; 54 | } 55 | .container{ 56 | max-height: 75vh; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/static/syncify.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheWicklowWolf/Syncify/43e83e19e2d367d9676c63b331255533a6e19b4c/src/static/syncify.png -------------------------------------------------------------------------------- /src/static/syncify_full_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheWicklowWolf/Syncify/43e83e19e2d367d9676c63b331255533a6e19b4c/src/static/syncify_full_logo.png -------------------------------------------------------------------------------- /src/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 | 13 | 16 | 17 | 20 | 21 | 24 | Syncify 25 | 26 | 27 | 28 |
29 |
30 | 31 |

Syncify

32 | 36 |
37 |
38 | 39 | 40 | 92 | 93 |
94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 |
Playlist NameLast SyncedSongsActions
107 | 108 |
109 |
110 | 111 | 112 | 113 |
114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /thewicklowwolf-init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo -e "\033[1;32mTheWicklowWolf\033[0m" 4 | echo -e "\033[1;34mSyncify\033[0m" 5 | echo "Initializing app..." 6 | 7 | cat << 'EOF' 8 | _____________________________________ 9 | 10 | .-'''''-. 11 | .' `. 12 | : : 13 | : : 14 | : _/| : 15 | : =/_/ : 16 | `._/ | .' 17 | ( / ,|...-' 18 | \_/^\/||__ 19 | _/~ `""~`"` \_ 20 | __/ -'/ `-._ `\_\__ 21 | / /-'` `\ \ \-.\ 22 | _____________________________________ 23 | Brought to you by TheWicklowWolf 24 | _____________________________________ 25 | 26 | If you'd like to buy me a coffee: 27 | https://buymeacoffee.com/thewicklow 28 | 29 | EOF 30 | 31 | echo "-----------------" 32 | echo -e "\033[1mInstalled Versions\033[0m" 33 | # Get the version of yt-dlp 34 | echo -n "yt-dlp: " 35 | pip show yt-dlp | grep Version: | awk '{print $2}' 36 | 37 | # Get the version of ffmpeg 38 | echo -n "FFmpeg: " 39 | ffmpeg -version | head -n 1 | awk '{print $3}' 40 | echo "-----------------" 41 | 42 | PUID=${PUID:-1000} 43 | PGID=${PGID:-1000} 44 | 45 | echo "-----------------" 46 | echo -e "\033[1mRunning with:\033[0m" 47 | echo "PUID=${PUID}" 48 | echo "PGID=${PGID}" 49 | echo "-----------------" 50 | 51 | # Create the required directories with the correct permissions 52 | echo "Setting up directories.." 53 | mkdir -p /syncify/downloads /syncify/config /syncify/cache 54 | chown -R ${PUID}:${PGID} /syncify 55 | 56 | # Set XDG_CACHE_HOME to use the cache directory 57 | export XDG_CACHE_HOME=/syncify/cache 58 | 59 | # Start the application with the specified user permissions 60 | echo "Running Syncify..." 61 | exec su-exec ${PUID}:${PGID} gunicorn src.Syncify:app -c gunicorn_config.py 62 | --------------------------------------------------------------------------------