├── app.ico ├── requirements.txt ├── models ├── ctc_model.onnx └── captcha_model.onnx ├── config.env ├── .github ├── dependabot.yml └── ISSUE_TEMPLATE │ ├── ---------------------------.md │ └── ---------------.md ├── .gitignore ├── README.md ├── LICENSE └── vk-music-import.py /app.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mewforest/vk-music-import/HEAD/app.ico -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mewforest/vk-music-import/HEAD/requirements.txt -------------------------------------------------------------------------------- /models/ctc_model.onnx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mewforest/vk-music-import/HEAD/models/ctc_model.onnx -------------------------------------------------------------------------------- /models/captcha_model.onnx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mewforest/vk-music-import/HEAD/models/captcha_model.onnx -------------------------------------------------------------------------------- /config.env: -------------------------------------------------------------------------------- 1 | VK_TOKEN='' 2 | BYPASS_CAPTCHA='1' 3 | SPOTIFY_MODE='1' 4 | APPLE_MODE='0' 5 | VK_LINKS_MODE='0' 6 | REVERSE='1' 7 | STRICT_SEARCH='0' 8 | ADD_TO_LIBRARY='0' 9 | TIMEOUT_AFTER_ERROR='1' 10 | TIMEOUT_AFTER_CAPTCHA='0' 11 | TIMEOUT_AFTER_SUCCESS='0' 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---------------------------.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Идея для нового функционала 3 | about: Предложите идею для этого проекта 4 | title: "[Новая фича]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Связан ли ваш запрос на функцию с какой-либо проблемой?** 11 | Напишите, в чем заключается проблема. Например, *Я всегда расстраиваюсь, когда необходимо [...]* 12 | 13 | **Опишите решение, которое вы хотели бы получить** 14 | Напишите здесь описание того, что вы хотите, чтобы было добавлено. 15 | 16 | **Опишите альтернативы, которые вы рассматривали** 17 | Напишите здесь описание любых альтернативных решений, которые вы рассмотрели. 18 | 19 | **Дополнительно** 20 | Добавьте сюда любые важные пояснения или скриншоты для запроса (по желанию). 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---------------.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Отчёт об ошибке 3 | about: Создайте отчёт об ошибке 4 | title: "[Проблема]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Опишите проблему** 11 | Добавьте сюда описание ошибки. 12 | 13 | **Как воспроизвести ошибку** 14 | Опишите шаги, которые привели вас к ошибке. 15 | 16 | **Скриншоты** 17 | Если необходимо, добавьте скриншоты, чтобы помочь решить вашу проблему. 18 | 19 | **Технические данные (пожалуйста, заполните следующую информацию):** 20 | - ОС [например, Windows 11] 21 | - Содержимое файла настроек (`.env`) 22 | - Ссылка на плейлист 23 | - Ссылка на профиль ВКонтакте 24 | - Запускали ли вы готовый релиз (или использовали Python)? 25 | - Версия программы [например, 0.1] 26 | 27 | **Дополнительная информация** 28 | Добавьте сюда дополнительные данные, касающийся проблемы. 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | #config.env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | 132 | # Custom 133 | .idea 134 | /отчет.txt 135 | /tracklist.txt 136 | /.gitignore 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vk-music-import 2 | 3 | Программа для переноса плейлистов из Spotify и текстовых треклистов в VK Музыку. 4 | 5 | ![Untitled Diagram drawio-3](https://user-images.githubusercontent.com/15357833/161931217-9c374cf8-749a-4966-b3f5-4e8a85194572.png) 6 | 7 | Преимущества: 8 | 9 | - **Позволяет быстро импортировать плейлисты из Spotify в VK Музыку** 10 | - Импортирует даже неточные по названию треки 11 | - Имеет доступ только к аудиозаписям, данные никуда не "утекают" 12 | - Поддерживает большие плейлисты (более 1000 треков) 13 | - Позволяет импортировать также обычные текстовые списки треков в VK Музыку 14 | - Умеет обходить капчу 15 | 16 | --- 17 | ## Скриншоты 18 | 19 | 20 | 21 | 22 | 23 | ## Как запустить? (для обычных пользователей) 24 | 25 | Инструкция по использованию на Windows: 26 | 27 | - Скачайте и распакуйте 28 | архив ([vk-music-import-vX.X_win32.zip](https://github.com/mewforest/vk-music-import/releases)) 29 | в любую папку 30 | - Запустите исполняемый файл и следуйте инструкциям: 31 | 32 | ![2022-04-08_12h22_59](https://user-images.githubusercontent.com/15357833/167272239-55fc04eb-27c1-40bc-abe9-596390c64459.png) 33 | 34 | **Более подробная инструкция на 35 | DTF:** [Переносим плейлисты из Spotify в VK Музыку (подробное руководство)](https://dtf.ru/u/292194-mew-forest/1152260-perenosim-pleylisty-iz-spotify-v-vk-muzyku-podrobnoe-rukovodstvo) 36 | . 37 | 38 | ## Как запустить? (для продвинутых пользователей) 39 | 40 | 1. Убедитесь, что у вас установлен Python 3.8+. 41 | 2. Установите зависимости: 42 | ``` 43 | pip install -r requirements.txt 44 | ``` 45 | 3. Запустите скрипт и следуйте инструкциям (если некоторые библиотеки не устанавливаются - игнорируйте это, часть библиотек 46 | используется только для компиляции win32 с помощью pyinstaller - об этом в другом разделе): 47 | ``` 48 | python vk-music-import.py 49 | ``` 50 | 4. После переноса треков, скрипт сгенерирует отчет и выведет ссылку на плейлисты с импортированными треками. 51 | 52 | ## Перенос плейлистов из Apple Music 53 | 54 | 1. В приложении Музыка на Mac выберите плейлист в боковом меню, затем выберите «Файл» > «Медиатека» > «Экспортировать плейлист». Выберите формат «Простой Текст». 55 | 2. В файле настроек (`config.env`, лежит в папке с программой) с помощью блокнота выключите режим spotify: `SPOTIFY_MODE="0"` 56 | 3. Аналогично предыдущему шагу включите режим Apple Music: `APPLE_MODE="1"` 57 | 4. Запустите скрипт, поместив экспортированный файл в папку со скриптом (**ВАЖНО**: файл должен называться `tracklist.csv`): 58 | ``` 59 | python vk-music-import.py 60 | ``` 61 | 62 | Важно: данный режим экспериментальный и может не поддерживаться полностью. 63 | 64 | ## Как перенести музыку из других сервисов? 65 | 66 | Чтобы перенести музыку из сторонних сервисов (YouTube, Apple Music, Яндекс Музыка и т.д.), вам необходимо будет экспортировать оттуда треклист (текстовой файл с названиями треков). Это можно сделать с помощью стороннего сервиса [TuneMyMusic](https://www.tunemymusic.com/ru/): 67 | 68 | 1. Перейдите на сайт [TuneMyMusic](https://www.tunemymusic.com/ru/) и нажмите кнопку «Давайте приступим». 69 | 2. Выберите сервис, из которого вы хотите перенести музыку, и авторизуйтесь в нем. 70 | 3. Выберите плейлист для переноса, нажав кнопку «Загрузить из вашей учетной записи». 71 | 4. На странице «Выберите целевую платформу» нажмите кнопку «Файл» и скачайте его в формате .txt. 72 | 5. Нажмите «Начать перенос музыки». 73 | 6. Сохраните файл на свой компьютер, а затем переместите его в папку с данной программой и переименуйте в `tracklist.txt`. 74 | 7. В файле настроек (`config.env`, лежит в папке с программой) с помощью блокнота выключите режим spotify: `SPOTIFY_MODE="0"` 75 | 8. Готово, запускайте скрипт! 76 | 77 | *Инструкция частично заимствована [отсюда](https://zvuk.com/lp/howto)*. 78 | 79 | ### Альтернативы 80 | 81 | - Яндекс Музыка: [расширение для Google Chrome](https://chrome.google.com/webstore/detail/yamutools-%D0%BD%D0%BE%D0%B2%D1%8B%D0%B5-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8-%D0%B4/dgjneghdfaeajjemeklgmbojeeplehah) (могут быть неточности из-за формата экспорта [#5](https://github.com/mewforest/vk-music-import/issues/5)). 82 | - YouTube Музыка: сервис [yt.spotya.ru](https://yt.spotya.ru/). 83 | - Apple Music, Deezer, Amazon и другие: вместо [TuneMyMusic](https://www.tunemymusic.com/ru/) можете воспользоваться конкурентом - [Soundiiz](https://soundiiz.com/). 84 | 85 | ## Как создать плейлист из ссылок на треки во Вконтакте 86 | 87 | На любой трек во ВКонтакте можно получить прямую ссылку, если вы создадите список таких ссылок, то их также можно будет добавить в плейлист 88 | с помощью данной утилиты. Это может быть полезно, если вы создаете плейлисты в стороннем приложении для прослушивания музыки, 89 | например, в AIMP с использованием плагина [VK Plugin](https://www.aimp.ru/forum/index.php?topic=64170.0). 90 | 91 | Чтобы перейти в режим импорта из списка ссылок, в `config.env` отключите режим Spotify: `SPOTIFY_MODE="0"` и включите 92 | режим `VK_LINKS_MODE="1"`. Теперь скрипт будет добавлять треки по ссылкам из файла `tracklist.txt` минуя поиск. Вот как 93 | должен выглядеть этот список: 94 | 95 | ``` 96 | https://vk.com/audio570484580_456249918_30a6c863d7cb56d834 97 | https://vk.com/audio570484580_456245588_3c170a3340106a374a 98 | https://vk.com/audio570484580_456245614_4bb21fb36173e3c61b 99 | https://vk.com/audio570484580_456254608_7784e1bddd07c3289f 100 | ``` 101 | 102 | ### Как получить список ссылок на музыку в AIMP-е 103 | 104 | 1. Установить [VK Plugin](https://www.aimp.ru/forum/index.php?topic=64170.0) в AIMP 105 | 2. Правой кнопкой мыши по списку треков "Экспорт треклиста" 106 | 3. Появится окошко с настройками экспорта, в поле "Форматная строка" написать `%Link` и кликнуть "ОК" 107 | 4. Готово! Треклист можно сохранять как `tracklist.txt`, предварительно удалив из него лишние строки в самом начале файла. 108 | 109 | ## Настройки 110 | 111 | ## Описание настроек 112 | 113 | | Параметр | Описание | Значение по умолчанию | 114 | |-------------------------|------------------------------------------------------------------------------------------------------------|-----------------------| 115 | | `VK_TOKEN` | Токен для доступа к VK API** | `""` | 116 | | `BYPASS_CAPTCHA` | Включить обход капчи автоматически (если отключить, будет предложено вводить капчу каждый раз вручную) | `1` | 117 | | `SPOTIFY_MODE` | Включить режим импорта из Spotify | `1` | 118 | | `APPLE_MODE` | Включить режим импорта из Apple Music | `0` | 119 | | `VK_LINKS_MODE` | Включить режим импорта из списка ссылок на треки во Вконтакте (ссылки должны быть в файле `tracklist.txt`) | `0` | 120 | | `REVERSE` | Добавлять треки в обратном порядке (от новых к старым) | `1` | 121 | | `STRICT_SEARCH` | Искать только точные совпадения по исполнителю | `0` | 122 | | `ADD_TO_LIBRARY` | Добавлять треки в мои аудиозаписи | `0` | 123 | | `ADD_TO_GROUP_ID` | Добавлять треки в сообщество с указанным ID. Если пусто, то опция выключена. | `` | 124 | | `TIMEOUT_AFTER_ERROR` | Задержка после ошибки (в секундах)* | `10` | 125 | | `TIMEOUT_AFTER_CAPTCHA` | Задержка после капчи (в секундах)* | `30` | 126 | | `TIMEOUT_AFTER_SUCCESS` | Задержка после успешного импорта (в секундах)* | `1` | 127 | 128 | *Только для beta-версии. 129 | ** Ссылка для получения токена [здесь](https://oauth.vk.com/oauth/authorize?client_id=6121396&scope=audio,offline&redirect_uri=https://oauth.vk.com/blank.html&display=page&response_type=token&revoke=1&slogin_h=23a7bd142d757e24f9.93b0910a902d50e507&__q_hash=fed6a6c326a5673ad33facaf442b3991 130 | ). 131 | 132 | 133 | ### Добавление в мои аудиозаписи 134 | 135 | По-умолчанию треки переносятся в плейлист без добавления в раздел "мои аудиозаписи". Чтобы включить добавление музыки в свою 136 | медиатеку ВКонтакте, в `config.env` включите соответственный пункт: `ADD_TO_LIBRARY="1"`. 137 | 138 | **Используйте с осторожностью:** ВКонтакте не проверяет трек на наличие в аудиозаписях, так что при импорте возможны дубликаты. 139 | 140 | ### Импорт музыки из треклиста 141 | 142 | По-умолчанию включен импорт треков из плейлиста Spotify, чтобы перейти в режим импорта из треклиста, в `config.env` 143 | отключите режим Spotify: `SPOTIFY_MODE="0"`. Теперь скрипт будет искать треки из файла `tracklist.txt` (его нужно 144 | создать самостоятельно в папке со скриптом), который должен содержать список треков, разделенных переносом, например: 145 | 146 | ``` 147 | Khalid - Better 148 | Billie Eilish - i love you 149 | ``` 150 | 151 | > Если дефисы не проставлены, скрипт проставит их автоматически после первого слова. 152 | 153 | ### Треки в обратном порядке 154 | 155 | По-умолчанию все плейлисты добавляются в обратном порядке (от новых к старым). Чтобы это отключить, в `config.env` 156 | отключите режим обратного порядка: `REVERSE="0"`. 157 | 158 | ### Строгий поиск 159 | 160 | По-умолчанию скрипт ищет неточные совпадения для треков и также их переносит, побочный эффект этого: в вашу медиатеку 161 | могут попасть ремиксы и bassboosted-версии. Чтобы разрешить перенос только точных совпадений по исполнителю, 162 | в `config.env` включите строгий режим: `STRICT_SEARCH="1"`. 163 | 164 | ### Добавление в сообщество (группу) 165 | 166 | Чтобы добавить треки в сообщество (группу), вы должны быть её администратором. В `config.env` добавьте строчку: 167 | `ADD_TO_GROUP_ID="123456789"`. Вместо`123456789` укажите ID сообщества ([как узнать id группы в VK](https://vk.com/faq18062)), 168 | в которое вы хотите добавить треки. 169 | 170 | ## Возможные проблемы и их решения 171 | 172 | ### Обход капчи не работает на macOS на M1 173 | 174 | Это происходит из-за проблем с установкой onnx-runtime. 175 | 176 | - **Решение 1**: запустите скрипт через Python x64 с помощью Rosetta. 177 | - **Решение 2**: отключить распознавание капчи и вводить ответы вручную. Для этого закомментируйте строчку 178 | импорта `import onnxruntime as rt` в `vk-music-import.py` (можете удалить строчки, где эта библиотека используется) и выключите распознавание капчи в 179 | файле `config.env`: `BYPASS_CAPTCHA="0"`. 180 | 181 | 182 | ### Не работает обход капчи 183 | 184 | - Увеличьте значение `CAPTCHA_TIMEOUT` в `config.env` (по-умолчанию 30 секунд)*. 185 | - Отключите автоматический обход капчи в `config.env`: `BYPASS_CAPTCHA="0"` и вводите ответы вручную. 186 | - Повторите попытку через некоторое время, возможно ВКонтакте временно заблокировал ваш аккаунт. 187 | 188 | ### Слетела конфигурация по умолчанию 189 | 190 | Все настройки хранятся в файле `config.env`, если он был удален или повредился, то его можно восстановить вручную, вставив настройки по умолчанию из [файла в репозитории](https://github.com/mewforest/vk-music-import/blob/main/config.env). 191 | 192 | 193 | ## Компиляция программы 194 | 195 | Вы можете скомпилировать данную утилиту самостоятельно, в том числе для своей операционной системы (в инструкции пример 196 | для Windows). 197 | 198 | - Создайте виртуальное окружение и установите зависимости и Pyinstaller: 199 | ```shell 200 | python -m virtualenv venv 201 | venv\Scripts\activate 202 | pip install -r requirements.txt 203 | pip install pyinstaller 204 | ``` 205 | - Запустите компиляцию (да, это больно): 206 | ```shell 207 | pyinstaller --onefile --icon=app.ico --add-binary="venv\Lib\site-packages\onnxruntime\capi\onnxruntime_providers_shared.dll;.\onnxruntime\capi" --windowed --hidden-import=PySide2 --hidden-import=tkinter .\vk-music-import.py 208 | ``` 209 | - Скопируйте в папку `dist` файл с моделями капчи (`models`) и файл конфигурации (`config.env`): 210 | ```shell 211 | cp -r .\models\ .\dist\models 212 | cp .\config.env .\dist 213 | ``` 214 | 215 | ## Поддержка пользователей 216 | 217 | - **[Оставить запрос на фичу или сообщить о баге](https://github.com/mewforest/vk-music-import/issues/new/choose)** 218 | - [Поблагодарить разработчика](https://mewforest.github.io/donate/) 219 | 220 | ## Полезный материал 221 | 222 | - [Айти заметки](https://t.me/mewnotes) - телеграм-канал автора сервиса. 223 | - [Spotya](https://spotya.ru/) - сервис для переноса музыки из Spotify в Яндекс Музыку, некоторые метаданные о 224 | плейлистах я собираю с его API. 225 | - [vkCaptchaBreaker](https://github.com/Defasium/vkCaptchaBreaker/) - модель для решения капчи ВК взята из данного 226 | репозитория 227 | - [VK API Reference](https://vodka2.github.io/vk-audio-token/) - описание методов VK API для доступа к аудиозаписям. 228 | 229 | ## Альтернативные решения 230 | 231 | - [Официальный сервис "Перенос Музыки"](https://vk.com/app8116845) - Умеет переносить пользовательскую библиотеку из резервных копий Spotify 232 | 233 | ## Условия пользования 234 | 235 | Автор не несет ответственности за любые действия, которые предпринимаете с данным ПО, вы делаете всё на свой страх и 236 | риск. Учитывайте, что данный метод импортирования музыки не является официальным, но банов за его использования пока не 237 | было. 238 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /vk-music-import.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imports music to VK Music from Track list. 3 | 4 | AUTH: 5 | https://oauth.vk.com/oauth/authorize?client_id=6121396&scope=8&redirect_uri=https://oauth.vk.com/blank.html&display=page&response_type=token&revoke=1&slogin_h=23a7bd142d757e24f9.93b0910a902d50e507&__q_hash=fed6a6c326a5673ad33facaf442b3991 6 | 7 | """ 8 | import csv 9 | import json 10 | import logging 11 | import os 12 | import platform 13 | import re 14 | import sys 15 | import webbrowser 16 | from datetime import datetime 17 | from io import BytesIO 18 | from logging.handlers import RotatingFileHandler 19 | from time import sleep 20 | from types import SimpleNamespace 21 | from urllib.parse import urlparse, parse_qs 22 | import requests 23 | import vk_api 24 | import numpy as np 25 | import onnxruntime as rt 26 | from PySide2.QtGui import QPixmap, QClipboard, QDesktopServices 27 | from dotenv import load_dotenv, set_key 28 | from vk_api import Captcha 29 | from typing import Union, Optional, List 30 | from PIL import Image, ImageTk 31 | import qdarktheme 32 | from PySide2.QtWidgets import QApplication, QWidget, QTabWidget, QVBoxLayout, QFormLayout, QCheckBox, QLineEdit, \ 33 | QProgressBar, QTextEdit, QPushButton, QDialog, QLabel, QHBoxLayout, QRadioButton, QMessageBox, QInputDialog, \ 34 | QFileDialog 35 | from PySide2.QtCore import Qt, QUrl 36 | from PySide2.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QApplication 37 | from PySide2.QtGui import QPixmap, QImage 38 | from PySide2.QtCore import Qt 39 | 40 | 41 | # from curl_cffi import requests 42 | # from bs4 import BeautifulSoup 43 | # from fuzzywuzzy import fuzz 44 | 45 | def fix_relative_path(relative_path: str) -> str: 46 | """ 47 | Фикс относительных путей PyInstaller 48 | """ 49 | application_path = '' 50 | if getattr(sys, 'frozen', False): 51 | application_path = os.path.dirname(os.path.abspath(sys.executable)) 52 | elif __file__: 53 | application_path = os.path.dirname(os.path.abspath(__file__)) 54 | return os.path.abspath(os.path.join(application_path, relative_path)) 55 | 56 | 57 | # Class for envs syncing (config.env) 58 | class MainEnv: 59 | def __init__(self): 60 | self.env = SimpleNamespace() 61 | self.load_env_config() 62 | 63 | def load_env_config(self): 64 | self.env = SimpleNamespace() 65 | 66 | load_dotenv(config_path, override=True) 67 | 68 | self.env.BYPASS_CAPTCHA = os.getenv("BYPASS_CAPTCHA", "0") == "1" 69 | self.env.VK_TOKEN = os.getenv("VK_TOKEN") 70 | self.env.SPOTIFY_MODE = os.getenv("SPOTIFY_MODE", "0") == "1" 71 | self.env.APPLE_MODE = os.getenv("APPLE_MODE", "0") == "1" 72 | self.env.VK_LINKS_MODE = os.getenv("VK_LINKS_MODE", "0") == "1" 73 | self.env.REVERSE = os.getenv("REVERSE", "0") == "1" 74 | self.env.STRICT_SEARCH = os.getenv("STRICT_SEARCH", "0") == "1" 75 | self.env.ADD_TO_LIBRARY = os.getenv("ADD_TO_LIBRARY", "0") == "1" 76 | self.env.ADD_TO_GROUP_ID = os.getenv("ADD_TO_GROUP_ID", "") 77 | # self.env.UPDATE_PLAYLIST = os.getenv("UPDATE_PLAYLIST", "0") == "1" 78 | self.env.TIMEOUT_AFTER_ERROR = int(os.getenv("TIMEOUT_AFTER_ERROR", "10")) 79 | self.env.TIMEOUT_AFTER_CAPTCHA = int(os.getenv("TIMEOUT_AFTER_CAPTCHA", "10")) 80 | self.env.TIMEOUT_AFTER_SUCCESS = int(os.getenv("TIMEOUT_AFTER_SUCCESS", "10")) 81 | 82 | 83 | # Creating a class for the main window 84 | class MainWindow(QWidget): 85 | def __init__(self): 86 | super().__init__() 87 | # Setting the window title and size 88 | self.setWindowTitle("VK Music Import (v1.1 beta)") 89 | self.resize(600, 300) 90 | # Creating a tab widget 91 | self.tab_widget = QTabWidget() 92 | # Creating two tabs 93 | self.main_tab = MainTab() 94 | self.settings_tab = SettingsTab() 95 | # Adding the tabs to the tab widget 96 | self.tab_widget.addTab(self.main_tab, "Главная") 97 | self.tab_widget.addTab(self.settings_tab, "Настройки") 98 | # Creating a layout for the window 99 | self.layout = QVBoxLayout() 100 | # Adding the tab widget to the layout 101 | self.layout.addWidget(self.tab_widget) 102 | # Setting the layout for the window 103 | self.setLayout(self.layout) 104 | 105 | 106 | # Creating a class for the main tab 107 | class MainTab(QWidget, MainEnv): 108 | def __init__(self): 109 | # Call both parents constructors 110 | QWidget.__init__(self) 111 | MainEnv.__init__(self) 112 | # Environment variables 113 | self.env = SimpleNamespace() 114 | # Creating buttons (start, pause, stop) 115 | self.start_button = QPushButton("Начать импорт") 116 | self.start_button.setStyleSheet("QPushButton {font-weight: bold; height: 24px}") 117 | # Connecting the buttons to their functions 118 | self.start_button.clicked.connect(self.start) 119 | # Creating a progress bar 120 | self.progress_bar = QProgressBar() 121 | # Setting the initial value and range of the progress bar 122 | self.progress_bar.setValue(0) 123 | self.progress_bar.setRange(0, 100) 124 | # Creating a text edit 125 | self.text_edit = QTextEdit() 126 | # Setting the text edit to read only 127 | self.text_edit.setReadOnly(True) 128 | # Creating a layout for the tab 129 | self.layout = QVBoxLayout() 130 | # Adding the buttons to the layout 131 | self.layout.addWidget(self.start_button) 132 | # Adding the progress bar and the text edit to the layout 133 | self.layout.addWidget(self.progress_bar) 134 | self.layout.addWidget(self.text_edit) 135 | # Setting the layout for the tab 136 | self.setLayout(self.layout) 137 | # Main 138 | self.is_running = False 139 | self.is_under_ban = False 140 | self.ok_tracks = None 141 | self.questionable_tracks = None 142 | self.playlist_response = None 143 | 144 | def update_progress_bar(self, value: int): 145 | """ 146 | Обновляет прогресс бар 147 | """ 148 | self.progress_bar.setValue(value) 149 | QApplication.processEvents() 150 | 151 | def add_log(self, text: str, level: str = 'INFO'): 152 | """ 153 | Добавляет текст в лог 154 | """ 155 | self.text_edit.append(text) 156 | if level == 'INFO': 157 | logging.info(text) 158 | else: 159 | logging.warning(text) 160 | QApplication.processEvents() 161 | 162 | def show_input_dialog(self, title: str, text: str, default_text: str = "") -> str: 163 | """ 164 | Показывает диалог ввода текста 165 | """ 166 | text, ok = QInputDialog.getText(self, title, text, QLineEdit.Normal, default_text) 167 | if ok: 168 | return text 169 | else: 170 | return None 171 | 172 | # Defining a function that starts the import process 173 | def start(self): 174 | self.load_env_config() 175 | 176 | if self.is_running: 177 | # Ask user is he sure to stop 178 | reply = QMessageBox.question(self, 'Подтверждение', 'Вы уверены, что хотите остановить импорт?', 179 | QMessageBox.Yes | QMessageBox.No, QMessageBox.No) 180 | if reply == QMessageBox.Yes: 181 | self.stop_import() 182 | self.add_log("Останавливается пользователем...") 183 | 184 | return 185 | 186 | # Rename the start button to pause 187 | self.is_running = True 188 | self.start_button.setText("Стоп") 189 | 190 | # VK Authentication 191 | self.add_log("Авторизуюсь в ВКонтакте...") 192 | if self.env.VK_TOKEN is None: 193 | self.add_log("Не обнаружен токен VK API в config_path файле, запрашиваю авторизацию вручную...") 194 | self.get_token() 195 | vk_session = vk_api.VkApi(token=self.env.VK_TOKEN, 196 | captcha_handler=lambda captcha: self.captcha_handler(captcha)) 197 | vk = vk_session.get_api() 198 | tracklist = [] 199 | try: 200 | user_info = vk.users.get()[0] 201 | except vk_api.exceptions.ApiError as e: 202 | self.add_log(f"Кажется, ваш токен устарел, необходимо заново авторизоваться (ошибка: {e})") 203 | self.stop_import() 204 | 205 | # Show info dialog with suggestion to go to settings and update token, only with OK button 206 | reply = QMessageBox.information(self, 'Токен устарел', 207 | 'Кажется, ваш токен устарел, необходимо войти в VK.\n\n' 208 | 'Перейдите в настройки и нажмите "Авторизоваться".', 209 | QMessageBox.Ok, QMessageBox.Ok) 210 | 211 | # Show info dialog with suggestion to go to settings and update token 212 | # reply = QMessageBox.question(self, 'Токен устарел', 213 | # 'Кажется, ваш токен устарел, необходимо заново авторизоваться.\n' 214 | # 'Перейти в настройки?', 215 | # QMessageBox.Yes | QMessageBox.No, QMessageBox.No) 216 | # if reply == QMessageBox.Yes: 217 | # self.tab_widget.setCurrentIndex(1) 218 | return 219 | 220 | # self.get_token() 221 | # user_info = vk.users.get()[0] 222 | # self.add_log("Токен в файле config_path успешно сброшен") 223 | title_playlist = f"Импортированная музыка от {datetime.now().strftime('%d.%m.%Y %H:%M')}" 224 | report_filename = f"Отчет об импорте за {datetime.now().strftime('%d.%m.%Y %H-%M')}.txt" 225 | playlist_img = None 226 | self.add_log(f"Авторизовался как {user_info['first_name']} {user_info['last_name']} (id: {user_info['id']})") 227 | 228 | # Getting Spotify playlist 229 | use_audio_links = False 230 | if self.env.SPOTIFY_MODE: 231 | while True: 232 | spotify_playlist_url = self.show_input_dialog('Ссылка на Spotify', 233 | 'Вставь сюда ссылку на плейлист в Spotify') 234 | if spotify_playlist_url is None: 235 | self.stop_import() 236 | self.add_log("Отменено пользователем...") 237 | return 238 | spotify_playlist_url = spotify_playlist_url.strip() 239 | # Use better input dialog in pyside2 (QInputDialog) 240 | tracklist_response = requests.post('https://spotya.ru/data.php', json={ 241 | "url": f"https://spotya.ru/api.php?playlist={spotify_playlist_url}", 242 | "type": "playlist" 243 | }) 244 | tracklist_text = tracklist_response.text.replace('\ufeff', '') 245 | if len(tracklist_text) != 0: 246 | break 247 | self.add_log("Не сумел прочитать треки из плейлиста. У тебя точно открытый плейлист?") 248 | self.add_log(f"Нашел {tracklist_text.count(' ') + 1} треков в плейлисте") 249 | tracklist_content = tracklist_text.replace(' ', '\n').strip() 250 | self.add_log("Сохраняю в tracklist.txt...") 251 | with open("tracklist.txt", "w", encoding="utf-8") as f: 252 | f.write(tracklist_content) 253 | playlist_info_response = requests.post('https://spotya.ru/data.php', json={ 254 | "url": f"https://spotya.ru/api.php?playlist={spotify_playlist_url}", 255 | "type": "poster" 256 | }) 257 | self.add_log("Загружаю метаданные...") 258 | try: 259 | playlist_info = json.loads(playlist_info_response.text.replace('\ufeff', '')) 260 | except json.JSONDecodeError as e: 261 | self.add_log(f"Не сумел загрузить метаданные из плейлиста ({e}). Пропускаю этот этап...") 262 | else: 263 | title_playlist = playlist_info["name"] 264 | playlist_img = playlist_info["image"] 265 | self.add_log(f"Получил метаданные для плейлиста \"{playlist_info['name']}\"") 266 | elif self.env.APPLE_MODE: 267 | self.add_log('Начинаю импорт из Apple Music...') 268 | self.add_log('Важно: данный функционал находится в бета-тестировании и может работать некорректно.') 269 | try: 270 | with open(fix_relative_path('tracklist.csv'), newline='', encoding='utf-8') as csvfile: 271 | reader = csv.DictReader(csvfile, dialect='excel-tab') 272 | tracks = open(fix_relative_path('export-tracklist.txt'), 'w', encoding="utf-8") 273 | for row in reader: 274 | tracks.write(row['Артист'] + ' - ' + row['Название'] + '\n') 275 | tracks.close() 276 | except FileNotFoundError: 277 | self.add_log("Не найден плейлист. Нужно указать корректный путь до файла <имя плейлиста>.txt") 278 | return 279 | elif self.env.VK_LINKS_MODE: 280 | use_audio_links = True 281 | 282 | # Open tracklist 283 | self.add_log("Загружаю треклист...") 284 | try: 285 | try: 286 | with open("tracklist.txt", "r", encoding="utf-8") as f: 287 | text_lines = f.readlines() 288 | except UnicodeDecodeError: 289 | with open("tracklist.txt", "r", encoding="cp1251") as f: 290 | text_lines = f.readlines() 291 | except FileNotFoundError: 292 | self.add_log("Не найден треклист (tracklist.txt). Вы не забыли его предварительно создать?") 293 | return 294 | if use_audio_links: 295 | for text_line in text_lines: 296 | parsed_row = re.match(r"^https://vk\.com/audio(-?\d+)_(\d+)(?:_([a-z0-9]+))?", text_line) 297 | if parsed_row is not None and len(parsed_row.groups()) == 3: 298 | tracklist.append(parsed_row.groups()) 299 | else: 300 | for text_line in text_lines: 301 | parsed_row = re.match(r"^([^-—]+)[-—]([^\r\n]+)", text_line) 302 | if parsed_row is not None: 303 | tracklist.append((parsed_row.group(1).strip(), parsed_row.group(2).strip())) 304 | continue 305 | parsed_row = re.match(r"^(\S+)\s(.+)", text_line) 306 | if parsed_row is not None: 307 | track_info = (parsed_row.group(1).strip(), parsed_row.group(2).strip(),) 308 | tracklist.append(track_info) 309 | self.add_log( 310 | f"В строчке треклиста нет дефиса, разделил вручную: {track_info[0]} - {track_info[1]}") 311 | 312 | # Search and add tracks 313 | if self.env.REVERSE: 314 | tracklist.reverse() 315 | self.add_log( 316 | f"Буду {'добавлять' if use_audio_links else 'искать'} {len(tracklist)} из {len(text_lines)} треков...") 317 | 318 | is_continue = False 319 | if os.path.exists(fix_relative_path("progress.json")): 320 | # Ask user to continue from last progress 321 | reply = QMessageBox.question(self, 'Подтверждение', 322 | 'Найден файл с прошлого незаконченного переноса, продолжить с него?\n' 323 | 'Важно: треклист должен быть тот же самый, иначе возможны ошибки.', 324 | QMessageBox.Yes | QMessageBox.No, QMessageBox.No) 325 | if reply == QMessageBox.Yes: 326 | with open(fix_relative_path("progress.json"), "r", encoding="utf-8") as f: 327 | progress = json.load(f) 328 | self.ok_tracks = progress['ok_tracks'] 329 | self.questionable_tracks = progress['questionable_tracks'] 330 | self.playlist_response = progress['playlist_response'] 331 | is_continue = True 332 | self.add_log(f"Продолжаю с {len(self.ok_tracks) + len(self.questionable_tracks)} трека...") 333 | # self.update_progress_bar( 334 | # int((len(self.ok_tracks) + len(self.questionable_tracks)) / len(tracklist) * 100)) 335 | 336 | # Удаляем треки из tracklist, которые уже добавлены 337 | for track in self.ok_tracks + self.questionable_tracks: 338 | if (track[0], track[1]) in tracklist: 339 | tracklist.remove((track[0], track[1])) 340 | else: 341 | os.remove(fix_relative_path("progress.json")) 342 | self.add_log("Начинаю сначала...") 343 | 344 | # if self.env.UPDATE_PLAYLIST: 345 | # # Ask user to input link to existing VK playlist 346 | # playlist_url = self.show_input_dialog('Ссылка на плейлист', 347 | # 'Вставьте ссылку на существующий плейлист в VK, чтобы обновить его.') 348 | # if playlist_url is None: 349 | # self.stop_import() 350 | # self.add_log("Отменено пользователем...") 351 | # return 352 | # playlist_url = playlist_url.strip() 353 | # parsed_url = urlparse(playlist_url) 354 | # if parsed_url.scheme != 'https' or \ 355 | # parsed_url.netloc != 'vk.com' or \ 356 | # not (parsed_url.path.startswith('/audios') or parsed_url.path.startswith('/music')): 357 | # self.add_log("Некорректная ссылка на плейлист, пропускаю этот этап...") 358 | # else: 359 | # playlist_id = '' 360 | # # https://vk.com/audios95755136?section=all&z=audio_playlist95755136_77191690 -> 77191690 361 | # if parsed_url.path.startswith('/audios'): 362 | # playlist_id = parse_qs(parsed_url.query)['z'][0].split('_')[-1] 363 | # # https://vk.com/music/playlist/95755136_77191690_501288fa2e11eed984 -> 77191690 364 | # elif parsed_url.path.startswith('/music'): 365 | # playlist_id = parsed_url.path.split('/')[-1].split('_')[1] 366 | # 367 | # try: 368 | # assert playlist_id.isdigit(), "Некорректная ссылка на плейлист (id not int), пропускаю этот этап..." 369 | # self.playlist_response = vk_session.method("audio.getPlaylistById", { 370 | # "owner_id": user_info['id'], 371 | # "playlist_id": int(playlist_id), 372 | # }) 373 | # except (vk_api.VkApiError, AssertionError) as e: 374 | # self.add_log( 375 | # f"Не получается получить информацию о плейлисте, ошибка: \"{e}\". Останавливаю импорт...") 376 | # self.stop_import() 377 | # else: 378 | # self.add_log(f"Получил базовую информацию о плейлисте \"{self.playlist_response['title']}\"") 379 | # title_playlist = self.playlist_response['title'] 380 | # count = self.playlist_response['count'] 381 | # # playlist_img = self.playlist_response['photo']['photo_600'] 382 | # is_continue = True 383 | # 384 | # # Getting playlist tracks by HTML parsing 385 | # parsed_tracklist = [] 386 | # try: 387 | # raw_response = requests.get(f"https://m.vk.com/music/playlist/{user_info['id']}_{playlist_id}", impersonate="chrome101") 388 | # soup = BeautifulSoup(raw_response.text, 'lxml') 389 | # for track in soup.find_all('div', {'class': 'audio_row__inner'}): 390 | # artist = track.find('div', {'class': 'audio_row__performers'}).text 391 | # title = track.find('div', {'class': 'audio_row__title_inner'}).text 392 | # parsed_tracklist.append((artist, title,)) 393 | # except Exception as e: 394 | # self.add_log(f"Не получается получить содержимое плейлиста в VK (он точно публичный?), ошибка: \"{e}\".\n" 395 | # f"Возможно, метод парсинга устарел. Останавливаю импорт...") 396 | # self.stop_import() 397 | # 398 | # if len(parsed_tracklist) != count: 399 | # self.add_log(f"Количество спарсенных треков в плейлисте не совпадает с данными VK API ({len(parsed_tracklist)} != {count}). Останавливаю импорт...") 400 | # self.stop_import() 401 | # 402 | # # Удаляем треки из tracklist, которые уже добавлены до последнего трека в плейлисте (parsed_tracklist) 403 | # last_track = parsed_tracklist[-1] 404 | # for i, track in enumerate(tracklist): 405 | # if fuzz.ratio(track[0], last_track[0]) > 80 and fuzz.ratio(track[1], last_track[1]) > 80: 406 | # self.add_log(f"Нашел последний добавленный трек в плейлисте: \"{track[0]} - {track[1]}\" (номер {i + 1} в импортируемом треклисте)") 407 | # tracklist = tracklist[i + 1:] 408 | # break 409 | 410 | if not is_continue: 411 | self.ok_tracks = [] 412 | self.questionable_tracks = [] 413 | failed_tracks = [] 414 | added_count = 0 415 | chucked_rows = list(chunks(tracklist, 1000)) 416 | playlists = [] 417 | for k, chunk_row in enumerate(chucked_rows, 1): 418 | self.add_log("Создаем плейлист для добавления музыки...") 419 | if len(chucked_rows) > 1: 420 | title_playlist = f'[{k}/{len(chucked_rows)}] {title_playlist}' 421 | if not is_continue: 422 | try: 423 | self.playlist_response = vk_session.method("audio.createPlaylist", { 424 | "owner_id": user_info['id'], 425 | "title": title_playlist 426 | }) 427 | except vk_api.VkApiError as e: 428 | self.add_log( 429 | f"Не получается создать плейлист, ошибка: \"{e}\".Попробуйте еще раз позже или обновите токен.") 430 | self.stop_import() 431 | return 432 | is_continue = False 433 | playlists.append(f"https://vk.com/audios{user_info['id']}?" 434 | f"section=all&z=audio_playlist{user_info['id']}_{self.playlist_response['id']}") 435 | if 'id' not in self.playlist_response: 436 | raise PermissionError( 437 | f"VK не позволяет создать плейлист, повторите позже. Доп. информация: {self.playlist_response}") 438 | for i, track_row in enumerate(chunk_row, 1): 439 | if not use_audio_links: 440 | artist, title = track_row 441 | if self.is_running is False: 442 | return 443 | self.add_log(f"Ищу трек \"{title}\" от исполнителя {artist} ({i} из {len(tracklist)})...") 444 | self.update_progress_bar(int(i / len(tracklist) * 100)) 445 | try: 446 | response = vk_session.method("audio.search", {"q": f"{artist} - {title}", "count": 3}) 447 | except vk_api.VkApiError as e: 448 | self.add_log(f"Не получить трек, ошибка: \"{e}\". Жду 10 секунд (программа может зависнуть)...") 449 | sleep(self.env.TIMEOUT_AFTER_ERROR) 450 | if self.is_running: 451 | try: 452 | response = vk_session.method("audio.search", {"q": f"{artist} - {title}", "count": 3}) 453 | except vk_api.VkApiError as e: 454 | self.add_log( 455 | f"Не могу найти трек повторно, ошибка: \"{e}\". Пропускаю трек...") 456 | failed_tracks.append(track_row) 457 | if 'items' not in response: 458 | raise PermissionError( 459 | f"VK временно заблокировал доступ к API, повторите позже. Доп. информация: {response}") 460 | if len(response['items']) == 0: 461 | failed_tracks.append(track_row) 462 | self.add_log(f"Трек не найден в VK Музыке (исполнитель: {artist}, трек: {title})") 463 | continue 464 | full_matched = None 465 | for item in response['items']: 466 | if item['artist'].lower() == artist.lower() and title.lower() == item['title'].lower(): 467 | full_matched = item 468 | break 469 | if full_matched is not None: 470 | self.ok_tracks.append(track_row) 471 | track_info = full_matched 472 | self.add_log(f"Успешно нашел трек \"{title}\" от исполнителя {artist}") 473 | elif self.env.STRICT_SEARCH: 474 | failed_tracks.append(track_row) 475 | self.add_log( 476 | f"Точного совпадения не найдено, пропускаю трек (исполнитель: {artist}, трек: {title})") 477 | continue 478 | else: 479 | partially_matched = response['items'][0] 480 | track_info = partially_matched 481 | self.questionable_tracks.append( 482 | track_row + (partially_matched['artist'], partially_matched['title'],)) 483 | self.add_log(f"Нашел похожий трек: \"{artist} - {title}\" → \"{partially_matched['artist']} - " 484 | f"{partially_matched['title']}\"") 485 | self.add_log( 486 | f"Добавляю \"{track_info['artist']} - {track_info['title']}\" (id: {track_info['id']}) в плейлист...") 487 | else: 488 | owner_id, track_id, access_key = track_row 489 | track_info = { 490 | 'owner_id': owner_id, 491 | 'id': track_id, 492 | 'access_key': access_key, 493 | 'title': '', 494 | 'artist': '', 495 | } 496 | audio_ids = f"{track_info['owner_id']}_{track_info['id']}" 497 | if use_audio_links and track_info['access_key'] is not None: 498 | audio_ids += f"_{track_info['access_key']}" 499 | try: 500 | add_to_playlist_response = vk_session.method("audio.addToPlaylist", { 501 | "owner_id": user_info['id'], 502 | "playlist_id": self.playlist_response['id'], 503 | "audio_ids": audio_ids, 504 | }) 505 | except vk_api.VkApiError as e: 506 | self.add_log( 507 | f"Не получается добавить трек в плейлист, ошибка: \"{e}\". Жду 10 секунд (программа может зависнуть)...") 508 | sleep(self.env.TIMEOUT_AFTER_ERROR) 509 | delayed_response = None 510 | try: 511 | delayed_response = vk_session.method("audio.addToPlaylist", { 512 | "owner_id": user_info['id'], 513 | "playlist_id": self.playlist_response['id'], 514 | "audio_ids": track_info['id'], 515 | }) 516 | except vk_api.VkApiError as e: 517 | self.add_log( 518 | f"Не получается повторно добавить трек в плейлист \"{e}\". Если ошибка повторится, " 519 | f"перезапустите скрипт спустя некоторое время ({delayed_response}).") 520 | else: 521 | if len(add_to_playlist_response) == 0: 522 | self.add_log(f"Ошибка добавления в плейлист: возвращен пустой ответ, возможно, " 523 | f"у вас нет прав на добавление трека (id: {track_info['id']})") 524 | continue 525 | if self.env.ADD_TO_LIBRARY: 526 | self.add_log( 527 | f"Добавляю \"{track_info['artist']} - {track_info['title']}\" (id: {track_info['id']}) в мои аудиозаписи...") 528 | add_params = { 529 | 'audio_id': track_info['id'], 530 | 'owner_id': track_info['owner_id'] 531 | } 532 | if use_audio_links and track_info['access_key'] is not None: 533 | add_params['access_key'] = track_info['access_key'] 534 | try: 535 | vk_session.method("audio.add", add_params) 536 | except vk_api.VkApiError as e: 537 | self.add_log( 538 | f"Не получается добавить трек в мои аудиозаписи, ошибка: \"{e}\". Пропускаю трек...") 539 | else: 540 | self.add_log( 541 | f"Успешно добавил в мои аудиозаписи: \"{track_info['artist']} - {track_info['title']}\"") 542 | if len(self.env.ADD_TO_GROUP_ID or '') > 0: 543 | self.add_log( 544 | f"Добавляю \"{track_info['artist']} - {track_info['title']}\" (id: {track_info['id']}) в выбранное сообщество...") 545 | add_params = { 546 | 'audio_id': track_info['id'], 547 | 'owner_id': track_info['owner_id'], 548 | 'group_id': self.env.ADD_TO_GROUP_ID 549 | } 550 | if use_audio_links and track_info['access_key'] is not None: 551 | add_params['access_key'] = track_info['access_key'] 552 | try: 553 | vk_session.method("audio.add", add_params) 554 | except vk_api.VkApiError as e: 555 | self.add_log( 556 | f"Не получается добавить трек в сообщество, ошибка: \"{e}\". Пропускаю трек...") 557 | else: 558 | self.add_log( 559 | f"Успешно добавил в сообщество: \"{track_info['artist']} - {track_info['title']}\"") 560 | if use_audio_links: 561 | self.add_log(f"Успешно добавил в плейлист: \"id: {track_info['id']}\"") 562 | else: 563 | self.add_log(f"Успешно добавил в плейлист: \"{track_info['artist']} - {track_info['title']}\"") 564 | added_count += 1 565 | if self.env.TIMEOUT_AFTER_SUCCESS > 0: 566 | self.add_log(f"Жду {self.env.TIMEOUT_AFTER_SUCCESS} секунд (программа может зависнуть)...") 567 | sleep(self.env.TIMEOUT_AFTER_SUCCESS) 568 | self.is_under_ban = False 569 | 570 | if len(tracklist) != added_count: 571 | self.add_log(f"Выполнено, но в плейлист добавилось не всё: {added_count} из {len(tracklist)}") 572 | else: 573 | self.add_log(f"Выполнено успешно! Все найденные треки добавлены") 574 | 575 | self.add_log(f"Найдено треков с точными совпадениями: {len(self.ok_tracks)}") 576 | self.add_log(f"Найдено треков с примерными совпадениями: {len(self.questionable_tracks)}") 577 | self.add_log(f"Не найдено треков: {len(failed_tracks)}") 578 | 579 | self.add_log(f"Всего перенесено треков: {added_count} из {len(text_lines)}") 580 | with open(fix_relative_path(report_filename), 'w', encoding='utf-8') as f: 581 | questionable_tracks_str = '\n'.join( 582 | f'- "{t[0]} - {t[1]}" → "{t[2]} - {t[3]}"' for t in self.questionable_tracks) 583 | ok_tracks_str = '\n'.join(f'- "{t[0]} - {t[1]}"' for t in self.ok_tracks) 584 | failed_tracks_str = '\n'.join(f'- "{t[0]} - {t[1]}"' for t in failed_tracks) 585 | playlists_str = '\n'.join(f'- {p}' for p in playlists) 586 | f.write(f""" 587 | [ Отчет о перенесенных треках в VK Музыку ] 588 | 589 | Дата/время: {datetime.now().strftime('%d.%m.%Y %H:%M')}. 590 | Название плейлиста (если доступно): {title_playlist or '-'} 591 | Изображение плейлиста (если доступно): {playlist_img or '-'} 592 | Найдено треков с точными совпадениями: {len(self.ok_tracks)} 593 | Найдено треков с примерными совпадениями: {len(self.questionable_tracks)} 594 | Не найдено треков: {len(failed_tracks)} 595 | {f'Добавлено треков по прямым ссылкам: {len(tracklist)}' if use_audio_links else ''} 596 | 597 | ССЫЛКИ: 598 | 599 | {playlists_str or '[x]'} 600 | 601 | 602 | СПИОК НАЙДЕННЫХ ТРЕКОВ: 603 | 604 | {ok_tracks_str or '[x]'} 605 | 606 | 607 | СПИСОК НАЙДЕННЫХ ПОХОЖИХ ТРЕКОВ: 608 | 609 | {questionable_tracks_str or '[x]'} 610 | 611 | 612 | СПИСОК НЕНАЙДЕННЫХ ТРЕКОВ: 613 | 614 | {failed_tracks_str or '[x]'} 615 | 616 | 617 | ♫ Музыка перенесена с помощью vk-music-import 618 | 619 | - Телеграм-канал автора: https://t.me/mewnotes 620 | - Поддержать разработчика: https://mewforest.github.io/donate/ 621 | - Исходный код: https://github.com/mewforest/vk-music-import 622 | """.strip()) 623 | 624 | self.add_log(f"Файл отчета сгенерирован в текущей папке (\"{report_filename}\")") 625 | 626 | # Set gui to Start again 627 | self.stop_import() 628 | 629 | if os.path.exists(fix_relative_path("progress.json")): 630 | os.remove(fix_relative_path("progress.json")) 631 | if len(playlists) == 1: 632 | self.add_log(f"Скрипт выполнен! Твой плейлист готов: {playlists[0]}") 633 | else: 634 | self.add_log(f"Скрипт выполнен! Ваши плейлисты готовы: {', '.join(playlists)}") 635 | # if playlist_img is not None: 636 | # self.add_log(f"Дополнительно: скачать обложку плейлиста можно здесь: {playlist_img}") 637 | self.show_success_dialog("Импорт завершен", playlists, report_filename, playlist_img) 638 | # if platform.system() == "Windows": 639 | # webbrowser.open(fix_relative_path(report_filename)) 640 | 641 | def show_success_dialog(self, title: str, playlists_urls: List[str], report_filename, 642 | playlistImageUrl: Optional[str] = None): 643 | """ 644 | Показывает диалог успешного завершения импорта плейлиста: ссылки на плейлисты и обложку с кнопкой скачивания (если есть). 645 | А еще тут есть кнопка "просмотреть отчет" 646 | """ 647 | dialog = QDialog(self) 648 | dialog.setWindowTitle(title) 649 | dialog.setWindowModality(Qt.ApplicationModal) 650 | dialog.resize(400, 200) 651 | layout = QVBoxLayout() 652 | layout.addWidget(QLabel( 653 | "Импорт завершен!\n\n" 654 | "Треки успешно импортированы, посмотрите отчет или скачайте обложку плейлиста.")) 655 | for playlist_url in playlists_urls: 656 | playlist_url_label = QLabel(f'{playlist_url}') 657 | playlist_url_label.setOpenExternalLinks(True) 658 | layout.addWidget(playlist_url_label) 659 | 660 | # Playlist image 661 | if playlistImageUrl is not None: 662 | playlist_image_response = requests.get(playlistImageUrl) 663 | playlist_image = QImage() 664 | playlist_image.loadFromData(playlist_image_response.content) 665 | playlist_image_label = QLabel() 666 | playlist_image_pixmap = QPixmap.fromImage(playlist_image).scaled(200, 200, 667 | aspectRatioMode=Qt.KeepAspectRatio) 668 | playlist_image_label.setPixmap(playlist_image_pixmap) 669 | layout.addWidget(playlist_image_label, alignment=Qt.AlignCenter) 670 | download_image_button = QPushButton("Скачать обложку") 671 | download_image_button.clicked.connect(lambda: self.download_image(playlist_image_response.content)) 672 | 673 | if platform.system() == "Windows": 674 | show_report_button = QPushButton("Просмотреть отчет") 675 | show_report_button.setStyleSheet("QPushButton {font-weight: bold; margin-top: 10px;}") 676 | show_report_button.setFixedHeight(40) 677 | show_report_button.clicked.connect( 678 | lambda: webbrowser.open(fix_relative_path(report_filename))) 679 | layout.addWidget(show_report_button) 680 | 681 | if playlistImageUrl is not None: 682 | layout.addWidget(download_image_button) 683 | dialog.setLayout(layout) 684 | dialog.exec_() 685 | 686 | def download_image(self, image: bytes): 687 | """ 688 | Скачивает обложку плейлиста 689 | """ 690 | filename, _ = QFileDialog.getSaveFileName(self, 'Сохранить обложку плейлиста', 'playlist.jpg', 691 | "Images (*.jpg *.png)") 692 | if filename: 693 | with open(filename, "wb") as f: 694 | f.write(image) 695 | 696 | def stop_import(self): 697 | self.is_running = False 698 | self.start_button.setText("Начать импорт") 699 | 700 | def save_progress_to_file(self): 701 | """ 702 | Сохраняет прогресс в JSON файл (self.ok_tracks, self.questionable_tracks, self.playlist_response) 703 | """ 704 | with open(fix_relative_path("progress.json"), "w", encoding="utf-8") as f: 705 | json.dump({ 706 | "ok_tracks": self.ok_tracks, 707 | "questionable_tracks": self.questionable_tracks, 708 | "playlist_response": self.playlist_response, 709 | }, f, indent=4) 710 | 711 | def captcha_handler(self, captcha: Captcha): 712 | """ 713 | Хендлер для обработки капчи из VK 714 | """ 715 | if self.is_under_ban: 716 | # If captcha showed up before, show dialog yes/no to pause current progress and exit 717 | reply = QMessageBox.question(self, 'Сделаем паузу?', 718 | 'Кажется, VK снова запросил капчу, это значит, что vk временно блокирует возможность импорта музыки.\n' 719 | 'Возможно, стоит сделать перерыв в запросах и продолжить позже?\n\n' 720 | 'Если вы нажмете "Да", то скрипт остановится, но вы сможете продолжить импорт позже.\n' 721 | 'Если вы нажмете "Нет", то скрипт продолжит работу, но возможно, что vk так и не захочет импортировать.\n', 722 | QMessageBox.Yes | QMessageBox.No, QMessageBox.No) 723 | if reply == QMessageBox.Yes: 724 | self.save_progress_to_file() 725 | self.stop_import() 726 | self.add_log("Останавливается пользователем...") 727 | # Show user goodbye message 728 | QMessageBox.information(self, 'До встречи!', 729 | 'Программа остановлена, но вы можете продолжить импорт позже в любой момент.\n\n' 730 | 'Лучше подождите несколько минут, чтобы ВКонтакте перестал ругаться.') 731 | # exit program 732 | sys.exit(0) 733 | #return captcha.try_again('') 734 | else: 735 | self.add_log("Продолжаю работу, но vk может не захотеть импортировать...") 736 | self.is_under_ban = False 737 | 738 | self.is_under_ban = True 739 | start_time = datetime.now() 740 | captcha_url = captcha.get_url() 741 | parsed_url = urlparse(captcha_url) 742 | parsed_url_params = parse_qs(parsed_url.query) 743 | captcha_sid = parsed_url_params["sid"][0] 744 | captcha_s = parsed_url_params["s"][0] 745 | captcha_params_parsed = { 746 | "sid": int(captcha_sid), 747 | "s": int(captcha_s) 748 | } 749 | if self.env.BYPASS_CAPTCHA: 750 | self.add_log("Появилась капча, пытаюсь автоматически её решить...") 751 | key = solve_captcha(sid=captcha_params_parsed["sid"], s=captcha_params_parsed["s"]) 752 | else: 753 | self.add_log("Чтобы продолжить, введи капчу с картинки во всплывающем окне") 754 | response = requests.get(f'https://api.vk.com/captcha.php?sid={0}&s={1}'.format( 755 | captcha_params_parsed["sid"], captcha_params_parsed["s"])) 756 | img = Image.open(BytesIO(response.content)).resize((128, 64)).convert('RGB') 757 | key = get_user_solve(captcha_image=img, captcha_params_parsed=captcha_params_parsed) 758 | if key is None: 759 | self.add_log("Капча не решена, завершаю работу...") 760 | sys.exit(1) 761 | elapsed_time = datetime.now() - start_time 762 | self.add_log(f"Капча решена за {elapsed_time.microseconds * 0.001}мс") 763 | if self.env.TIMEOUT_AFTER_CAPTCHA > 0: 764 | self.add_log(f"Чтобы VK не ругался, жду {self.env.TIMEOUT_AFTER_CAPTCHA} сек...") 765 | self.add_log(f"(Программа может подвиснуть на {self.env.TIMEOUT_AFTER_CAPTCHA} секунд)") 766 | sleep(self.env.TIMEOUT_AFTER_CAPTCHA) 767 | self.add_log("Отправляю решение капчи...") 768 | return captcha.try_again(key) 769 | 770 | 771 | # Creating a class for the settings tab 772 | class SettingsTab(QWidget, MainEnv): 773 | def __init__(self): 774 | # Call both parents constructors 775 | QWidget.__init__(self) 776 | MainEnv.__init__(self) 777 | # Creating a form layout for the tab 778 | self.layout = QFormLayout() 779 | # Creating radio buttons for the mode selection 780 | self.tracklist_mode = QRadioButton("Треклист (tracklist.txt)") 781 | self.spotify_mode = QRadioButton("Плейлист Spotify") 782 | self.apple_mode = QRadioButton("Плейлист из Apple Music") 783 | self.vk_links_mode = QRadioButton("Список ссылок на треки в VK") 784 | self.reverse = QCheckBox() 785 | self.strict_search = QCheckBox() 786 | self.add_to_library = QCheckBox() 787 | self.add_to_group = QLineEdit() 788 | self.bypass_captcha = QCheckBox() 789 | # self.update_playlist = QCheckBox() 790 | # Creating line edits for the string and integer environment variables 791 | self.vk_token = QLineEdit() 792 | self.vk_token.setPlaceholderText("Нажмите \"Авторизоваться\", чтобы войти в VK") 793 | self.timeout_after_error = QLineEdit() 794 | self.timeout_after_captcha = QLineEdit() 795 | self.timeout_after_success = QLineEdit() 796 | # Setting the initial values of the widgets from the environment variables 797 | self.tracklist_mode.setChecked( 798 | not self.env.SPOTIFY_MODE and not self.env.APPLE_MODE and not self.env.VK_LINKS_MODE) 799 | self.spotify_mode.setChecked(self.env.SPOTIFY_MODE) 800 | self.apple_mode.setChecked(self.env.APPLE_MODE) 801 | self.vk_links_mode.setChecked(self.env.VK_LINKS_MODE) 802 | self.bypass_captcha.setChecked(self.env.BYPASS_CAPTCHA) 803 | self.reverse.setChecked(self.env.REVERSE) 804 | self.strict_search.setChecked(self.env.STRICT_SEARCH) 805 | self.add_to_library.setChecked(self.env.ADD_TO_LIBRARY) 806 | self.add_to_group.setText(str(self.env.ADD_TO_GROUP_ID)) 807 | # self.update_playlist.setChecked(self.env.UPDATE_PLAYLIST) 808 | self.vk_token.setText(self.env.VK_TOKEN) 809 | self.timeout_after_error.setText(str(self.env.TIMEOUT_AFTER_ERROR)) 810 | self.timeout_after_captcha.setText(str(self.env.TIMEOUT_AFTER_CAPTCHA)) 811 | self.timeout_after_success.setText(str(self.env.TIMEOUT_AFTER_SUCCESS)) 812 | # Adding help tooltips to the widgets 813 | self.tracklist_mode.setToolTip("Импортировать треки из файла tracklist.txt") 814 | self.spotify_mode.setToolTip("Импортировать треки из плейлиста Spotify (SPOTIFY_MODE)") 815 | self.apple_mode.setToolTip("Импортировать треки из экспортированного CSV-плейлиста Apple Music (APPLE_MODE)") 816 | self.vk_links_mode.setToolTip("Импортировать треки из списка ссылок на треки в VK Музыке (VK_LINKS_MODE)") 817 | self.bypass_captcha.setToolTip( 818 | "Автоматически решать капчу, если выключена, ответ придётся вводить вручную (BYPASS_CAPTCHA)") 819 | self.reverse.setToolTip( 820 | "Добавлять треки в обратном порядке - подходит по-умолчанию для плейлистов Spotify (REVERSE)") 821 | self.strict_search.setToolTip( 822 | "Искать только точные совпадения, если выключено может добавить ремикс или 'перезалив' оригинальной композиции (STRICT_SEARCH)") 823 | self.add_to_library.setToolTip("Добавлять треки в Мои Аудиозаписи (ADD_TO_LIBRARY)") 824 | self.add_to_group.setToolTip("Добавлять треки в сообщество с указанным ID. Если пусто, то опция выключена. (ADD_TO_GROUP_ID)") 825 | # self.update_playlist.setToolTip("Обновлять плейлист, если он уже существует (UPDATE_PLAYLIST)") 826 | self.vk_token.setToolTip("Токен VK API, через него утилита получает доступ к вашим аудиозаписям (VK_TOKEN)") 827 | self.timeout_after_error.setToolTip("Задержка после ошибки, сек (TIMEOUT_AFTER_ERROR)") 828 | self.timeout_after_captcha.setToolTip("Задержка после капчи, сек (TIMEOUT_AFTER_CAPTCHA)") 829 | self.timeout_after_success.setToolTip( 830 | "Задержка после успешного добавления аудиозаписи, сек (TIMEOUT_AFTER_SUCCESS)") 831 | # Adding the widgets and their labels to the form layout 832 | # VK Token + refresh button 833 | self.vk_token_layout = QHBoxLayout() 834 | self.vk_token_layout.addWidget(self.vk_token) 835 | self.vk_token_refresh_button = QPushButton("Авторизоваться заново" if self.env.VK_TOKEN else 'Авторизоваться') 836 | self.vk_token_refresh_button.clicked.connect(self.get_token) 837 | self.vk_token_layout.addWidget(self.vk_token_refresh_button) 838 | self.layout.addRow("Токен от ВКонтакте", self.vk_token_layout) 839 | self.layout.addRow("Откуда импортировать:", self.tracklist_mode) 840 | self.layout.addRow("", self.spotify_mode) 841 | self.layout.addRow("", self.apple_mode) 842 | self.layout.addRow("", self.vk_links_mode) 843 | self.layout.addRow("Автоматический обход капчи", self.bypass_captcha) 844 | self.layout.addRow("В обратном порядке", self.reverse) 845 | self.layout.addRow("Только точные совпадения", self.strict_search) 846 | self.layout.addRow("Добавлять в Мои Аудиозаписи", self.add_to_library) 847 | self.layout.addRow("Добавить в VK Сообщество с ID", self.add_to_group) 848 | # self.layout.addRow("Обновлять существующий плейлист", self.update_playlist) 849 | self.layout.addRow("Задержка после ошибок, сек", self.timeout_after_error) 850 | self.layout.addRow("Задержка после капчи, сек", self.timeout_after_captcha) 851 | self.layout.addRow("Задержка после успеха, сек", self.timeout_after_success) 852 | # Creating save and reset button 853 | self.save_button = QPushButton("Сохранить настройки") 854 | self.reset_button = QPushButton("Сбросить настройки") 855 | self.save_button.setStyleSheet("QPushButton {font-weight: bold; margin-top: 10px;}") 856 | self.save_button.setFixedHeight(40) 857 | # Connecting save and reset button to a function that updates the environment variables 858 | self.save_button.clicked.connect(self.save_envs) 859 | self.reset_button.clicked.connect(self.reset_envs) 860 | # Adding save and reset button to the form layout 861 | self.layout.addRow(self.save_button) 862 | self.layout.addRow(self.reset_button) 863 | # Setting the layout for the tab 864 | self.setLayout(self.layout) 865 | 866 | def reset_envs(self): 867 | # Ask user to confirm reset 868 | reply = QMessageBox.question(self, 'Подтверждение', 869 | 'Вы уверены, что хотите сбросить настройки?', 870 | QMessageBox.Yes | QMessageBox.No, QMessageBox.No) 871 | if reply == QMessageBox.No: 872 | return 873 | # Setting the environment variables using the set_key function 874 | set_key(config_path, "BYPASS_CAPTCHA", "1") 875 | set_key(config_path, "SPOTIFY_MODE", "1") 876 | set_key(config_path, "APPLE_MODE", "0") 877 | set_key(config_path, "VK_LINKS_MODE", "0") 878 | set_key(config_path, "REVERSE", "1") 879 | set_key(config_path, "STRICT_SEARCH", "0") 880 | set_key(config_path, "ADD_TO_LIBRARY", "0") 881 | set_key(config_path, "ADD_TO_GROUP_ID", "") 882 | set_key(config_path, "VK_TOKEN", "") 883 | set_key(config_path, "TIMEOUT_AFTER_ERROR", "1") 884 | set_key(config_path, "TIMEOUT_AFTER_CAPTCHA", "0") 885 | set_key(config_path, "TIMEOUT_AFTER_SUCCESS", "0") 886 | # set_key(config_path, "UPDATE_PLAYLIST", "0") 887 | # Reloading the config_path file 888 | self.load_env_config() 889 | # Setting the initial values of the widgets from the environment variables 890 | self.tracklist_mode.setChecked( 891 | not self.env.SPOTIFY_MODE and not self.env.APPLE_MODE and not self.env.VK_LINKS_MODE) 892 | self.spotify_mode.setChecked(self.env.SPOTIFY_MODE) 893 | self.apple_mode.setChecked(self.env.APPLE_MODE) 894 | self.vk_links_mode.setChecked(self.env.VK_LINKS_MODE) 895 | self.bypass_captcha.setChecked(self.env.BYPASS_CAPTCHA) 896 | self.reverse.setChecked(self.env.REVERSE) 897 | self.strict_search.setChecked(self.env.STRICT_SEARCH) 898 | self.add_to_library.setChecked(self.env.ADD_TO_LIBRARY) 899 | self.add_to_group.setText(str(self.env.ADD_TO_GROUP_ID)) 900 | self.vk_token.setText(self.env.VK_TOKEN) 901 | self.timeout_after_error.setText(str(self.env.TIMEOUT_AFTER_ERROR)) 902 | self.timeout_after_captcha.setText(str(self.env.TIMEOUT_AFTER_CAPTCHA)) 903 | self.timeout_after_success.setText(str(self.env.TIMEOUT_AFTER_SUCCESS)) 904 | # self.add_log("Настройки сброшены") 905 | 906 | # Defining a function that updates the environment variables 907 | def save_envs(self): 908 | # Converting the checkboxes to 0 or 1 909 | bypass_captcha = "1" if self.bypass_captcha.isChecked() else "0" 910 | spotify_mode = "1" if self.spotify_mode.isChecked() else "0" 911 | apple_mode = "1" if self.apple_mode.isChecked() else "0" 912 | vk_links_mode = "1" if self.vk_links_mode.isChecked() else "0" 913 | reverse = "1" if self.reverse.isChecked() else "0" 914 | strict_search = "1" if self.strict_search.isChecked() else "0" 915 | add_to_library = "1" if self.add_to_library.isChecked() else "0" 916 | add_to_group_id = self.add_to_group.text() 917 | # update_playlist = "1" if self.update_playlist.isChecked() else "0" 918 | # If tracklist mode is selected, set all the other modes to 0 919 | if self.tracklist_mode.isChecked(): 920 | spotify_mode = "0" 921 | apple_mode = "0" 922 | vk_links_mode = "0" 923 | # Getting the values of the line edits 924 | vk_token = self.vk_token.text() 925 | timeout_after_error = self.timeout_after_error.text() 926 | timeout_after_captcha = self.timeout_after_captcha.text() 927 | timeout_after_success = self.timeout_after_success.text() 928 | # Setting the environment variables using the set_key function 929 | set_key(config_path, "BYPASS_CAPTCHA", bypass_captcha) 930 | set_key(config_path, "SPOTIFY_MODE", spotify_mode) 931 | set_key(config_path, "APPLE_MODE", apple_mode) 932 | set_key(config_path, "VK_LINKS_MODE", vk_links_mode) 933 | set_key(config_path, "REVERSE", reverse) 934 | set_key(config_path, "STRICT_SEARCH", strict_search) 935 | set_key(config_path, "ADD_TO_LIBRARY", add_to_library) 936 | set_key(config_path, "ADD_TO_GROUP_ID", add_to_group_id) 937 | set_key(config_path, "VK_TOKEN", vk_token) 938 | # set_key(config_path, "UPDATE_PLAYLIST", update_playlist) 939 | set_key(config_path, "TIMEOUT_AFTER_ERROR", timeout_after_error) 940 | set_key(config_path, "TIMEOUT_AFTER_CAPTCHA", timeout_after_captcha) 941 | set_key(config_path, "TIMEOUT_AFTER_SUCCESS", timeout_after_success) 942 | # Reloading the config_path file 943 | self.load_env_config() 944 | 945 | def get_token(self): 946 | self.token_dialog = QDialog() 947 | self.token_dialog.setWindowTitle('Необходимо авторизоваться во ВКонтакте') 948 | self.token_dialog.setFixedSize(500, 150) 949 | 950 | layout = QVBoxLayout() 951 | 952 | # Add instructions label 953 | instructions_label = QLabel(self.token_dialog) 954 | instructions_label.setText( 955 | "1. Перейди по ссылке ниже и нажми 'Разрешить'\n" 956 | "2. Скопируй ссылку из адресной строки браузера и вставь её в следующем\n" 957 | "диалоге.".strip()) 958 | layout.addWidget(instructions_label) 959 | 960 | # Add open link button 961 | open_link_button = QPushButton(self.token_dialog) 962 | open_link_button.setText('Открыть ссылку для авторизации') 963 | layout.addWidget(open_link_button) 964 | 965 | # Add copy link button 966 | copy_link_button = QPushButton(self.token_dialog) 967 | copy_link_button.setText('Скопировать ссылку в буфер обмена') 968 | layout.addWidget(copy_link_button) 969 | 970 | # Connect open link button clicked event 971 | open_link_button.clicked.connect(self.open_vk_authorization_link) 972 | 973 | # Connect copy link button clicked event 974 | copy_link_button.clicked.connect(self.copy_vk_authorization_link) 975 | 976 | self.token_dialog.setLayout(layout) 977 | self.token_dialog.exec_() 978 | 979 | def open_vk_authorization_link(self): 980 | link = 'https://oauth.vk.com/oauth/authorize?client_id=6121396' \ 981 | '&scope=audio,offline' \ 982 | '&redirect_uri=https://oauth.vk.com/blank.html' \ 983 | '&display=page' \ 984 | '&response_type=token' \ 985 | '&revoke=1' \ 986 | '&slogin_h=23a7bd142d757e24f9.93b0910a902d50e507&__q_hash=fed6a6c326a5673ad33facaf442b3991' 987 | QDesktopServices.openUrl(QUrl(link)) 988 | self.input_token_url() 989 | 990 | def copy_vk_authorization_link(self): 991 | link = 'https://oauth.vk.com/oauth/authorize?client_id=6121396' \ 992 | '&scope=audio,offline' \ 993 | '&redirect_uri=https://oauth.vk.com/blank.html' \ 994 | '&display=page' \ 995 | '&response_type=token' \ 996 | '&revoke=1' \ 997 | '&slogin_h=23a7bd142d757e24f9.93b0910a902d50e507&__q_hash=fed6a6c326a5673ad33facaf442b3991' 998 | clipboard = QApplication.clipboard() 999 | clipboard.setText(link, QClipboard.Clipboard) 1000 | self.input_token_url() 1001 | 1002 | def input_token_url(self): 1003 | """ 1004 | Shows input dialog for token url and saves it to config_path 1005 | """ 1006 | self.token_input_dialog = QDialog() 1007 | self.token_input_dialog.setWindowTitle('Вставь ссылку с токеном') 1008 | self.token_input_dialog.setFixedSize(400, 150) 1009 | 1010 | layout = QVBoxLayout() 1011 | 1012 | # Add instructions label 1013 | instructions_label = QLabel(self.token_input_dialog) 1014 | instructions_label.setText( 1015 | "После того, как вы нажмёте \"Разрешить\" откроется пустая\n" 1016 | "страница, скопируй ссылку на неё из адресной строки\n" 1017 | "браузера и вставь её в поле ниже:") 1018 | layout.addWidget(instructions_label) 1019 | 1020 | # Add token entry 1021 | token_entry = QLineEdit(self.token_input_dialog) 1022 | layout.addWidget(token_entry) 1023 | 1024 | # Add submit button 1025 | submit_button = QPushButton(self.token_input_dialog) 1026 | submit_button.setText('Сохранить') 1027 | layout.addWidget(submit_button) 1028 | 1029 | # Connect submit button clicked event 1030 | submit_button.clicked.connect(self.apply_token) 1031 | 1032 | self.token_input_dialog.setLayout(layout) 1033 | self.token_input_dialog.exec_() 1034 | 1035 | def apply_token(self): 1036 | """ 1037 | Функция для запроса токена от ВКонтакте 1038 | """ 1039 | token_url = self.token_input_dialog.findChild(QLineEdit).text() 1040 | token_match = re.match(r'https://oauth.vk.com/blank.html#access_token=([^&]+).+', token_url) 1041 | if token_match is None: 1042 | # self.token_dialog.accept() 1043 | warn_text = "Некорректная ссылка. После того, как вы нажали \"Разрешить\" ссылка должна начинаться с https://oauth.vk.com/blank.html#access_token=" 1044 | QMessageBox.warning(self.token_input_dialog, "Некорректная ссылка", warn_text) 1045 | return 1046 | # Applying token 1047 | self.token_input_dialog.accept() 1048 | self.env.VK_TOKEN = token_match.group(1) 1049 | set_key(config_path, "VK_TOKEN", token_match.group(1)) 1050 | self.load_env_config() 1051 | # Close token dialog 1052 | self.token_input_dialog.close() 1053 | self.token_dialog.close() 1054 | self.vk_token.setText(token_match.group(1)) 1055 | self.vk_token_refresh_button.setText("Авторизоваться заново" if self.env.VK_TOKEN else 'Авторизоваться') 1056 | 1057 | 1058 | def chunks(lst, n): 1059 | """ 1060 | Разделяет список на чанки 1061 | """ 1062 | for i in range(0, len(lst), n): 1063 | yield lst[i:i + n] 1064 | 1065 | 1066 | def get_user_solve(captcha_image: Image, captcha_params_parsed: dict[str, int]) -> Union[str, None]: 1067 | """ 1068 | Получает решение капчи от пользователя (GUI) 1069 | """ 1070 | dialog = QDialog() 1071 | dialog.setWindowTitle('Введи капчу с картинки') 1072 | dialog.setFixedSize(285, 145) 1073 | 1074 | layout = QVBoxLayout() 1075 | 1076 | # Add image label 1077 | image_label = QLabel(dialog) 1078 | captcha_image_bytes = captcha_image.tobytes("raw", "RGB") 1079 | qimage = QImage(captcha_image_bytes, captcha_image.size[0], captcha_image.size[1], QImage.Format_RGB888) 1080 | image_label.setPixmap(QPixmap.fromImage(qimage)) 1081 | layout.addWidget(image_label) 1082 | 1083 | # Add captcha solve entry 1084 | captcha_solve_entry = QLineEdit(dialog) 1085 | captcha_solve_entry.setText( 1086 | solve_captcha(sid=captcha_params_parsed["sid"], s=captcha_params_parsed["s"], img=captcha_image)) 1087 | captcha_solve_entry.selectAll() 1088 | layout.addWidget(captcha_solve_entry) 1089 | 1090 | # Add submit button 1091 | submit_button = QPushButton('Отправить решение', dialog) 1092 | submit_button.clicked.connect(dialog.accept) 1093 | layout.addWidget(submit_button) 1094 | 1095 | dialog.setLayout(layout) 1096 | 1097 | if dialog.exec_() == QDialog.Accepted: 1098 | captcha_solve = captcha_solve_entry.text() 1099 | return captcha_solve if captcha_solve else None 1100 | else: 1101 | return None 1102 | 1103 | 1104 | def solve_captcha(sid, s, img=None): 1105 | """ 1106 | Обработчик капчи с помощью машинного зрения 1107 | """ 1108 | if img is None: 1109 | response = requests.get(f'https://api.vk.com/captcha.php?sid={sid}&s={s}') 1110 | img = Image.open(BytesIO(response.content)).resize((128, 64)).convert('RGB') 1111 | x = np.array(img).reshape(1, -1) 1112 | x = np.expand_dims(x, axis=0) 1113 | x = x / np.float32(255.) 1114 | session = rt.InferenceSession(fix_relative_path('models/captcha_model.onnx')) 1115 | session2 = rt.InferenceSession(fix_relative_path('models/ctc_model.onnx')) 1116 | out = session.run(None, dict([(inp.name, x[n]) for n, inp in enumerate(session.get_inputs())])) 1117 | out = session2.run(None, dict([(inp.name, np.float32(out[n])) for n, inp in enumerate(session2.get_inputs())])) 1118 | char_map = ' 24578acdehkmnpqsuvxyz' 1119 | captcha = ''.join([char_map[c] for c in np.uint8(out[-1][out[0] > 0])]) 1120 | return captcha 1121 | 1122 | 1123 | if __name__ == "__main__": 1124 | # Logging formatting 1125 | logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') 1126 | # Create a RotatingFileHandler with a max size of 10MB 1127 | file_handler = RotatingFileHandler(fix_relative_path('debug.log'), maxBytes=10 * 1024 * 1024, backupCount=1, 1128 | encoding='utf-8' 1129 | ) 1130 | file_handler.setLevel(logging.DEBUG) 1131 | # Add the file handler to the root logger 1132 | logging.getLogger().addHandler(file_handler) 1133 | 1134 | try: 1135 | # Config path 1136 | config_path = fix_relative_path("config.env") 1137 | # Creating an application instance 1138 | app = QApplication(sys.argv) 1139 | # Apply the complete dark theme to your Qt App. 1140 | qdarktheme.setup_theme('auto', additional_qss="QToolTip {color: black;}") 1141 | # Setting the high DPI scaling 1142 | qdarktheme.enable_hi_dpi() 1143 | # Creating a main window instance 1144 | window = MainWindow() 1145 | # Showing the main window 1146 | window.show() 1147 | # Executing the application 1148 | sys.exit(app.exec_()) 1149 | except Exception as e: 1150 | logging.error(e) 1151 | --------------------------------------------------------------------------------