├── app ├── __init__.py ├── bot │ ├── __init__.py │ ├── state_manager.py │ ├── main.py │ └── plugins │ │ ├── __init__.py │ │ ├── common.py │ │ ├── wall.py │ │ └── playlist.py ├── schemas │ ├── __init__.py │ └── vk.py ├── utils │ ├── __init__.py │ ├── telegram.py │ ├── database.py │ ├── downloader.py │ └── vk.py ├── handlers │ ├── __init__.py │ ├── playlist.py │ ├── text.py │ └── wall.py ├── gunicorn_worker.py ├── celeryconfig.py.example ├── logging_config.yaml ├── sign_in.py ├── main.py ├── celery_worker.py └── config.py ├── logs └── .gitignore ├── tgm_sessions └── .gitignore ├── .shellcheckrc ├── babel.cfg ├── poetry.toml ├── setup ├── ssl │ ├── .gitignore │ ├── renew.sh │ └── README.md ├── nginx │ └── vtt-cb-receiver.conf ├── systemd │ ├── vtt-tgm-bot.service │ ├── vtt-cb-receiver.service │ ├── vtt-dbc-scheduler.service │ └── vtt-workers.service └── configs │ └── vtt-celery.conf ├── setup.cfg ├── assets ├── vtt_example.gif └── vtt_schema.png ├── locale ├── en │ └── LC_MESSAGES │ │ ├── vtt.mo │ │ └── vtt.po ├── ru │ └── LC_MESSAGES │ │ ├── vtt.mo │ │ └── vtt.po └── base.pot ├── .gitignore ├── tunnel ├── package.json ├── app.js └── package-lock.json ├── .vscode ├── settings.json └── launch.json ├── CHANGELOG.md ├── Dockerfile ├── .github └── workflows │ └── bumpversion.yml ├── uninstall.sh ├── pyproject.toml ├── .env.example ├── docker-compose.yml ├── vtt-cli.sh ├── install.sh ├── README.md ├── requirements.txt ├── functions.sh └── LICENSE /app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/bot/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/schemas/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /logs/.gitignore: -------------------------------------------------------------------------------- 1 | *.log* -------------------------------------------------------------------------------- /app/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tgm_sessions/.gitignore: -------------------------------------------------------------------------------- 1 | *.session 2 | -------------------------------------------------------------------------------- /.shellcheckrc: -------------------------------------------------------------------------------- 1 | external-sources=true 2 | -------------------------------------------------------------------------------- /babel.cfg: -------------------------------------------------------------------------------- 1 | [python: **.py] 2 | encoding = utf-8 3 | -------------------------------------------------------------------------------- /poetry.toml: -------------------------------------------------------------------------------- 1 | [virtualenvs] 2 | in-project = true 3 | -------------------------------------------------------------------------------- /setup/ssl/.gitignore: -------------------------------------------------------------------------------- 1 | *.crt 2 | *.key 3 | *.p12 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | ban-relative-imports = true 4 | -------------------------------------------------------------------------------- /assets/vtt_example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bizordec/vk-to-tgm/HEAD/assets/vtt_example.gif -------------------------------------------------------------------------------- /assets/vtt_schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bizordec/vk-to-tgm/HEAD/assets/vtt_schema.png -------------------------------------------------------------------------------- /locale/en/LC_MESSAGES/vtt.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bizordec/vk-to-tgm/HEAD/locale/en/LC_MESSAGES/vtt.mo -------------------------------------------------------------------------------- /locale/ru/LC_MESSAGES/vtt.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bizordec/vk-to-tgm/HEAD/locale/ru/LC_MESSAGES/vtt.mo -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | .venv 3 | __pycache__ 4 | vk_config.v2.json 5 | celeryconfig.py 6 | .env* 7 | !.env.example 8 | node_modules 9 | *.db 10 | *.session 11 | *.session-journal 12 | celerybeat-* -------------------------------------------------------------------------------- /app/gunicorn_worker.py: -------------------------------------------------------------------------------- 1 | from uvicorn.workers import UvicornWorker 2 | 3 | 4 | class MyUvicornWorker(UvicornWorker): 5 | CONFIG_KWARGS = { 6 | "log_config": "app/logging_config.yaml", 7 | } 8 | -------------------------------------------------------------------------------- /setup/ssl/renew.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | openssl req -newkey rsa:2048 -sha256 -nodes -keyout vkapi.key -x509 -days 365 -out vkapi.crt -subj "/C=RU/ST=Saint Petersburg/L=Saint Petersburg/O=VK API Club/CN=vkapi" 4 | 5 | openssl pkcs12 -export -in vkapi.crt -name "Test" -descert -inkey vkapi.key -out vkapi.p12 -passout pass: 6 | -------------------------------------------------------------------------------- /tunnel/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tunnel", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node app.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "envfile": "^6.17.0", 13 | "localtunnel": "^2.0.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[python]": { 3 | "editor.codeActionsOnSave": { 4 | "source.organizeImports": true, 5 | }, 6 | "editor.formatOnSave": true, 7 | }, 8 | "python.linting.enabled": true, 9 | "python.linting.flake8Enabled": true, 10 | "python.formatting.provider": "black", 11 | } -------------------------------------------------------------------------------- /setup/nginx/vtt-cb-receiver.conf: -------------------------------------------------------------------------------- 1 | server { 2 | # Add SSL client certificate 3 | # ssl_client_certificate ; 4 | # ssl_verify_client on; 5 | # ssl_verify_depth 0; 6 | 7 | # Add domain server name 8 | # server_name ; 9 | location / { 10 | include proxy_params; 11 | proxy_pass http://127.0.0.1:8000; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /setup/systemd/vtt-tgm-bot.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Telegram bot for forwarding wall posts and playlists from VK 3 | After=network.target 4 | After=rabbitmq-server.service 5 | Wants=rabbitmq-server.service 6 | 7 | [Service] 8 | User=vtt-user 9 | Group=vtt-user 10 | WorkingDirectory=/srv/vk-to-tgm 11 | Environment="VTT_VENV=/srv/vk-to-tgm/.venv" 12 | ExecStart=/bin/sh -c '${VTT_VENV}/bin/python -m app.bot.main' 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## v1.2.1 (2023-08-10) 2 | 3 | ### Fix 4 | 5 | - **docker**: Fix docker image build error caused by old poetry 6 | 7 | ## v1.2.0 (2023-08-06) 8 | 9 | ### Feat 10 | 11 | - **cb-receiver**: add option to skip ad posts (true by default) 12 | 13 | ## v1.1.3 (2023-01-14) 14 | 15 | ## v1.1.2 (2022-07-15) 16 | 17 | ## v1.1.1 (2022-07-03) 18 | 19 | ## v1.1.0 (2022-06-13) 20 | 21 | ## v1.0.2 (2022-05-07) 22 | 23 | ## v1.0.1 (2022-04-30) 24 | 25 | ## v1.0.0 (2022-04-27) 26 | -------------------------------------------------------------------------------- /setup/systemd/vtt-cb-receiver.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=VK callback reciever for VK to Telegram forwarding 3 | After=network.target 4 | After=rabbitmq-server.service 5 | Wants=rabbitmq-server.service 6 | 7 | [Service] 8 | User=vtt-user 9 | Group=vtt-user 10 | WorkingDirectory=/srv/vk-to-tgm 11 | Environment="VTT_VENV=/srv/vk-to-tgm/.venv" 12 | ExecStart=/bin/sh -c '${VTT_VENV}/bin/gunicorn -w 1 -k app.gunicorn_worker.MyUvicornWorker app.main:app' 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /setup/systemd/vtt-dbc-scheduler.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=VK to Telegram database cleanup scheduler service 3 | After=network.target 4 | 5 | [Service] 6 | Type=simple 7 | User=vtt-user 8 | Group=vtt-user 9 | EnvironmentFile=/etc/default/vtt-celery.conf 10 | WorkingDirectory=/srv/vk-to-tgm 11 | ExecStart=/bin/sh -c '${CELERY_BIN} -A ${CELERY_APP} beat \ 12 | --pidfile=${CELERYBEAT_PID_FILE} \ 13 | --logfile=${CELERYBEAT_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL}' 14 | Restart=always 15 | 16 | [Install] 17 | WantedBy=multi-user.target 18 | -------------------------------------------------------------------------------- /app/celeryconfig.py.example: -------------------------------------------------------------------------------- 1 | # Create .celeryconfig file based on this file. If you want, you can modify the variables. 2 | # cp .celeryconfig.py.example .celeryconfig.py 3 | 4 | # Broker settings. 5 | broker_url = "amqp://guest:guest@localhost:5672//" 6 | 7 | # Using the database to store task state and results. 8 | result_backend = "db+sqlite:///celery-results.db" 9 | 10 | task_track_started = True 11 | 12 | worker_cancel_long_running_tasks_on_connection_loss = True 13 | 14 | broker_pool_limit = 1 15 | broker_heartbeat = None 16 | task_acks_late = True 17 | worker_prefetch_multiplier = 1 18 | 19 | task_routes = { 20 | "app.celery_worker.forward_wall": {"queue": "vtt-wall"}, 21 | "app.celery_worker.forward_playlist": {"queue": "vtt-playlist"}, 22 | } 23 | -------------------------------------------------------------------------------- /tunnel/app.js: -------------------------------------------------------------------------------- 1 | const localtunnel = require('localtunnel'); 2 | const fs = require('fs'); 3 | const { parse, stringify } = require('envfile'); 4 | 5 | 6 | (async () => { 7 | const port = process.argv.splice(2)[0] || 8000; 8 | const tunnel = await localtunnel({ port: port, subdomain: 'mtest' }); 9 | 10 | // the assigned public url for your tunnel 11 | // i.e. https://abcdefgjhij.localtunnel.me 12 | console.log(tunnel.url); 13 | 14 | const sourcePath = '../.env' 15 | const data = fs.readFileSync(sourcePath, 'utf8'); 16 | const parsedFile = parse(data); 17 | parsedFile.SERVER_URL = '"' + tunnel.url + '/"'; 18 | parsedFile.NGINX_HOST = '"' + tunnel.url.match(/https?:\/\/(.*)/)[1] + '"'; 19 | fs.writeFileSync(sourcePath, stringify(parsedFile)) 20 | 21 | tunnel.on('close', () => { 22 | console.warn('WARNING: Tunnel closed!'); 23 | }); 24 | })(); -------------------------------------------------------------------------------- /app/bot/state_manager.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | from typing import Dict, Optional, Tuple 3 | 4 | 5 | class State(Enum): 6 | WAITING_FOR_LINK = auto() 7 | LINK_SENT = auto() 8 | WAITING_FOR_CHOISE = auto() 9 | 10 | 11 | class StateManager: 12 | def __init__(self) -> None: 13 | self._states: "Dict[int, Tuple[State, dict]]" = {} 14 | 15 | def get_info(self, sender_id: int) -> Tuple[State, dict]: 16 | info = self._states.get(sender_id) 17 | if not info: 18 | info = (State.WAITING_FOR_LINK, {}) 19 | self._states[sender_id] = info 20 | return info 21 | 22 | def set_info(self, sender_id: int, state: State, data: Optional[dict] = None) -> None: 23 | self._states[sender_id] = (state, data or {}) 24 | 25 | def clear_info(self, sender_id: int) -> None: 26 | self._states.pop(sender_id, None) 27 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10.12-bullseye AS build-stage 2 | 3 | WORKDIR /vk-to-tgm 4 | 5 | ENV PYTHONUNBUFFERED=1 \ 6 | PYTHONDONTWRITEBYTECODE=1 \ 7 | PIP_NO_CACHE_DIR=1 \ 8 | PIP_DISABLE_PIP_VERSION_CHECK=1 \ 9 | PIP_DEFAULT_TIMEOUT=100 \ 10 | POETRY_VIRTUALENVS_IN_PROJECT=1 11 | 12 | RUN pip install poetry==1.5.1 13 | 14 | COPY ./pyproject.toml ./poetry.lock* /vk-to-tgm/ 15 | RUN poetry install --no-root --without=dev --no-interaction --no-ansi 16 | 17 | 18 | FROM python:3.10.12-slim-bullseye 19 | 20 | WORKDIR /vk-to-tgm 21 | 22 | ENV PYTHONUNBUFFERED=1 \ 23 | PYTHONDONTWRITEBYTECODE=1 \ 24 | PATH="/vk-to-tgm/.venv/bin:$PATH" 25 | 26 | COPY --from=build-stage /vk-to-tgm/.venv/ /vk-to-tgm/.venv 27 | 28 | RUN mkdir logs/ 29 | 30 | COPY app/ ./app 31 | COPY app/celeryconfig.py.example ./app/celeryconfig.py 32 | COPY locale/ ./locale 33 | COPY vtt-cli.sh functions.sh ./ 34 | -------------------------------------------------------------------------------- /setup/ssl/README.md: -------------------------------------------------------------------------------- 1 | # Client SSL certificate setup 2 | 3 | 1. Setup server SSL certificate. [Certbot](https://certbot.eff.org/) can help you with that; 4 | 2. Create client self-signed certificate (will work 365 days): 5 | ```bash 6 | openssl req -newkey rsa:2048 -sha256 -nodes -keyout vkapi.key -x509 -days 365 -out vkapi.crt -subj "/C=RU/ST=Saint Petersburg/L=Saint Petersburg/O=VK API Club/CN=vkapi" 7 | 8 | openssl pkcs12 -export -in vkapi.crt -name "Test" -descert -inkey vkapi.key -out vkapi.p12 -passout pass: 9 | ``` 10 | 3. Go to your VK community page, `"Manage" > "Settings" > "API usage" > "Callback API" > "Server settings"` and upload `vkapi.p12` file; 11 | 4. Add following lines to the nginx config: 12 | ``` 13 | ssl_client_certificate ; 14 | ssl_verify_client on; 15 | ssl_verify_depth 0; 16 | ``` 17 | 5. Restart nginx: 18 | ```bash 19 | sudo service nginx restart 20 | ``` 21 | -------------------------------------------------------------------------------- /.github/workflows/bumpversion.yml: -------------------------------------------------------------------------------- 1 | name: Bump version 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | bump-version: 10 | if: "!startsWith(github.event.head_commit.message, 'bump:')" 11 | runs-on: ubuntu-latest 12 | name: "Bump version and create changelog with commitizen" 13 | permissions: 14 | contents: write 15 | steps: 16 | - name: Check out 17 | uses: actions/checkout@v3 18 | with: 19 | token: "${{ secrets.PERSONAL_ACCESS_TOKEN }}" 20 | fetch-depth: 0 21 | - name: Create bump and changelog 22 | uses: commitizen-tools/commitizen-action@master 23 | with: 24 | github_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }} 25 | changelog_increment_filename: body.md 26 | - name: Release 27 | uses: softprops/action-gh-release@v1 28 | with: 29 | body_path: "body.md" 30 | tag_name: v${{ env.REVISION }} 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /setup/systemd/vtt-workers.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=VK to Telegram forwarding service 3 | After=network.target 4 | After=rabbitmq-server.service 5 | Wants=rabbitmq-server.service 6 | Wants=vtt-dbc-scheduler.service 7 | 8 | [Service] 9 | Type=forking 10 | User=vtt-user 11 | Group=vtt-user 12 | EnvironmentFile=/etc/default/vtt-celery.conf 13 | WorkingDirectory=/srv/vk-to-tgm 14 | ExecStart=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi start $CELERYD_NODES \ 15 | --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ 16 | --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' 17 | ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait $CELERYD_NODES \ 18 | --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ 19 | --loglevel="${CELERYD_LOG_LEVEL}"' 20 | ExecReload=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi restart $CELERYD_NODES \ 21 | --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ 22 | --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' 23 | Restart=always 24 | 25 | [Install] 26 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | source functions.sh 4 | 5 | prompt_text "Enter installation path to delete" "^/.+$" "/srv/vk-to-tgm" 6 | INSTALL_PATH=$ret_val 7 | 8 | prompt_text "Enter app's owner" "^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\$)$" "vtt-user" 9 | VTT_USER=$ret_val 10 | 11 | echo "Stopping services..." 12 | sudo systemctl stop vtt-cb-receiver vtt-workers vtt-dbc-scheduler vtt-tgm-bot 13 | sudo systemctl disable vtt-cb-receiver vtt-workers vtt-dbc-scheduler vtt-tgm-bot 14 | 15 | echo "Deleting service configs..." 16 | sudo rm -f "/etc/systemd/system/vtt-cb-receiver.service" \ 17 | "/etc/systemd/system/vtt-workers.service" \ 18 | "/etc/systemd/system/vtt-dbc-scheduler.service" \ 19 | "/etc/systemd/system/vtt-tgm-bot.service" \ 20 | "/etc/default/vtt-workers.conf" 21 | 22 | sudo systemctl daemon-reload 23 | 24 | echo "Deleting '$INSTALL_PATH'..." 25 | sudo rm -rf "$INSTALL_PATH" 26 | 27 | echo "Deleting user '$VTT_USER'..." 28 | sudo userdel "$VTT_USER" 29 | 30 | if [ -f /etc/nginx/sites-enabled/vtt-cb-receiver.conf ]; then 31 | echo "Deleting Nginx site config..." 32 | sudo rm /etc/nginx/sites-enabled/vtt-cb-receiver.conf 33 | sudo systemctl reload nginx 34 | fi 35 | 36 | echo "Uninstallation completed." 37 | -------------------------------------------------------------------------------- /app/logging_config.yaml: -------------------------------------------------------------------------------- 1 | version: 1 2 | formatters: 3 | default: 4 | (): uvicorn.logging.DefaultFormatter 5 | fmt: '%(levelprefix)s %(asctime)-8s %(name)-15s %(message)s' 6 | use_colors: None 7 | file: 8 | format: '%(levelname)s %(asctime)-8s %(name)-15s %(message)s' 9 | access: 10 | (): uvicorn.logging.AccessFormatter 11 | fmt: '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s' 12 | handlers: 13 | default: 14 | formatter: default 15 | class: logging.StreamHandler 16 | stream: ext://sys.stderr 17 | access: 18 | formatter: access 19 | class: logging.StreamHandler 20 | stream: ext://sys.stdout 21 | app_default: 22 | formatter: default 23 | class: logging.StreamHandler 24 | rotating_file: 25 | formatter: file 26 | filename: logs/vtt-cb-receiver.log 27 | maxBytes: 1000000 28 | backupCount: 5 29 | class: logging.handlers.RotatingFileHandler 30 | loggers: 31 | uvicorn: 32 | handlers: [default, rotating_file] 33 | level: INFO 34 | uvicorn.error: 35 | level: INFO 36 | uvicorn.access: 37 | handlers": [access, rotating_file] 38 | level: INFO 39 | propagate: False 40 | app: 41 | handlers: [app_default, rotating_file] 42 | level: INFO -------------------------------------------------------------------------------- /setup/configs/vtt-celery.conf: -------------------------------------------------------------------------------- 1 | # Name of nodes to start 2 | # here we have a single node 3 | # CELERYD_NODES="w1" 4 | # or we could have three nodes: 5 | # CELERYD_NODES="w1 w2 w3" 6 | CELERYD_NODES="vtt-worker-wall vtt-worker-pl vtt-worker-dbc -Q:1 vtt-wall -Q:2 vtt-playlist -Q:3 celery" 7 | 8 | # Absolute or relative path to the 'celery' command: 9 | # CELERY_BIN="/usr/local/bin/celery" 10 | # CELERY_BIN="/virtualenvs/def/bin/celery" 11 | CELERY_BIN="/srv/vk-to-tgm/.venv/bin/celery" 12 | 13 | # App instance to use 14 | # comment out this line if you don't use an app 15 | # CELERY_APP="proj" 16 | # or fully qualified: 17 | CELERY_APP="app.celery_worker" 18 | 19 | # How to call manage.py 20 | CELERYD_MULTI="multi" 21 | 22 | # Extra command-line arguments to the worker 23 | CELERYD_OPTS="--time-limit=3600 --pool=solo" 24 | 25 | # - %n will be replaced with the first part of the nodename. 26 | # - %I will be replaced with the current child process index 27 | # and is important when using the prefork pool to avoid race conditions. 28 | CELERYD_PID_FILE="logs/run/%n.pid" 29 | CELERYD_LOG_FILE="logs/%n%I.log" 30 | CELERYD_LOG_LEVEL="INFO" 31 | 32 | # If enabled pid and log directories will be created if missing, 33 | # and owned by the userid/group configured. 34 | CELERY_CREATE_DIRS=1 35 | 36 | # you may wish to add these options for Celery Beat 37 | CELERYBEAT_PID_FILE="logs/run/vtt-dbc-scheduler.pid" 38 | CELERYBEAT_LOG_FILE="logs/vtt-dbc-scheduler.log" 39 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "vk-to-tgm" 3 | version = "1.2.1" 4 | description = "An application that forwards wall posts and playlists from VK community to Telegram channel" 5 | license = "GPL-3.0-or-later" 6 | authors = ["Ilia Boyazitov"] 7 | readme = "README.md" 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.8" 11 | fastapi = "^0.75.2" 12 | vkbottle = "^4.2.2" 13 | uvicorn = {extras = ["standard"], version = "^0.17.6"} 14 | ffmpeg-python = "^0.2.0" 15 | gunicorn = "^20.1.0" 16 | celery = "^5.2.6" 17 | SQLAlchemy = "^1.4.35" 18 | Telethon = "^1.38.0" 19 | cryptg = "^0.2.post4" 20 | Pillow = "^9.1.0" 21 | aiohttp = "^3.8.1" 22 | hachoir = "^3.1.2" 23 | eyed3 = "^0.9.6" 24 | aiofiles = "^0.8.0" 25 | vkaudiotoken = {git = "https://github.com/Bizordec/vkaudiotoken-python.git"} 26 | 27 | [tool.poetry.dev-dependencies] 28 | black = "^22.3.0" 29 | flake8 = "^4.0.1" 30 | isort = "^5.10.1" 31 | flake8-bugbear = "^22.4.25" 32 | flake8-comprehensions = "^3.8.0" 33 | flake8-tidy-imports = "^4.6.0" 34 | sqlalchemy2-stubs = "^0.0.2-alpha.22" 35 | bandit = "^1.7.4" 36 | Babel = "^2.10.1" 37 | 38 | [tool.poetry.group.dev.dependencies] 39 | commitizen = "^3.6.0" 40 | 41 | [tool.black] 42 | line-length = 120 43 | 44 | [tool.isort] 45 | profile = "black" 46 | line_length = 120 47 | multi_line_output = 3 48 | include_trailing_comma = true 49 | 50 | [tool.commitizen] 51 | name = "cz_conventional_commits" 52 | tag_format = "v$version" 53 | version_scheme = "semver" 54 | version_provider = "poetry" 55 | update_changelog_on_bump = true 56 | 57 | [build-system] 58 | requires = ["poetry-core>=1.0.0"] 59 | build-backend = "poetry.core.masonry.api" 60 | -------------------------------------------------------------------------------- /app/bot/main.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import os 4 | import sys 5 | from logging.handlers import RotatingFileHandler 6 | 7 | from aiohttp import ClientSession 8 | from telethon import TelegramClient 9 | from vkaudiotoken import supported_clients 10 | from vkbottle import AiohttpClient 11 | from vkbottle.api.api import API 12 | 13 | from app.bot import plugins 14 | from app.config import settings 15 | from app.utils.vk import VkLangRequestValidator 16 | 17 | logging.basicConfig( 18 | format="%(levelname)s: %(asctime)s [%(name)s] %(message)s", 19 | level=logging.INFO, 20 | handlers=[ 21 | RotatingFileHandler(filename="logs/vtt-bot.log", maxBytes=1000000, backupCount=5), 22 | logging.StreamHandler(), 23 | ], 24 | ) 25 | 26 | logger = logging.getLogger("bot.main") 27 | 28 | 29 | async def main(): 30 | vk_api = API( 31 | token=settings.KATE_TOKEN, 32 | http_client=AiohttpClient( 33 | session=ClientSession( 34 | headers={"User-agent": supported_clients.KATE.user_agent}, 35 | ), 36 | ), 37 | ) 38 | vk_api.request_validators.append(VkLangRequestValidator()) 39 | 40 | client = TelegramClient("tgm_sessions/tgm_search_client", settings.TGM_API_ID, settings.TGM_API_HASH) 41 | await client.start(phone=lambda: settings.TGM_CLIENT_PHONE) 42 | 43 | bot = TelegramClient("tgm_sessions/tgm_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 44 | await bot.start(bot_token=settings.TGM_BOT_TOKEN) 45 | 46 | async with client: 47 | await plugins.init(bot, client, vk_api) 48 | await bot.run_until_disconnected() 49 | await vk_api.http_client.close() 50 | 51 | 52 | if __name__ == "__main__": 53 | try: 54 | asyncio.run(main()) 55 | except KeyboardInterrupt: 56 | logger.warning("Program interrupted by user.") 57 | try: 58 | sys.exit(0) 59 | except SystemExit: 60 | os._exit(0) 61 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # Create .env file based on this file and fill the variables. 2 | # cp .env.example .env 3 | 4 | # VK login and password. 5 | # Required if both KATE_TOKEN and VK_OFFICIAL_TOKEN not specified. 6 | VK_LOGIN= 7 | VK_PASSWORD= 8 | 9 | # Numeric id of VK community. 10 | # Required. 11 | VK_COMMUNITY_ID= 12 | 13 | # VK community token. 14 | # To obtain it: 15 | # 1. Go to your community page; 16 | # 2. "Manage" -> "API usage" -> "Access usage" -> "Create token"; 17 | # 3. Select "Allow access to community management"; 18 | # 4. Copy token and paste here. 19 | # Required. 20 | VK_COMMUNITY_TOKEN= 21 | 22 | # Title for your server (1-14 characters). 23 | # Required. 24 | VK_SERVER_TITLE= 25 | 26 | # Numeric id of main Telegram channel. 27 | # Required if channel is private. 28 | TGM_CHANNEL_ID= 29 | 30 | # Name of main Telegram channel. 31 | # Required if TGM_CHANNEL_ID not specified. 32 | TGM_CHANNEL_USERNAME= 33 | 34 | # Numeric id of playlist Telegram channel. 35 | # Optional if you don't need playlist channel, 36 | # otherwise required if channel is private. 37 | TGM_PL_CHANNEL_ID= 38 | 39 | # Name of playlist Telegram channel. 40 | # Optional if you don't need playlist channel, 41 | # otherwise required if TGM_PL_CHANNEL_ID not specified. 42 | TGM_PL_CHANNEL_USERNAME= 43 | 44 | # Phone number of Telegram client account. 45 | # Required if you need Telegram bot. 46 | TGM_CLIENT_PHONE= 47 | 48 | # Token of Telegram bot. 49 | # Read more: https://core.telegram.org/bots#6-botfather 50 | # Required. 51 | TGM_BOT_TOKEN= 52 | 53 | # Id and hash for your Telegram application. 54 | # Read more: https://core.telegram.org/api/obtaining_api_id 55 | # Required. 56 | TGM_API_ID= 57 | TGM_API_HASH= 58 | 59 | # Server URL, which will be used by VK for callback events. 60 | # Required. 61 | SERVER_URL= 62 | 63 | # VK user tokens. 64 | # Required if VK_LOGIN and VK_PASSWORD not specified, otherwise tokens will be auto generated. 65 | KATE_TOKEN= 66 | VK_OFFICIAL_TOKEN= 67 | 68 | # App's language 69 | # Available: "en", "ru" 70 | # Default: "en" 71 | VTT_LANGUAGE= 72 | 73 | # VK API language 74 | # Default: value of VTT_LANGUAGE 75 | VK_API_LANGUAGE= 76 | 77 | # Nginx server_name 78 | NGINX_HOST= 79 | 80 | # Ingore VK ad posts 81 | # Default: True 82 | VK_IGNORE_ADS= 83 | -------------------------------------------------------------------------------- /app/sign_in.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import sys 4 | 5 | from telethon.client.telegramclient import TelegramClient 6 | 7 | from app.config import settings 8 | from app.utils.telegram import get_entity_by_id 9 | 10 | logger = logging.getLogger("app.sign_in") 11 | 12 | 13 | async def get_channel_entities(client: TelegramClient): 14 | logger.info("Getting main channel entity...") 15 | entity = await get_entity_by_id( 16 | client, 17 | settings.TGM_CHANNEL_ID, 18 | ) 19 | if not entity: 20 | sys.exit(1) 21 | 22 | if settings.TGM_PL_CHANNEL_ID: 23 | logger.info("Getting playlist channel entity...") 24 | entity = await get_entity_by_id( 25 | client, 26 | settings.TGM_PL_CHANNEL_ID, 27 | ) 28 | if not entity: 29 | sys.exit(1) 30 | 31 | 32 | async def main(): 33 | logger.info("Signing into Telegram...") 34 | tgm_search_client = TelegramClient("tgm_sessions/tgm_search_client", settings.TGM_API_ID, settings.TGM_API_HASH) 35 | await tgm_search_client.start(phone=lambda: settings.TGM_CLIENT_PHONE) 36 | await get_channel_entities(tgm_search_client) 37 | await tgm_search_client.disconnect() 38 | 39 | tgm_bot = TelegramClient("tgm_sessions/tgm_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 40 | await tgm_bot.start(bot_token=settings.TGM_BOT_TOKEN) 41 | await get_channel_entities(tgm_bot) 42 | await tgm_bot.disconnect() 43 | 44 | worker_bot = TelegramClient("tgm_sessions/worker_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 45 | await worker_bot.start(bot_token=settings.TGM_BOT_TOKEN) 46 | await get_channel_entities(worker_bot) 47 | await worker_bot.disconnect() 48 | 49 | if settings.TGM_PL_CHANNEL_ID: 50 | worker_pl_bot = TelegramClient("tgm_sessions/worker_pl_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 51 | await worker_pl_bot.start(bot_token=settings.TGM_BOT_TOKEN) 52 | await get_channel_entities(worker_pl_bot) 53 | await worker_pl_bot.disconnect() 54 | 55 | logger.info("Done.") 56 | 57 | 58 | if __name__ == "__main__": 59 | logging.basicConfig(format="%(levelname)s: %(asctime)s [%(name)s] %(message)s", level=logging.INFO, force=True) 60 | asyncio.run(main()) 61 | -------------------------------------------------------------------------------- /app/main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | from fastapi import BackgroundTasks, FastAPI, Response 5 | from vkbottle_types.objects import CallbackType, WallPostType, WallWallpostFull 6 | 7 | from app.celery_worker import forward_wall 8 | from app.config import settings 9 | from app.schemas.vk import VkCallback 10 | from app.utils.database import VttTaskType, get_queued_task 11 | from app.utils.vk import setup_vk_server 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | app = FastAPI() 16 | 17 | 18 | @app.on_event("startup") 19 | async def on_startup(): 20 | await setup_vk_server() 21 | 22 | 23 | @app.post("/") 24 | def read_vk(req: VkCallback, bg: BackgroundTasks): 25 | if req.secret != settings.VK_SERVER_SECRET: 26 | logger.warning(f"Unauthorized request: {req}") 27 | return Response(status_code=401) 28 | 29 | req_type = req.type 30 | logger.info(f"[VK] New event: {req_type}") 31 | if req_type == CallbackType.CONFIRMATION: 32 | confirmation_token = os.getenv("VK_CONFIRM_CODE") 33 | logger.info(f'[VK] Response with confirmation code "{confirmation_token}" has been sent.') 34 | return Response(confirmation_token) 35 | if req_type == CallbackType.WALL_POST_NEW: 36 | post = WallWallpostFull(**req.object) 37 | if post.marked_as_ads and settings.VK_IGNORE_ADS: 38 | logger.info('[VK] Response with "ok" string has been sent.') 39 | return Response("ok") 40 | if post.post_type in [ 41 | WallPostType.POST, 42 | WallPostType.REPLY, 43 | WallPostType.PHOTO, 44 | WallPostType.VIDEO, 45 | ] and not (post.donut and post.donut.is_donut): 46 | owner_id = post.owner_id 47 | post_id = post.id 48 | if owner_id and post_id: 49 | logger.info(f"[VK] New post ({owner_id}_{post_id}).") 50 | if get_queued_task(owner_id, post_id, VttTaskType.wall): 51 | logger.warning(f"[VK] Post {owner_id}_{post_id} already exists.") 52 | else: 53 | forward_wall.delay( 54 | owner_id=owner_id, 55 | wall_id=post_id, 56 | ) 57 | logger.info('[VK] Response with "ok" string has been sent.') 58 | return Response("ok") 59 | 60 | 61 | if __name__ == "__main__": 62 | import uvicorn 63 | 64 | uvicorn.run( 65 | "app.main:app", 66 | host="127.0.0.1", 67 | port=8000, 68 | reload=True, 69 | log_config="logging_config.yaml", 70 | use_colors=True, 71 | log_level="debug", 72 | ) 73 | -------------------------------------------------------------------------------- /app/utils/telegram.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List, Tuple, Union 3 | 4 | from telethon.client.telegramclient import TelegramClient 5 | from telethon.extensions import html 6 | from telethon.hints import Entity 7 | from telethon.tl.types import Chat, TypeInputPeer, TypeMessageEntity 8 | from telethon.utils import split_text as telethon_split_text 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | MAX_MESSAGE_LENGTH = 4096 13 | MAX_CAPTION_LENGTH = 1024 14 | 15 | 16 | def split_text(header_text: str, footer_text: str = "", is_caption=False) -> List[Tuple[str, List[TypeMessageEntity]]]: 17 | tgm_limit = MAX_CAPTION_LENGTH if is_caption else MAX_MESSAGE_LENGTH 18 | 19 | p_header_text, p_header_entities = html.parse(header_text) 20 | p_footer_text, _ = html.parse(footer_text) 21 | main_text = header_text 22 | rest_texts = [] 23 | 24 | newline_offset = 2 if footer_text.startswith("\n\n") else 0 25 | 26 | strip_len = tgm_limit - newline_offset - len(p_footer_text) 27 | if len(p_header_text) > strip_len: 28 | s_header_text, s_header_entities = next( 29 | telethon_split_text(p_header_text, p_header_entities, limit=strip_len), 30 | ("", None), 31 | ) 32 | if s_header_text and s_header_entities is not None: 33 | main_text = html.unparse(s_header_text, s_header_entities) 34 | main_text_offset = len(main_text) 35 | p_rest_text, p_rest_entities = html.parse(header_text[main_text_offset:]) 36 | rest_texts = list(telethon_split_text(p_rest_text, p_rest_entities)) 37 | 38 | main_text += footer_text 39 | return [html.parse(main_text)] + rest_texts 40 | 41 | 42 | def get_html_link(href: str, title: str): 43 | return f'{html.escape(title)}' 44 | 45 | 46 | def get_message_link(entity: Entity, message_id) -> str: 47 | if isinstance(entity, Chat): 48 | return "" 49 | channel = entity.username 50 | if channel is None: 51 | channel = f"c/{entity.id}" 52 | return f"https://t.me/{channel}/{message_id}" 53 | 54 | 55 | async def get_entity_by_username( 56 | client: TelegramClient, 57 | channel_username: str, 58 | ) -> Union[TypeInputPeer, None]: 59 | entity = None 60 | try: 61 | entity = await client.get_input_entity(channel_username) 62 | except ValueError: 63 | logger.critical("Failed to get entity! If your channel is private, you can only use the id.") 64 | return entity 65 | 66 | 67 | async def get_entity_by_id( 68 | client: TelegramClient, 69 | channel_id: int, 70 | ) -> Union[TypeInputPeer, None]: 71 | entity = None 72 | try: 73 | entity = await client.get_input_entity(channel_id) 74 | except ValueError: 75 | logger.critical("Failed to get entity! Add bot to your channel as an admin and try again.") 76 | return entity 77 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Telegram Bot", 9 | "type": "python", 10 | "request": "launch", 11 | "module": "app.bot.main", 12 | "justMyCode": false 13 | }, 14 | { 15 | "name": "Python: VK Callback receiver", 16 | "type": "python", 17 | "request": "launch", 18 | "module": "uvicorn", 19 | "args": [ 20 | "app.main:app", 21 | "--log-config", 22 | "app/logging_config.yaml", 23 | "--log-level", 24 | "debug", 25 | ], 26 | "jinja": true, 27 | "justMyCode": false 28 | }, 29 | { 30 | "name": "Python: Wall worker", 31 | "type": "python", 32 | "request": "launch", 33 | "module": "celery", 34 | "console": "integratedTerminal", 35 | "args": [ 36 | "-A", 37 | "app.celery_worker", 38 | "worker", 39 | "-Q", 40 | "vtt-wall", 41 | "-l", 42 | "info", 43 | "-P", 44 | "solo", 45 | ], 46 | "justMyCode": false 47 | }, 48 | { 49 | "name": "Python: Playlist worker", 50 | "type": "python", 51 | "request": "launch", 52 | "module": "celery", 53 | "console": "integratedTerminal", 54 | "args": [ 55 | "-A", 56 | "app.celery_worker", 57 | "worker", 58 | "-Q", 59 | "vtt-playlist", 60 | "-l", 61 | "info", 62 | "-P", 63 | "solo", 64 | ], 65 | "justMyCode": false 66 | }, 67 | { 68 | "name": "Python: DB cleanup scheduler", 69 | "type": "python", 70 | "request": "launch", 71 | "module": "celery", 72 | "console": "integratedTerminal", 73 | "args": [ 74 | "-A", 75 | "app.celery_worker", 76 | "beat", 77 | "-l", 78 | "debug", 79 | ], 80 | "justMyCode": false 81 | }, 82 | { 83 | "name": "Python: Current File", 84 | "type": "python", 85 | "request": "launch", 86 | "program": "${file}", 87 | "console": "integratedTerminal", 88 | "env": { 89 | "PYTHONPATH": "${workspaceFolder}:${env:PYTHONPATH}" 90 | }, 91 | "justMyCode": false 92 | }, 93 | ] 94 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | volumes: 3 | vtt: 4 | networks: 5 | net_vtt: 6 | services: 7 | sign_in: 8 | build: . 9 | volumes: 10 | - vtt:/vk-to-tgm/tgm_sessions/ 11 | - ./.env:/vk-to-tgm/.env 12 | profiles: 13 | - sign_in 14 | command: python -m app.sign_in 15 | rabbitmq: 16 | image: rabbitmq:3.10.5-alpine 17 | networks: 18 | - net_vtt 19 | cb-receiver: 20 | build: . 21 | restart: always 22 | environment: 23 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 24 | volumes: 25 | - vtt:/vk-to-tgm/tgm_sessions/ 26 | - ./.env:/vk-to-tgm/.env 27 | command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --log-config app/logging_config.yaml 28 | depends_on: 29 | - rabbitmq 30 | networks: 31 | - net_vtt 32 | ports: 33 | - "127.0.0.1:8000:8000" 34 | tgm-bot: 35 | build: . 36 | restart: always 37 | environment: 38 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 39 | volumes: 40 | - vtt:/vk-to-tgm/tgm_sessions/ 41 | - ./.env:/vk-to-tgm/.env 42 | command: python3 -m app.bot.main 43 | depends_on: 44 | - rabbitmq 45 | networks: 46 | - net_vtt 47 | worker-wall: 48 | build: . 49 | restart: always 50 | environment: 51 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 52 | volumes: 53 | - vtt:/vk-to-tgm/tgm_sessions/ 54 | - ./.env:/vk-to-tgm/.env 55 | command: celery -A app.celery_worker worker -n vtt-worker-wall@%%h -Q vtt-wall --pool=solo --loglevel=INFO 56 | depends_on: 57 | - rabbitmq 58 | networks: 59 | - net_vtt 60 | worker-pl: 61 | build: . 62 | restart: always 63 | environment: 64 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 65 | volumes: 66 | - vtt:/vk-to-tgm/tgm_sessions/ 67 | - ./.env:/vk-to-tgm/.env 68 | command: celery -A app.celery_worker worker -n vtt-worker-pl@%%h -Q vtt-playlist --pool=solo --loglevel=INFO 69 | depends_on: 70 | - rabbitmq 71 | networks: 72 | - net_vtt 73 | profiles: 74 | - with_pl 75 | worker-dbc: 76 | build: . 77 | restart: always 78 | environment: 79 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 80 | volumes: 81 | - vtt:/vk-to-tgm/tgm_sessions/ 82 | - ./.env:/vk-to-tgm/.env 83 | command: celery -A app.celery_worker worker -n vtt-worker-dbc@%%h -Q celery --pool=solo --loglevel=INFO 84 | depends_on: 85 | - rabbitmq 86 | networks: 87 | - net_vtt 88 | dbc-scheduler: 89 | build: . 90 | restart: always 91 | environment: 92 | - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// 93 | volumes: 94 | - vtt:/vk-to-tgm/tgm_sessions/ 95 | - ./.env:/vk-to-tgm/.env 96 | command: celery -A app.celery_worker beat --loglevel=INFO --logfile=logs/vtt-dbc-scheduler.log 97 | depends_on: 98 | - rabbitmq 99 | networks: 100 | - net_vtt 101 | -------------------------------------------------------------------------------- /vtt-cli.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cli_help() { 4 | cli_name=${0##*/} 5 | echo " 6 | vk-to-tgm CLI 7 | Usage: ./$cli_name [command] 8 | Commands: 9 | set_env, se Set .env file 10 | receiver, r Run callback receiver 11 | bot, b Run Telegram bot 12 | wall_worker, ww Run Celery wall worker 13 | playlist_worker, pw Run Celery playlist worker 14 | dbcleanup_worker, dw Run Celery db cleanup worker 15 | local_tunnel, lt Run local tunnel 16 | sign_in, si Create VK tokens and Telegram sessions 17 | upd_locale, ul Update locales 18 | setup_nginx, su Setup Nginx config 19 | * Help 20 | " 21 | exit 1 22 | } 23 | 24 | venv() { 25 | if [ -d .venv ]; then 26 | if command -v python3 &> /dev/null; then 27 | source .venv/bin/activate 28 | else 29 | echo "Python3 not installed!" || exit 1 30 | fi 31 | else 32 | if command -v poetry &> /dev/null; then 33 | poetry install 34 | source .venv/bin/activate 35 | elif command -v python3 &> /dev/null; then 36 | python3 -m venv .venv 37 | source .venv/bin/activate 38 | python3 -m pip install wheel 39 | python3 -m pip install -r requirements.txt 40 | else 41 | echo "Python3 not installed!" || exit 1 42 | fi 43 | fi 44 | } 45 | 46 | case $1 in 47 | set_env|fe) 48 | source functions.sh 49 | set_env 50 | ;; 51 | receiver|r) 52 | venv 53 | uvicorn app.main:app --port 8000 --reload --log-config app/logging_config.yaml 54 | ;; 55 | bot|b) 56 | venv 57 | python3 -m app.bot.main 58 | ;; 59 | wall_worker|ww) 60 | venv 61 | celery -A app.celery_worker worker -n vtt-worker-wall@%%h -Q vtt-wall --pool=solo --loglevel=INFO 62 | ;; 63 | playlist_worker|pw) 64 | venv 65 | celery -A app.celery_worker worker -n vtt-worker-pl@%%h -Q vtt-playlist --pool=solo --loglevel=INFO 66 | ;; 67 | dbcleanup_worker|dw) 68 | venv 69 | celery -A app.celery_worker worker -B -n vtt-worker-dbc@%%h -Q celery --pool=solo --loglevel=INFO 70 | ;; 71 | local_tunnel|lt) 72 | cd tunnel/ || exit 1 73 | if [ ! -f node_modules/localtunnel/localtunnel.js ]; then 74 | npm install 75 | fi 76 | port=$2 77 | npm start "$port" 78 | ;; 79 | sign_in|si) 80 | venv 81 | python3 -m app.sign_in 82 | ;; 83 | upd_locale|ul) 84 | venv 85 | pybabel extract --mapping babel.cfg -o locale/base.pot app/ 86 | pybabel update -l en -i locale/base.pot -D vtt -d locale/ 87 | pybabel update -l ru -i locale/base.pot -D vtt -d locale/ 88 | pybabel compile -D vtt -d locale/ 89 | ;; 90 | setup_nginx|su) 91 | source .env 92 | source functions.sh 93 | setup_nginx 94 | ;; 95 | *) 96 | cli_help 97 | esac -------------------------------------------------------------------------------- /app/utils/database.py: -------------------------------------------------------------------------------- 1 | import enum 2 | from typing import Optional, Union 3 | 4 | from celery import states 5 | from celery.app.task import Context 6 | from celery.backends.database import DatabaseBackend, retry, session_cleanup 7 | from celery.backends.database.models import ResultModelBase, Task 8 | from sqlalchemy import Column, Enum, ForeignKey, Integer, event 9 | from sqlalchemy.engine import Engine 10 | from sqlalchemy.sql.expression import desc 11 | 12 | 13 | @event.listens_for(Engine, "connect") 14 | def set_sqlite_pragma(dbapi_connection, connection_record): 15 | cursor = dbapi_connection.cursor() 16 | cursor.execute("PRAGMA foreign_keys=ON") 17 | cursor.close() 18 | 19 | 20 | class VttTaskType(enum.Enum): 21 | wall = 0 22 | playlist = 1 23 | unknown = 2 24 | 25 | 26 | class VttTask(ResultModelBase): 27 | __tablename__ = "vtt_task" 28 | 29 | id = Column(Integer, primary_key=True) 30 | vk_type = Column(Enum(VttTaskType)) 31 | vk_owner_id = Column(Integer) 32 | vk_id = Column(Integer) 33 | task_id = Column(Integer, ForeignKey(Task.id, ondelete="CASCADE")) 34 | 35 | def __repr__(self): 36 | return f"" 37 | 38 | 39 | @retry 40 | def vtt_store_result( 41 | vk_type: VttTaskType, 42 | vk_owner_id: int, 43 | vk_id: int, 44 | task_uuid: str, 45 | result, 46 | state: str, 47 | traceback: Optional[str] = None, 48 | request: Optional[Context] = None, 49 | **kwargs, 50 | ) -> None: 51 | """Store return value and state of an executed task.""" 52 | from app.celery_worker import worker 53 | 54 | backend: DatabaseBackend = worker.backend 55 | celery_task = backend.task_cls 56 | session = backend.ResultSession() 57 | with session_cleanup(session): 58 | task = list(session.query(celery_task).filter(celery_task.task_id == task_uuid)) 59 | task = task and task[0] 60 | if not task: 61 | task = celery_task(task_uuid) 62 | task.task_id = task_uuid 63 | session.add(task) 64 | session.flush() 65 | 66 | # Add entry to vtt_task table 67 | session.add(VttTask(vk_type=vk_type.name, vk_owner_id=vk_owner_id, vk_id=vk_id, task_id=task.id)) 68 | session.flush() 69 | 70 | backend._update_result(task, result, state, traceback=traceback, request=request) 71 | session.commit() 72 | 73 | 74 | def get_queued_task(vk_owner_id: int, vk_id: int, vk_type: VttTaskType): 75 | from app.celery_worker import worker 76 | 77 | backend: DatabaseBackend = worker.backend 78 | celery_task = backend.task_cls 79 | session = backend.ResultSession() 80 | with session_cleanup(session): 81 | queued_task: Union[celery_task, None] = ( 82 | session.query(celery_task) 83 | .join(VttTask) 84 | .filter( 85 | (VttTask.vk_owner_id == vk_owner_id) 86 | & (VttTask.vk_id == vk_id) 87 | & (VttTask.vk_type == vk_type.name) 88 | & ((celery_task.status == "SENT") | (celery_task.status == states.STARTED)) 89 | ) 90 | .order_by(desc(celery_task.date_done)) 91 | .first() 92 | ) 93 | return queued_task 94 | -------------------------------------------------------------------------------- /app/bot/plugins/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import importlib 3 | import inspect 4 | import logging 5 | import os 6 | import time 7 | 8 | from telethon import events 9 | 10 | from app.bot.plugins.common import NewMessageEvent, check_permission, check_state 11 | from app.bot.state_manager import State 12 | from app.config import _, settings 13 | 14 | INCORRECT_LINK = ( 15 | _("INCORRECT_LINK") 16 | + ( 17 | ":\n" 18 | "\nvk.com/wall{owner_id}_{id}" 19 | "\nm.vk.com/wall{owner_id}_{id}" 20 | "\nhttps://vk.com/wall{owner_id}_{id}" 21 | "\nhttps://m.vk.com/wall{owner_id}_{id}" 22 | ) 23 | + ( 24 | "\nvk.com/music/album/{owner_id}_{id}" 25 | "\nvk.com/music/playlist/{owner_id}_{id}" 26 | "\nm.vk.com/audio?act=audio_playlist{owner_id}_{id}" 27 | "\nhttps://vk.com/music/album/{owner_id}_{id}" 28 | "\nhttps://vk.com/music/playlist/{owner_id}_{id}" 29 | "\nhttps://m.vk.com/audio?act=audio_playlist{owner_id}_{id}" 30 | ) 31 | if settings.TGM_PL_CHANNEL_ID 32 | else "" 33 | ) 34 | 35 | logger = logging.getLogger(__name__) 36 | 37 | 38 | async def init(bot, client, vk_api): 39 | plugins = [ 40 | # Dynamically import 41 | importlib.import_module(".", f"{__name__}.{file[:-3]}") 42 | # All the files in the current directory 43 | for file in os.listdir(os.path.dirname(__file__)) 44 | # If they start with a letter and are Python files 45 | if file[0].isalpha() and file.endswith(".py") 46 | ] 47 | 48 | # Keep a mapping of module name to module for easy access inside the plugins 49 | modules = {m.__name__.split(".")[-1]: m for m in plugins} 50 | 51 | if not settings.TGM_PL_CHANNEL_ID: 52 | modules.pop("playlist", None) 53 | 54 | # All kwargs provided to get_init_args are those that plugins may access 55 | to_init = (get_init_coro(plugin, bot=bot, client=client, vk_api=vk_api, modules=modules) for plugin in plugins) 56 | 57 | # Plugins may not have a valid init so those need to be filtered out 58 | await asyncio.gather(*(filter(None, to_init))) 59 | 60 | @bot.on(events.NewMessage(func=lambda e: check_state(e, State.WAITING_FOR_LINK))) 61 | async def incorrect_link(event: NewMessageEvent): 62 | if not await check_permission(event): 63 | raise events.StopPropagation 64 | 65 | await event.respond(INCORRECT_LINK) 66 | raise events.StopPropagation 67 | 68 | 69 | def get_init_coro(plugin, **kwargs): 70 | p_init = getattr(plugin, "init", None) 71 | if not callable(p_init): 72 | return 73 | 74 | result_kwargs = {} 75 | sig = inspect.signature(p_init) 76 | for param in sig.parameters: 77 | if param in kwargs: 78 | result_kwargs[param] = kwargs[param] 79 | else: 80 | logger.error("Plugin %s has unknown init parameter %s", plugin.__name__, param.__name__) 81 | return 82 | 83 | return _init_plugin(plugin, result_kwargs) 84 | 85 | 86 | async def _init_plugin(plugin, kwargs): 87 | try: 88 | logger.warning(f"Loading plugin {plugin.__name__}…") 89 | start = time.time() 90 | await plugin.init(**kwargs) 91 | took = time.time() - start 92 | logger.warning(f"Loaded plugin {plugin.__name__} (took {took:.2f}s)") 93 | except Exception: 94 | logger.exception(f"Failed to load plugin {plugin}") 95 | -------------------------------------------------------------------------------- /app/schemas/vk.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from typing import Any, List, Optional 3 | 4 | from pydantic.main import BaseModel 5 | from telethon.tl.types import InputMediaPoll 6 | from vkbottle_types.objects import AudioAudio, CallbackBase 7 | 8 | 9 | class VkCallback(CallbackBase): 10 | object: Optional[Any] = None 11 | 12 | 13 | class VkApiAudio(BaseModel): 14 | id: int 15 | owner_id: int 16 | track_covers: List[str] 17 | url: str 18 | artist: str 19 | title: str 20 | duration: int 21 | 22 | 23 | class AudioPlaylistGenres(BaseModel): 24 | id: int 25 | name: str 26 | 27 | 28 | class AudioPlaylistFollowed(BaseModel): 29 | playlist_id: int 30 | owner_id: int 31 | 32 | 33 | class AudioPlaylistPhoto(BaseModel): 34 | width: int 35 | height: int 36 | photo_34: str 37 | photo_68: str 38 | photo_135: str 39 | photo_270: str 40 | photo_300: str 41 | photo_600: str 42 | photo_1200: str 43 | 44 | 45 | class AudioPlaylistPermissions(BaseModel): 46 | play: bool 47 | share: bool 48 | edit: bool 49 | follow: bool 50 | delete: bool 51 | boom_download: bool 52 | 53 | 54 | class AudioPlaylistMainArtist(BaseModel): 55 | name: str 56 | domain: str 57 | id: str 58 | 59 | 60 | class VkApiAudioPlaylist(BaseModel): 61 | id: int 62 | owner_id: int 63 | type: int 64 | title: str 65 | description: str 66 | count: int 67 | followers: int 68 | plays: int 69 | create_time: int 70 | update_time: int 71 | genres: List[AudioPlaylistGenres] 72 | is_following: bool 73 | year: Optional[int] = None 74 | followed: Optional[AudioPlaylistFollowed] = None 75 | photo: Optional[AudioPlaylistPhoto] = None 76 | thumbs: Optional[List[AudioPlaylistPhoto]] = None 77 | permissions: AudioPlaylistPermissions 78 | subtitle_badge: bool 79 | play_button: bool 80 | access_key: str 81 | is_explicit: Optional[bool] = None 82 | main_artists: Optional[List[AudioPlaylistMainArtist]] = None 83 | album_type: str 84 | 85 | 86 | class Document(BaseModel): 87 | url: str 88 | extension: str 89 | 90 | 91 | class VttVideo(BaseModel): 92 | title: str 93 | url: str 94 | platform: Optional[str] = None 95 | is_live: bool = False 96 | 97 | 98 | class AudioPlaylist(BaseModel): 99 | id: int 100 | owner_id: int 101 | access_key: Optional[str] = None 102 | full_id: str 103 | title: str 104 | description: str 105 | photo: Optional[str] = None 106 | audios: List[AudioAudio] = [] 107 | 108 | 109 | class VttMarket(BaseModel): 110 | id: int 111 | owner_id: int 112 | title: str 113 | 114 | 115 | class VttLink(BaseModel): 116 | caption: str 117 | url: str 118 | 119 | 120 | class Attachments: 121 | def __init__(self) -> None: 122 | self.audios: List[AudioAudio] = [] 123 | self.audio_playlist: typing.Optional[AudioPlaylist] = None 124 | self.photos: List[str] = [] 125 | self.documents: List[Document] = [] 126 | self.videos: List[VttVideo] = [] 127 | self.poll: typing.Optional[InputMediaPoll] = None 128 | self.market: typing.Optional[VttMarket] = None 129 | self.link: typing.Optional[VttLink] = None 130 | 131 | @property 132 | def length(self): 133 | return len(self.audios) + len(self.photos) + len(self.documents) + len(self.videos) 134 | -------------------------------------------------------------------------------- /app/bot/plugins/common.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from enum import Enum 3 | from typing import Union 4 | 5 | from telethon import events 6 | from telethon.client.telegramclient import TelegramClient 7 | from telethon.errors.rpcbaseerrors import RPCError 8 | from telethon.tl.custom.button import Button 9 | from vkbottle.api.api import API 10 | 11 | from app.bot.state_manager import State, StateManager 12 | from app.config import _, settings 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | HELLO = _("HELLO") 17 | PERMISSION_CHECK_FAILED = _("PERMISSION_CHECK_FAILED") 18 | NO_PERMISSION = _("NO_PERMISSION") 19 | WAITING_FOR_LINK = _("WAITING_FOR_LINK") 20 | CANCELLED = _("CANCELLED") 21 | CLICK_BUTTON = _("CLICK_BUTTON") 22 | 23 | 24 | # Somewhat fixed type for NewMessage event 25 | NewMessageEvent = Union[events.NewMessage.Event, events.CallbackQuery.Event] 26 | 27 | # The state in which different users are, {user_id: state} 28 | conversation_state: "dict[int, Enum]" = {} 29 | 30 | state_manager = StateManager() 31 | 32 | 33 | def check_is_chat(event: NewMessageEvent): 34 | return event.is_private 35 | 36 | 37 | async def check_state(event: NewMessageEvent, expected_state: State): 38 | if not check_is_chat(event): 39 | return False 40 | current_state = state_manager.get_info(event.sender_id)[0] 41 | return current_state == expected_state 42 | 43 | 44 | async def check_permission(event: NewMessageEvent): 45 | sender = event.sender_id 46 | client: TelegramClient = event.client 47 | try: 48 | perm = await client.get_permissions(settings.TGM_CHANNEL_ID, sender) 49 | except RPCError as error: 50 | logger.warning(f"Failed to check permissions: {error.message}") 51 | await event.respond(PERMISSION_CHECK_FAILED, buttons=Button.clear()) 52 | return False 53 | if perm and perm.post_messages: 54 | return True 55 | await event.respond(NO_PERMISSION, buttons=Button.clear()) 56 | return False 57 | 58 | 59 | async def init(bot: TelegramClient, client: TelegramClient, vk_api: API): 60 | @bot.on(events.NewMessage(pattern="/start", func=check_is_chat)) 61 | async def start(event: NewMessageEvent): 62 | await event.respond(HELLO) 63 | if not await check_permission(event): 64 | raise events.StopPropagation 65 | state_manager.set_info(event.sender_id, State.WAITING_FOR_LINK) 66 | await event.respond(WAITING_FOR_LINK) 67 | raise events.StopPropagation 68 | 69 | @bot.on(events.NewMessage(pattern="/cancel")) 70 | async def cancel(event: events.CallbackQuery.Event): 71 | state_manager.set_info(event.sender_id, State.WAITING_FOR_LINK) 72 | await event.edit(buttons=Button.clear()) 73 | await event.respond(CANCELLED) 74 | raise events.StopPropagation 75 | 76 | @bot.on(events.CallbackQuery(data=b"cancel")) 77 | async def btn_cancel(event: events.CallbackQuery.Event): 78 | state_manager.set_info(event.sender_id, State.WAITING_FOR_LINK) 79 | await event.edit(buttons=Button.clear()) 80 | await event.respond(CANCELLED) 81 | raise events.StopPropagation 82 | 83 | @bot.on(events.NewMessage(func=lambda e: check_state(e, State.WAITING_FOR_CHOISE))) 84 | async def waiting_for_choice(event: NewMessageEvent): 85 | if not await check_permission(event): 86 | raise events.StopPropagation 87 | 88 | data = state_manager.get_info(event.sender_id)[1] 89 | await event.respond(CLICK_BUTTON, reply_to=data["choice_message"]) 90 | raise events.StopPropagation 91 | -------------------------------------------------------------------------------- /locale/base.pot: -------------------------------------------------------------------------------- 1 | # Translations template for PROJECT. 2 | # Copyright (C) 2022 ORGANIZATION 3 | # This file is distributed under the same license as the PROJECT project. 4 | # FIRST AUTHOR , 2022. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: PROJECT VERSION\n" 10 | "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" 11 | "POT-Creation-Date: 2022-04-27 02:39+0300\n" 12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 | "Last-Translator: FULL NAME \n" 14 | "Language-Team: LANGUAGE \n" 15 | "MIME-Version: 1.0\n" 16 | "Content-Type: text/plain; charset=utf-8\n" 17 | "Content-Transfer-Encoding: 8bit\n" 18 | "Generated-By: Babel 2.10.1\n" 19 | 20 | #: app/bot/plugins/__init__.py:15 21 | msgid "INCORRECT_LINK" 22 | msgstr "" 23 | 24 | #: app/bot/plugins/common.py:16 25 | msgid "HELLO" 26 | msgstr "" 27 | 28 | #: app/bot/plugins/common.py:17 29 | msgid "PERMISSION_CHECK_FAILED" 30 | msgstr "" 31 | 32 | #: app/bot/plugins/common.py:18 33 | msgid "NO_PERMISSION" 34 | msgstr "" 35 | 36 | #: app/bot/plugins/common.py:19 37 | msgid "WAITING_FOR_LINK" 38 | msgstr "" 39 | 40 | #: app/bot/plugins/common.py:20 41 | msgid "CANCELLED" 42 | msgstr "" 43 | 44 | #: app/bot/plugins/common.py:21 45 | msgid "CLICK_BUTTON" 46 | msgstr "" 47 | 48 | #: app/bot/plugins/playlist.py:22 49 | msgid "PL_NOT_READY" 50 | msgstr "" 51 | 52 | #: app/bot/plugins/playlist.py:23 53 | msgid "PL_SEARCHING" 54 | msgstr "" 55 | 56 | #: app/bot/plugins/playlist.py:24 57 | msgid "PL_NOT_FOUND_IN_VK" 58 | msgstr "" 59 | 60 | #: app/bot/plugins/playlist.py:25 61 | msgid "PL_ALREADY_IN_THE_QUEUE" 62 | msgstr "" 63 | 64 | #: app/bot/plugins/playlist.py:26 65 | msgid "PL_ALREADY_STARTED" 66 | msgstr "" 67 | 68 | #: app/bot/plugins/playlist.py:27 69 | msgid "PL_FOUND_IN_TGM" 70 | msgstr "" 71 | 72 | #: app/bot/plugins/playlist.py:28 73 | msgid "PL_NOT_FOUND_IN_TGM" 74 | msgstr "" 75 | 76 | #: app/bot/plugins/playlist.py:29 77 | msgid "PL_ADDED_TO_THE_QUEUE" 78 | msgstr "" 79 | 80 | #: app/bot/plugins/playlist.py:30 81 | msgid "PL_UNKNOWN_CHANNEL" 82 | msgstr "" 83 | 84 | #: app/bot/plugins/playlist.py:31 85 | msgid "PL_YES" 86 | msgstr "" 87 | 88 | #: app/bot/plugins/playlist.py:32 89 | msgid "PL_CANCEL" 90 | msgstr "" 91 | 92 | #: app/bot/plugins/wall.py:22 93 | msgid "WALL_SEARCHING" 94 | msgstr "" 95 | 96 | #: app/bot/plugins/wall.py:23 97 | msgid "WALL_NOT_FOUND_IN_VK" 98 | msgstr "" 99 | 100 | #: app/bot/plugins/wall.py:24 101 | msgid "WALL_ALREADY_IN_THE_QUEUE" 102 | msgstr "" 103 | 104 | #: app/bot/plugins/wall.py:25 105 | msgid "WALL_ALREADY_STARTED" 106 | msgstr "" 107 | 108 | #: app/bot/plugins/wall.py:26 109 | msgid "WALL_FOUND_IN_TGM" 110 | msgstr "" 111 | 112 | #: app/bot/plugins/wall.py:27 113 | msgid "WALL_NOT_FOUND_IN_TGM" 114 | msgstr "" 115 | 116 | #: app/bot/plugins/wall.py:28 117 | msgid "WALL_ADDED_TO_THE_QUEUE" 118 | msgstr "" 119 | 120 | #: app/bot/plugins/wall.py:29 121 | msgid "WALL_UNKNOWN_CHANNEL" 122 | msgstr "" 123 | 124 | #: app/bot/plugins/wall.py:30 125 | msgid "WALL_YES" 126 | msgstr "" 127 | 128 | #: app/bot/plugins/wall.py:31 129 | msgid "WALL_CANCEL" 130 | msgstr "" 131 | 132 | #: app/handlers/playlist.py:21 133 | msgid "PL_READY" 134 | msgstr "" 135 | 136 | #: app/handlers/playlist.py:22 137 | msgid "PL_GO_TO_WALL" 138 | msgstr "" 139 | 140 | #: app/handlers/playlist.py:23 141 | msgid "PL_OF" 142 | msgstr "" 143 | 144 | #: app/handlers/text.py:17 145 | msgid "SOURCE" 146 | msgstr "" 147 | 148 | #: app/handlers/text.py:18 149 | msgid "VK_POST" 150 | msgstr "" 151 | 152 | #: app/handlers/text.py:19 153 | msgid "VK_REPOST" 154 | msgstr "" 155 | 156 | #: app/handlers/text.py:20 157 | msgid "VK_PLAYLIST" 158 | msgstr "" 159 | 160 | #: app/handlers/wall.py:32 161 | msgid "PL_SOON" 162 | msgstr "" 163 | 164 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | main() { 4 | echo "Starting vk-to-tgm installation..." 5 | 6 | if ! command -v python3 &> /dev/null; then 7 | echo "Python3 not installed! Aborting." 8 | exit 1 9 | fi 10 | 11 | if ! command -v ffmpeg &> /dev/null; then 12 | echo "FFmpeg not installed! Aborting." 13 | exit 1 14 | fi 15 | 16 | source functions.sh 17 | 18 | prompt_yn "Do you want to setup Nginx server?" 19 | NGINX_ON=$ret_val 20 | if [ "$NGINX_ON" -eq 1 ]; then 21 | if ! command -v nginx &> /dev/null; then 22 | echo "Nginx is not installed! Aborting." 23 | exit 1 24 | fi 25 | fi 26 | 27 | prompt_text "Enter installation path" "^\/.*$" "/srv/vk-to-tgm" 28 | INSTALL_PATH=$ret_val 29 | 30 | prompt_text "Enter app's owner" "^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\$)$" "vtt-user" 31 | VTT_USER=$ret_val 32 | 33 | set_env 34 | 35 | echo "Setting up services config files..." 36 | sudo cp -f "app/celeryconfig.py.example" "app/celeryconfig.py" 37 | 38 | sudo cp -f "setup/systemd/vtt-cb-receiver.service" "/etc/systemd/system/" 39 | set_setting "/etc/systemd/system/vtt-cb-receiver.service" "User" "$VTT_USER" 40 | set_setting "/etc/systemd/system/vtt-cb-receiver.service" "Group" "$VTT_USER" 41 | set_setting "/etc/systemd/system/vtt-cb-receiver.service" "WorkingDirectory" "$INSTALL_PATH" 42 | set_setting "/etc/systemd/system/vtt-cb-receiver.service" "Environment" "VTT_VENV=$INSTALL_PATH/.venv" "y" 43 | 44 | sudo cp -f "setup/systemd/vtt-workers.service" "/etc/systemd/system/" 45 | set_setting "/etc/systemd/system/vtt-workers.service" "User" "$VTT_USER" 46 | set_setting "/etc/systemd/system/vtt-workers.service" "Group" "$VTT_USER" 47 | set_setting "/etc/systemd/system/vtt-workers.service" "WorkingDirectory" "$INSTALL_PATH" 48 | 49 | sudo cp -f "setup/systemd/vtt-dbc-scheduler.service" "/etc/systemd/system/" 50 | set_setting "/etc/systemd/system/vtt-dbc-scheduler.service" "User" "$VTT_USER" 51 | set_setting "/etc/systemd/system/vtt-dbc-scheduler.service" "Group" "$VTT_USER" 52 | set_setting "/etc/systemd/system/vtt-dbc-scheduler.service" "WorkingDirectory" "$INSTALL_PATH" 53 | 54 | sudo cp -f "setup/systemd/vtt-tgm-bot.service" "/etc/systemd/system/" 55 | set_setting "/etc/systemd/system/vtt-tgm-bot.service" "User" "$VTT_USER" 56 | set_setting "/etc/systemd/system/vtt-tgm-bot.service" "Group" "$VTT_USER" 57 | set_setting "/etc/systemd/system/vtt-tgm-bot.service" "WorkingDirectory" "$INSTALL_PATH" 58 | set_setting "/etc/systemd/system/vtt-tgm-bot.service" "Environment" "VTT_VENV=$INSTALL_PATH/.venv" "y" 59 | 60 | sudo cp -f "setup/configs/vtt-celery.conf" "/etc/default/" 61 | set_setting "/etc/default/vtt-celery.conf" "CELERY_BIN" "$INSTALL_PATH/.venv/bin/celery" "y" 62 | 63 | sudo systemctl daemon-reload 64 | 65 | if [ "$NGINX_ON" -eq 1 ]; then 66 | setup_nginx 67 | fi 68 | 69 | echo "Creating user '$VTT_USER'..." 70 | if id -u "$VTT_USER" &> /dev/null; then 71 | echo "User '$VTT_USER' already exists." 72 | else 73 | sudo useradd -r "$VTT_USER" 74 | echo "User '$VTT_USER' created." 75 | fi 76 | 77 | echo "Installing in '$INSTALL_PATH'..." 78 | sudo mkdir -p "$INSTALL_PATH" 79 | if [ "$PWD" != "$(realpath -s "$INSTALL_PATH")" ]; then 80 | sudo cp -rf app/ locale/ functions.sh .env requirements.txt uninstall.sh LICENSE README.md "$INSTALL_PATH" 81 | sudo mkdir -p "$INSTALL_PATH/logs" 82 | fi 83 | sudo chown -R "$VTT_USER": "$INSTALL_PATH" 84 | 85 | cd "$INSTALL_PATH" || exit 1 86 | 87 | sudo chmod o+w "$INSTALL_PATH" 88 | 89 | echo "Installing virtual environment..." 90 | sudo rm -rf .venv 91 | python3 -m venv .venv 92 | source .venv/bin/activate 93 | python3 -m pip install wheel 94 | python3 -m pip install -r requirements.txt 95 | 96 | echo "Signing in VK and Telegram..." 97 | sudo chmod -f o+rw .env ./*.session &> /dev/null 98 | python3 -m app.sign_in 99 | sudo chmod o-rw .env ./*.session 100 | 101 | sudo chmod o-w "$INSTALL_PATH" 102 | 103 | sudo chown -R "$VTT_USER": "$INSTALL_PATH" 104 | 105 | echo "Starting services..." 106 | sudo systemctl restart vtt-cb-receiver vtt-workers vtt-dbc-scheduler vtt-tgm-bot 107 | sudo systemctl enable vtt-cb-receiver vtt-workers vtt-dbc-scheduler vtt-tgm-bot 108 | 109 | echo "Installation completed." 110 | } 111 | 112 | main 113 | -------------------------------------------------------------------------------- /app/celery_worker.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | from typing import Optional, Tuple 4 | 5 | import uvloop 6 | from celery import Celery 7 | from celery.app.task import Context 8 | from celery.signals import before_task_publish 9 | from telethon import TelegramClient 10 | 11 | from app import celeryconfig 12 | from app.config import settings 13 | from app.handlers.playlist import PlaylistHandler 14 | from app.handlers.wall import WallHandler 15 | from app.utils.database import VttTaskType, vtt_store_result 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 20 | 21 | worker = Celery("vk-to-tgm") 22 | worker.config_from_object(celeryconfig) 23 | worker.conf.broker_url = settings.CELERY_BROKER_URL 24 | worker.conf.result_backend = settings.CELERY_RESULT_BACKEND 25 | 26 | 27 | @before_task_publish.connect 28 | def set_state_on_task_call( 29 | headers: dict, 30 | body: Tuple[dict, dict, dict], 31 | routing_key: str, 32 | **kwargs, 33 | ): 34 | task_name: str = headers["task"] 35 | short_task_name = task_name.split(".")[-1] 36 | if short_task_name not in ("forward_wall", "forward_playlist"): 37 | return 38 | 39 | task_id: str = headers["id"] 40 | args: dict = body[0] 41 | _kwargs: dict = body[1] 42 | task_request = Context( 43 | task=task_name, 44 | args=args, 45 | kwargs=_kwargs, 46 | delivery_info={ 47 | "routing_key": routing_key, 48 | }, 49 | ) 50 | 51 | if short_task_name == "forward_wall": 52 | vk_type = VttTaskType.wall 53 | vk_id = _kwargs.get("wall_id") 54 | elif short_task_name == "forward_playlist": 55 | vk_type = VttTaskType.playlist 56 | vk_id = _kwargs.get("playlist_id") 57 | else: 58 | vk_type = VttTaskType.unknown 59 | vk_id = 0 60 | 61 | vtt_store_result( 62 | vk_type=vk_type, 63 | vk_owner_id=_kwargs["owner_id"], 64 | vk_id=vk_id, 65 | task_uuid=task_id, 66 | result=None, 67 | state="SENT", 68 | request=task_request, 69 | ) 70 | 71 | 72 | async def aio_forward_wall( 73 | *, 74 | owner_id: int, 75 | wall_id: int, 76 | ): 77 | wall_url = f"https://vk.com/wall{owner_id}_{wall_id}" 78 | logger.info(f"Handling wall task ({wall_url})...") 79 | 80 | tgm_bot = TelegramClient("tgm_sessions/worker_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 81 | tgm_bot.parse_mode = "html" 82 | 83 | async with await tgm_bot.start(bot_token=settings.TGM_BOT_TOKEN): 84 | async with WallHandler( 85 | owner_id, 86 | wall_id, 87 | tgm_bot, 88 | ) as handler: 89 | post_link = await handler.run() 90 | 91 | logger.info(f"Wall task ({wall_url}) done.") 92 | 93 | return post_link 94 | 95 | 96 | async def aio_forward_playlist( 97 | *, 98 | owner_id: int, 99 | playlist_id: int, 100 | access_key: Optional[str] = None, 101 | reply_channel_id: Optional[int] = None, 102 | reply_message_id: Optional[int] = None, 103 | ): 104 | pl_url = f"https://vk.com/music/playlist/{owner_id}_{playlist_id}_{access_key}" 105 | logger.info(f"Handling task for forwarding playlist {pl_url}...") 106 | 107 | tgm_bot = TelegramClient("tgm_sessions/worker_pl_bot", settings.TGM_API_ID, settings.TGM_API_HASH) 108 | tgm_bot.parse_mode = "html" 109 | 110 | async with await tgm_bot.start(bot_token=settings.TGM_BOT_TOKEN): 111 | async with PlaylistHandler( 112 | owner_id, 113 | playlist_id, 114 | access_key, 115 | tgm_bot, 116 | settings.KATE_TOKEN, 117 | main_channel_id=reply_channel_id, 118 | main_message_id=reply_message_id, 119 | ) as handler: 120 | post_link = await handler.run() 121 | 122 | logger.info(f"Task for playlist ({pl_url}) done.") 123 | 124 | return post_link 125 | 126 | 127 | @worker.task() 128 | def forward_wall( 129 | *, 130 | owner_id: int, 131 | wall_id: int, 132 | ): 133 | return asyncio.run( 134 | aio_forward_wall( 135 | owner_id=owner_id, 136 | wall_id=wall_id, 137 | ) 138 | ) 139 | 140 | 141 | @worker.task() 142 | def forward_playlist( 143 | *, 144 | owner_id: int, 145 | playlist_id: int, 146 | access_key: Optional[str] = None, 147 | reply_channel_id: Optional[int] = None, 148 | reply_message_id: Optional[int] = None, 149 | ): 150 | return asyncio.run( 151 | aio_forward_playlist( 152 | owner_id=owner_id, 153 | playlist_id=playlist_id, 154 | access_key=access_key, 155 | reply_channel_id=reply_channel_id, 156 | reply_message_id=reply_message_id, 157 | ) 158 | ) 159 | -------------------------------------------------------------------------------- /locale/en/LC_MESSAGES/vtt.po: -------------------------------------------------------------------------------- 1 | # English translations for PROJECT. 2 | # Copyright (C) 2022 ORGANIZATION 3 | # This file is distributed under the same license as the PROJECT project. 4 | # FIRST AUTHOR , 2022. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: PROJECT VERSION\n" 9 | "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" 10 | "POT-Creation-Date: 2022-04-27 02:39+0300\n" 11 | "PO-Revision-Date: 2022-04-22 21:41+0300\n" 12 | "Last-Translator: FULL NAME \n" 13 | "Language: en\n" 14 | "Language-Team: en \n" 15 | "Plural-Forms: nplurals=2; plural=(n != 1);\n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=utf-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | "Generated-By: Babel 2.10.1\n" 20 | 21 | #: app/bot/plugins/__init__.py:15 22 | msgid "INCORRECT_LINK" 23 | msgstr "Incorrect link. Please, try again in one of the following formats" 24 | 25 | #: app/bot/plugins/common.py:16 26 | msgid "HELLO" 27 | msgstr "Hello!" 28 | 29 | #: app/bot/plugins/common.py:17 30 | msgid "PERMISSION_CHECK_FAILED" 31 | msgstr "" 32 | "Failed to check permissions. Something wrong on the Telegram side.\n" 33 | "\n" 34 | "Try again later." 35 | 36 | #: app/bot/plugins/common.py:18 37 | msgid "NO_PERMISSION" 38 | msgstr "Sorry, you don't have the required permissions to use this bot :(" 39 | 40 | #: app/bot/plugins/common.py:19 41 | msgid "WAITING_FOR_LINK" 42 | msgstr "Send me a VK link!" 43 | 44 | #: app/bot/plugins/common.py:20 45 | msgid "CANCELLED" 46 | msgstr "Operation cancelled." 47 | 48 | #: app/bot/plugins/common.py:21 49 | msgid "CLICK_BUTTON" 50 | msgstr "Please click one of the buttons!" 51 | 52 | #: app/bot/plugins/playlist.py:22 53 | msgid "PL_NOT_READY" 54 | msgstr "Playlist is not ready yet!" 55 | 56 | #: app/bot/plugins/playlist.py:23 57 | msgid "PL_SEARCHING" 58 | msgstr "Searching..." 59 | 60 | #: app/bot/plugins/playlist.py:24 61 | msgid "PL_NOT_FOUND_IN_VK" 62 | msgstr "" 63 | "Failed to find such playlist in VK! Either incorrect link or private " 64 | "playlist. Please try another link." 65 | 66 | #: app/bot/plugins/playlist.py:25 67 | msgid "PL_ALREADY_IN_THE_QUEUE" 68 | msgstr "This playlist is already in the queue! Send it again?" 69 | 70 | #: app/bot/plugins/playlist.py:26 71 | msgid "PL_ALREADY_STARTED" 72 | msgstr "This playlist is already handling! Send it again?" 73 | 74 | #: app/bot/plugins/playlist.py:27 75 | msgid "PL_FOUND_IN_TGM" 76 | msgstr "Playlist found! Send it again?" 77 | 78 | #: app/bot/plugins/playlist.py:28 79 | msgid "PL_NOT_FOUND_IN_TGM" 80 | msgstr "No such playlist found in the Telegram channel! Send it?" 81 | 82 | #: app/bot/plugins/playlist.py:29 83 | msgid "PL_ADDED_TO_THE_QUEUE" 84 | msgstr "The playlist has been added to the queue!" 85 | 86 | #: app/bot/plugins/playlist.py:30 87 | msgid "PL_UNKNOWN_CHANNEL" 88 | msgstr "Error. This bot is not an admin in the specified Telegram channel." 89 | 90 | #: app/bot/plugins/playlist.py:31 91 | msgid "PL_YES" 92 | msgstr "Yes" 93 | 94 | #: app/bot/plugins/playlist.py:32 95 | msgid "PL_CANCEL" 96 | msgstr "Cancel" 97 | 98 | #: app/bot/plugins/wall.py:22 99 | msgid "WALL_SEARCHING" 100 | msgstr "Searching..." 101 | 102 | #: app/bot/plugins/wall.py:23 103 | msgid "WALL_NOT_FOUND_IN_VK" 104 | msgstr "" 105 | "Failed to find post in VK! Either incorrect link or private post. Please " 106 | "try another link." 107 | 108 | #: app/bot/plugins/wall.py:24 109 | msgid "WALL_ALREADY_IN_THE_QUEUE" 110 | msgstr "This post is already in the queue! Send it again?" 111 | 112 | #: app/bot/plugins/wall.py:25 113 | msgid "WALL_ALREADY_STARTED" 114 | msgstr "This post is already handling! Send it again?" 115 | 116 | #: app/bot/plugins/wall.py:26 117 | msgid "WALL_FOUND_IN_TGM" 118 | msgstr "Post found! Send it again?" 119 | 120 | #: app/bot/plugins/wall.py:27 121 | msgid "WALL_NOT_FOUND_IN_TGM" 122 | msgstr "No such post found in Telegram channel! Send it?" 123 | 124 | #: app/bot/plugins/wall.py:28 125 | msgid "WALL_ADDED_TO_THE_QUEUE" 126 | msgstr "The post has been added to the queue!" 127 | 128 | #: app/bot/plugins/wall.py:29 129 | msgid "WALL_UNKNOWN_CHANNEL" 130 | msgstr "Error. This bot is not an admin in the specified Telegram channel." 131 | 132 | #: app/bot/plugins/wall.py:30 133 | msgid "WALL_YES" 134 | msgstr "Yes" 135 | 136 | #: app/bot/plugins/wall.py:31 137 | msgid "WALL_CANCEL" 138 | msgstr "Cancel" 139 | 140 | #: app/handlers/playlist.py:21 141 | msgid "PL_READY" 142 | msgstr "Listen to the playlist" 143 | 144 | #: app/handlers/playlist.py:22 145 | msgid "PL_GO_TO_WALL" 146 | msgstr "Go to post" 147 | 148 | #: app/handlers/playlist.py:23 149 | msgid "PL_OF" 150 | msgstr "of" 151 | 152 | #: app/handlers/text.py:17 153 | msgid "SOURCE" 154 | msgstr "Source" 155 | 156 | #: app/handlers/text.py:18 157 | msgid "VK_POST" 158 | msgstr "VK post" 159 | 160 | #: app/handlers/text.py:19 161 | msgid "VK_REPOST" 162 | msgstr "VK repost" 163 | 164 | #: app/handlers/text.py:20 165 | msgid "VK_PLAYLIST" 166 | msgstr "VK playlist" 167 | 168 | #: app/handlers/wall.py:32 169 | msgid "PL_SOON" 170 | msgstr "Playlist link will be here soon..." 171 | 172 | -------------------------------------------------------------------------------- /locale/ru/LC_MESSAGES/vtt.po: -------------------------------------------------------------------------------- 1 | # Russian translations for PROJECT. 2 | # Copyright (C) 2022 ORGANIZATION 3 | # This file is distributed under the same license as the PROJECT project. 4 | # FIRST AUTHOR , 2022. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: PROJECT VERSION\n" 9 | "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" 10 | "POT-Creation-Date: 2022-04-27 02:39+0300\n" 11 | "PO-Revision-Date: 2022-04-22 21:41+0300\n" 12 | "Last-Translator: FULL NAME \n" 13 | "Language: ru\n" 14 | "Language-Team: ru \n" 15 | "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && " 16 | "n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" 17 | "MIME-Version: 1.0\n" 18 | "Content-Type: text/plain; charset=utf-8\n" 19 | "Content-Transfer-Encoding: 8bit\n" 20 | "Generated-By: Babel 2.10.1\n" 21 | 22 | #: app/bot/plugins/__init__.py:15 23 | msgid "INCORRECT_LINK" 24 | msgstr "" 25 | "Неверная ссылка. Пожалуйста, попробуйте еще раз в одном из следующих " 26 | "форматов" 27 | 28 | #: app/bot/plugins/common.py:16 29 | msgid "HELLO" 30 | msgstr "Привет!" 31 | 32 | #: app/bot/plugins/common.py:17 33 | msgid "PERMISSION_CHECK_FAILED" 34 | msgstr "" 35 | "Не удалось проверить разрешения. Что-то не так на стороне Telegram.\n" 36 | "Попробуйте еще раз позже." 37 | 38 | #: app/bot/plugins/common.py:18 39 | msgid "NO_PERMISSION" 40 | msgstr "" 41 | "К сожалению, у вас нет необходимых разрешений для использования этого " 42 | "бота :(" 43 | 44 | #: app/bot/plugins/common.py:19 45 | msgid "WAITING_FOR_LINK" 46 | msgstr "Пришлите мне VK ссылку!" 47 | 48 | #: app/bot/plugins/common.py:20 49 | msgid "CANCELLED" 50 | msgstr "Операция отменена." 51 | 52 | #: app/bot/plugins/common.py:21 53 | msgid "CLICK_BUTTON" 54 | msgstr "Пожалуйста, нажмите одну из кнопок!" 55 | 56 | #: app/bot/plugins/playlist.py:22 57 | msgid "PL_NOT_READY" 58 | msgstr "Плейлист еще не готов!" 59 | 60 | #: app/bot/plugins/playlist.py:23 61 | msgid "PL_SEARCHING" 62 | msgstr "Поиск..." 63 | 64 | #: app/bot/plugins/playlist.py:24 65 | msgid "PL_NOT_FOUND_IN_VK" 66 | msgstr "" 67 | "Не удалось найти такой плейлист в VK! Либо неверная ссылка, либо плейлист" 68 | " является приватным. Пожалуйста, попробуйте другую ссылку." 69 | 70 | #: app/bot/plugins/playlist.py:25 71 | msgid "PL_ALREADY_IN_THE_QUEUE" 72 | msgstr "Этот плейлист уже в очереди! Отправить еще раз?" 73 | 74 | #: app/bot/plugins/playlist.py:26 75 | msgid "PL_ALREADY_STARTED" 76 | msgstr "Этот плейлист уже обрабатывается! Отправить еще раз?" 77 | 78 | #: app/bot/plugins/playlist.py:27 79 | msgid "PL_FOUND_IN_TGM" 80 | msgstr "Плейлист найден! Отправить еще раз?" 81 | 82 | #: app/bot/plugins/playlist.py:28 83 | msgid "PL_NOT_FOUND_IN_TGM" 84 | msgstr "В Telegram канале такой плейлист не найден! Отправить?" 85 | 86 | #: app/bot/plugins/playlist.py:29 87 | msgid "PL_ADDED_TO_THE_QUEUE" 88 | msgstr "Плейлист добавлен в очередь!" 89 | 90 | #: app/bot/plugins/playlist.py:30 91 | msgid "PL_UNKNOWN_CHANNEL" 92 | msgstr "" 93 | "Ошибка. Данный бот не является администратором в указанном Telegram " 94 | "канале." 95 | 96 | #: app/bot/plugins/playlist.py:31 97 | msgid "PL_YES" 98 | msgstr "Да" 99 | 100 | #: app/bot/plugins/playlist.py:32 101 | msgid "PL_CANCEL" 102 | msgstr "Отмена" 103 | 104 | #: app/bot/plugins/wall.py:22 105 | msgid "WALL_SEARCHING" 106 | msgstr "Поиск..." 107 | 108 | #: app/bot/plugins/wall.py:23 109 | msgid "WALL_NOT_FOUND_IN_VK" 110 | msgstr "" 111 | "Не удалось найти пост в VK! Либо неверная ссылка, либо пост является " 112 | "приватным. Пожалуйста, попробуйте другую ссылку." 113 | 114 | #: app/bot/plugins/wall.py:24 115 | msgid "WALL_ALREADY_IN_THE_QUEUE" 116 | msgstr "Этот пост уже в очереди! Отправить еще раз?" 117 | 118 | #: app/bot/plugins/wall.py:25 119 | msgid "WALL_ALREADY_STARTED" 120 | msgstr "Этот пост уже обрабатывается! Отправить еще раз?" 121 | 122 | #: app/bot/plugins/wall.py:26 123 | msgid "WALL_FOUND_IN_TGM" 124 | msgstr "Пост найден! Отправить еще раз?" 125 | 126 | #: app/bot/plugins/wall.py:27 127 | msgid "WALL_NOT_FOUND_IN_TGM" 128 | msgstr "В Telegram канале такой пост не найден! Отправить?" 129 | 130 | #: app/bot/plugins/wall.py:28 131 | msgid "WALL_ADDED_TO_THE_QUEUE" 132 | msgstr "Пост добавлен в очередь!" 133 | 134 | #: app/bot/plugins/wall.py:29 135 | msgid "WALL_UNKNOWN_CHANNEL" 136 | msgstr "" 137 | "Ошибка. Данный бот не является администратором в указанном Telegram " 138 | "канале." 139 | 140 | #: app/bot/plugins/wall.py:30 141 | msgid "WALL_YES" 142 | msgstr "Да" 143 | 144 | #: app/bot/plugins/wall.py:31 145 | msgid "WALL_CANCEL" 146 | msgstr "Отмена" 147 | 148 | #: app/handlers/playlist.py:21 149 | msgid "PL_READY" 150 | msgstr "Слушать плейлист" 151 | 152 | #: app/handlers/playlist.py:22 153 | msgid "PL_GO_TO_WALL" 154 | msgstr "Перейти к посту" 155 | 156 | #: app/handlers/playlist.py:23 157 | msgid "PL_OF" 158 | msgstr "из" 159 | 160 | #: app/handlers/text.py:17 161 | msgid "SOURCE" 162 | msgstr "Источник" 163 | 164 | #: app/handlers/text.py:18 165 | msgid "VK_POST" 166 | msgstr "Пост в VK" 167 | 168 | #: app/handlers/text.py:19 169 | msgid "VK_REPOST" 170 | msgstr "Репост в VK" 171 | 172 | #: app/handlers/text.py:20 173 | msgid "VK_PLAYLIST" 174 | msgstr "Плейлист в VK" 175 | 176 | #: app/handlers/wall.py:32 177 | msgid "PL_SOON" 178 | msgstr "Ссылка на плейлист скоро появится..." 179 | 180 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vk-to-tgm 2 | 3 | An application that forwards wall posts and playlists from VK community to Telegram channel. 4 | 5 | Consists of following services: 6 | - Server that receives VK Callback events 7 | - Telegram bot that forwards wall posts or playlists by user request 8 | - Celery worker that forwards wall posts 9 | - (optional) Celery worker that forwards playlists 10 | - Celery Beat service, that cleans up a SQLite3 database task results 11 | 12 | ![vtt_schema](assets/vtt_schema.png) 13 | 14 | ## Requirements: 15 | - Python 3.8+ 16 | - RabbitMQ Server 17 | - FFmpeg 18 | - [VK community token with access to community management](https://vk.com/dev/access_token) 19 | - VK account 20 | - Telegram channel (and additional channel if you need playlists) 21 | - Telegram account 22 | - [Telegram bot token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) 23 | - [Telegram application](https://core.telegram.org/api/obtaining_api_id) 24 | 25 | ## What can it forward 26 | 27 | | VK | Telegram | Notes | 28 | |-------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 29 | | Text | ✅ | Will be splitted into multpile messages if VK text is too big. | 30 | | Photo | ✅ | Will be posted with the largest size available. | 31 | | Video | ✅ | VK videos will be uploaded directly (up to 720p). External videos (YouTube, Vimeo, etc.) will be at the top in the form of links, so that the first one will be shown in the preview. | 32 | | Audio | ✅ | Will be posted in separate message. | 33 | | File | ✅ | Will be posted in separate message. | 34 | | Poll | ✅ | Will be posted in separate message. | 35 | | Market | ✅ | Will be in the form of link. | 36 | | Playlist | ✅ | Additional Telegram channel is required. There will be separate message in the main channel with the link to the message in the playlist channel, where audios will be uploaded. | 37 | | Link | ✅ | Will be shown just as VK link. | 38 | | Article | ✅ | Will be in the form of link. | 39 | | Poster | ✅ | Works the same way as with the photo. | 40 | | Graffiti | ✅ | Works the same way as with the photo. | 41 | | Map | ✅ | Will be posted in separate message. | 42 | | Live stream | ✅ | Will be posted at the top in the form of link. | 43 | 44 | **NOTE:** if post was edited in VK, it will NOT be edited in Telegram. As a workaround, you can delete old Telegram messages and reforward edited post through Telegram bot. 45 | 46 | ## Example 47 | ![vtt_example](assets/vtt_example.gif) 48 | 49 | Working example: https://t.me/mashup_vk 50 | 51 | ## Installation 52 | Run `install.sh` script. 53 | 54 | ### Docker installation 55 | 1. Set environment variables manually in `.env` file or by running 56 | ```sh 57 | ./vtt-cli.sh set_env 58 | ``` 59 | 2. Install Nginx and run command 60 | ```sh 61 | ./vtt-cli.sh setup_nginx 62 | ``` 63 | 3. Sign in VK and Telegram 64 | ```sh 65 | docker compose run --rm -it sign_in 66 | ``` 67 | 4. Start the app 68 | ```sh 69 | docker compose up 70 | 71 | # Or, if you also want to handle playlists 72 | docker compose --profile with_pl up 73 | ``` 74 | 75 | If you want to install client SSL certificate, read [here](setup/ssl/README.md). 76 | 77 | ## Uninstallation 78 | Run `uninstall.sh` script. 79 | ### Docker uninstallation 80 | ```sh 81 | docker compose down -v --rmi all --remove-orphans 82 | ``` 83 | 84 | ## Logs 85 | You can check logs in the `logs/` directory. 86 | 87 | ## License 88 | GNU General Public License v3.0 or later. 89 | 90 | See [LICENSE](LICENSE) file. 91 | -------------------------------------------------------------------------------- /app/bot/plugins/wall.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import re 3 | from typing import List, Union 4 | 5 | from telethon import Button, TelegramClient, events 6 | from telethon.events import StopPropagation 7 | from telethon.tl.functions.messages import SearchRequest 8 | from telethon.tl.patched import Message 9 | from telethon.tl.types import InputMessagesFilterUrl 10 | from telethon.tl.types.messages import ChannelMessages 11 | from vkbottle.api.api import API 12 | 13 | from app.bot.plugins.common import check_permission, check_state, state_manager 14 | from app.bot.state_manager import State 15 | from app.celery_worker import forward_wall 16 | from app.config import _, settings 17 | from app.utils.database import VttTaskType, get_queued_task 18 | from app.utils.telegram import get_entity_by_id 19 | 20 | logger = logging.getLogger(__name__) 21 | 22 | WALL_SEARCHING = _("WALL_SEARCHING") 23 | WALL_NOT_FOUND_IN_VK = _("WALL_NOT_FOUND_IN_VK") 24 | WALL_ALREADY_IN_THE_QUEUE = _("WALL_ALREADY_IN_THE_QUEUE") 25 | WALL_ALREADY_STARTED = _("WALL_ALREADY_STARTED") 26 | WALL_FOUND_IN_TGM = _("WALL_FOUND_IN_TGM") 27 | WALL_NOT_FOUND_IN_TGM = _("WALL_NOT_FOUND_IN_TGM") 28 | WALL_ADDED_TO_THE_QUEUE = _("WALL_ADDED_TO_THE_QUEUE") 29 | WALL_UNKNOWN_CHANNEL = _("WALL_UNKNOWN_CHANNEL") 30 | WALL_YES = _("WALL_YES") 31 | WALL_CANCEL = _("WALL_CANCEL") 32 | 33 | post_pattern = re.compile(r"(https:\/\/)?(www\.)?(m\.)?vk\.com(\/?|\/\w+\?w=)wall(?P-\d+)_(?P\d+)") 34 | 35 | # Somewhat fixed type for NewMessage event 36 | NewMessageEvent = Union[events.NewMessage.Event, events.CallbackQuery.Event] 37 | 38 | 39 | async def init(bot: TelegramClient, client: TelegramClient, vk_api: API): 40 | @bot.on(events.CallbackQuery(data=b"wall_confirm", func=lambda e: check_state(e, State.WAITING_FOR_CHOISE))) 41 | async def new_wall(event: NewMessageEvent): 42 | await event.edit(buttons=Button.clear()) 43 | if not await check_permission(event): 44 | raise events.StopPropagation 45 | 46 | data = state_manager.get_info(event.sender_id)[1] 47 | forward_wall.delay( 48 | owner_id=data["owner_id"], 49 | wall_id=data["id"], 50 | ) 51 | await event.respond(WALL_ADDED_TO_THE_QUEUE) 52 | state_manager.clear_info(event.sender_id) 53 | raise StopPropagation 54 | 55 | @bot.on(events.NewMessage(pattern=post_pattern, func=lambda e: check_state(e, State.WAITING_FOR_LINK))) 56 | async def on_new_wall(event: NewMessageEvent): 57 | if not await check_permission(event): 58 | raise events.StopPropagation 59 | 60 | await event.respond(WALL_SEARCHING) 61 | sender = event.sender_id 62 | match_dict = event.pattern_match.groupdict() 63 | owner_id = int(match_dict["owner_id"]) 64 | id = int(match_dict["id"]) 65 | 66 | full_id = f"{owner_id}_{id}" 67 | 68 | vk_wall_result: List[dict] = ( 69 | await vk_api.request( 70 | "wall.getById", 71 | { 72 | "posts": full_id, 73 | }, 74 | ) 75 | )["response"] 76 | if not vk_wall_result: 77 | await event.respond(WALL_NOT_FOUND_IN_VK) 78 | raise StopPropagation 79 | 80 | queued_task = get_queued_task(owner_id, id, VttTaskType.wall) 81 | if queued_task: 82 | if queued_task.status == "SENT": 83 | waiting_text = WALL_ALREADY_IN_THE_QUEUE 84 | else: 85 | waiting_text = WALL_ALREADY_STARTED 86 | message = await event.respond( 87 | waiting_text, 88 | buttons=[ 89 | Button.inline(WALL_YES, data="wall_confirm"), 90 | Button.inline(WALL_CANCEL, data=b"cancel"), 91 | ], 92 | ) 93 | state_manager.set_info( 94 | sender, 95 | State.WAITING_FOR_CHOISE, 96 | { 97 | "choice_message": message.id, 98 | "owner_id": owner_id, 99 | "id": id, 100 | }, 101 | ) 102 | raise StopPropagation 103 | 104 | peer = await get_entity_by_id(client, settings.TGM_CHANNEL_ID) 105 | if peer is None: 106 | message = await event.respond(WALL_UNKNOWN_CHANNEL) 107 | state_manager.clear_info(event.sender_id) 108 | raise StopPropagation 109 | 110 | filter = InputMessagesFilterUrl() 111 | search_result: ChannelMessages = await client( 112 | SearchRequest( 113 | peer=peer, 114 | q=f"https://vk.com/wall{full_id}", 115 | filter=filter, 116 | min_date=None, 117 | max_date=None, 118 | offset_id=0, 119 | add_offset=0, 120 | limit=1, 121 | max_id=0, 122 | min_id=0, 123 | hash=0, 124 | from_id=None, 125 | ) 126 | ) 127 | waiting_text = WALL_NOT_FOUND_IN_TGM 128 | if search_result.messages: 129 | waiting_text = WALL_FOUND_IN_TGM 130 | message: Message = search_result.messages[0] 131 | await bot.forward_messages(sender, message.id, from_peer=message.chat_id) 132 | message = await event.respond( 133 | waiting_text, 134 | buttons=[ 135 | Button.inline(WALL_YES, data="wall_confirm"), 136 | Button.inline(WALL_CANCEL, data=b"cancel"), 137 | ], 138 | ) 139 | state_manager.set_info( 140 | sender, 141 | State.WAITING_FOR_CHOISE, 142 | { 143 | "choice_message": message.id, 144 | "owner_id": owner_id, 145 | "id": id, 146 | }, 147 | ) 148 | raise StopPropagation 149 | -------------------------------------------------------------------------------- /app/utils/downloader.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import cgi 3 | import logging 4 | import os 5 | import re 6 | import tempfile 7 | from mimetypes import guess_extension 8 | from secrets import randbelow 9 | from typing import List, Optional 10 | from urllib.parse import urlparse 11 | 12 | import aiofiles 13 | import eyed3 14 | import ffmpeg 15 | from aiofiles.tempfile import NamedTemporaryFile 16 | from aiohttp import ClientSession 17 | from vkbottle.api.api import API 18 | from vkbottle_types.objects import AudioAudio 19 | 20 | from app.schemas.vk import VttVideo 21 | 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | class Downloader: 26 | def __init__(self) -> None: 27 | self.session = ClientSession() 28 | self.file_paths: List[str] = [] 29 | 30 | async def __aenter__(self): 31 | return self 32 | 33 | async def __aexit__(self, exc_type, exc_value, traceback): 34 | await self.close() 35 | 36 | async def close(self): 37 | await self.session.close() 38 | for path in self.file_paths: 39 | os.remove(path) 40 | 41 | async def download_media(self, url: str) -> str: 42 | logger.info(f"Downloading document from URL: {url}") 43 | filepath = "" 44 | await asyncio.sleep(randbelow(3)) 45 | async with self.session.get(url, timeout=3600) as response: 46 | temp_path = os.path.join(tempfile.gettempdir(), os.path.basename(response.url.path)) 47 | async with aiofiles.open(temp_path, "w+b") as file: 48 | async for chunk, _ in response.content.iter_chunks(): 49 | await file.write(chunk) 50 | filepath = temp_path 51 | return filepath 52 | 53 | async def download_video(self, url: str, title: str) -> str: 54 | logger.info(f'Downloading video "{title}" from URL: {url}') 55 | filepath = "" 56 | await asyncio.sleep(randbelow(3)) 57 | async with self.session.get(url, timeout=3600) as response: 58 | if not title: 59 | header = response.headers.get("Content-Disposition") 60 | _, opts = cgi.parse_header(header) 61 | filename = opts["filename"] 62 | else: 63 | name = title.strip().replace(" ", "_") 64 | name = re.sub(r"(?u)[^-\w.]", "", name) 65 | extension = guess_extension(response.headers.get("content-type")) 66 | filename = name + extension 67 | temp_path = os.path.join(tempfile.gettempdir(), filename) 68 | async with aiofiles.open(temp_path, "w+b") as file: 69 | async for chunk, _ in response.content.iter_chunks(): 70 | await file.write(chunk) 71 | filepath = temp_path 72 | return filepath 73 | 74 | async def download_audio( 75 | self, 76 | audio: AudioAudio, 77 | fallback_vk_api: Optional[API] = None, 78 | try_fallback: bool = True, 79 | ) -> str: 80 | url = audio.url 81 | audio_full_id = f"{audio.owner_id}_{audio.id}_{audio.access_key}" 82 | audio_full_title = f"{audio.artist} - {audio.title}" 83 | logger.info(f"Downloading audio [{audio_full_id}] from URL: {url}") 84 | filepath = "" 85 | await asyncio.sleep(randbelow(3)) 86 | async with NamedTemporaryFile(suffix=".mp3", delete=False) as temp: 87 | if not urlparse(url).path.endswith("m3u8"): 88 | logger.info("Downloading audio by http...") 89 | async with self.session.get(url, timeout=3600) as response: 90 | async for chunk, _ in response.content.iter_chunks(): 91 | await temp.write(chunk) 92 | else: 93 | logger.info("Downloading audio by ffmpeg...") 94 | stream = ffmpeg.input(url, http_persistent=False) 95 | stream = ffmpeg.output(stream, "-", c="copy", f="mp3") 96 | out, _ = ffmpeg.run(stream, capture_stdout=True, quiet=True) 97 | await temp.write(out) 98 | filepath = temp.name 99 | 100 | # Setting audio metadata 101 | audiofile = eyed3.load(filepath) 102 | if audiofile: 103 | audiofile.tag.artist = audio.artist 104 | audiofile.tag.title = audio.title 105 | audiofile.tag.save() 106 | elif fallback_vk_api and try_fallback: 107 | logger.warning(f"Broken audio [{audio_full_id}] [{audio_full_title}], trying with another token...") 108 | audios: List[dict] = ( 109 | await fallback_vk_api.request( 110 | "audio.getById", 111 | { 112 | "audios": audio_full_id, 113 | }, 114 | ) 115 | )["response"] 116 | fb_audio = next(iter(audios), None) 117 | if fb_audio and fb_audio.get("url"): 118 | audio = AudioAudio(**fb_audio) 119 | filepath = await self.download_audio(audio, fallback_vk_api, try_fallback=False) 120 | 121 | logger.info(f"Audio succesfully downloaded: [{audio_full_id}] [{audio_full_title}]") 122 | return filepath 123 | 124 | async def download_medias(self, media_urls: List[str]): 125 | media_paths = await asyncio.gather(*[self.download_media(url) for url in media_urls]) 126 | self.file_paths += media_paths 127 | return media_paths 128 | 129 | async def download_videos(self, videos: List[VttVideo]): 130 | video_paths = await asyncio.gather(*[self.download_video(video.url, video.title) for video in videos]) 131 | self.file_paths += video_paths 132 | return video_paths 133 | 134 | async def download_audios(self, audios: List[AudioAudio], fallback_vk_api: Optional[API] = None): 135 | audio_paths = await asyncio.gather(*[self.download_audio(audio, fallback_vk_api) for audio in audios]) 136 | self.file_paths += audio_paths 137 | return audio_paths 138 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiofiles==0.8.0; python_version >= "3.6" and python_version < "4.0" 2 | aiohttp==3.8.1; python_version >= "3.6" 3 | aiosignal==1.2.0; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" 4 | amqp==5.1.1; python_version >= "3.7" 5 | anyio==3.5.0; python_version >= "3.6" and python_full_version >= "3.6.2" 6 | asgiref==3.5.0; python_version >= "3.7" 7 | async-timeout==4.0.2; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" 8 | attrs==21.4.0; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" 9 | billiard==3.6.4.0; python_version >= "3.7" 10 | celery==5.2.6; python_version >= "3.7" 11 | certifi==2021.10.8; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" 12 | cffi==1.15.0; python_version >= "3.6" 13 | charset-normalizer==2.0.12; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" and python_version < "4" 14 | choicelib==0.1.5; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.7.2" and python_full_version < "4.0.0" 15 | click-didyoumean==0.3.0; python_full_version >= "3.6.2" and python_full_version < "4.0.0" and python_version >= "3.7" 16 | click-plugins==1.1.1; python_version >= "3.7" 17 | click-repl==0.2.0; python_version >= "3.7" 18 | click==8.1.2; python_full_version >= "3.6.2" and python_full_version < "4.0.0" and python_version >= "3.7" 19 | colorama==0.4.4; python_version >= "3.7" and python_full_version < "3.0.0" and sys_platform == "win32" and platform_system == "Windows" or sys_platform == "win32" and python_version >= "3.7" and python_full_version >= "3.5.0" and platform_system == "Windows" 20 | coverage==5.5; python_version >= "3.6" and python_full_version < "3.0.0" and python_version < "4.0" or python_full_version >= "3.5.0" and python_version < "4" and python_version >= "3.6" 21 | cryptg==0.2.post4; python_version >= "3.6" 22 | deprecation==2.1.0; python_version >= "3.6" and python_version < "4.0" 23 | eyed3==0.9.6; python_version >= "3.6" and python_version < "4.0" 24 | fastapi==0.75.2; python_full_version >= "3.6.1" 25 | ffmpeg-python==0.2.0 26 | filetype==1.0.13; python_version >= "3.6" and python_version < "4.0" 27 | frozenlist==1.3.0; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.7" 28 | future==0.18.2; python_version >= "2.6" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" 29 | greenlet==1.1.2; python_version >= "3" and python_full_version < "3.0.0" and (platform_machine == "aarch64" or platform_machine == "ppc64le" or platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "win32" or platform_machine == "WIN32") and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") or python_version >= "3" and (platform_machine == "aarch64" or platform_machine == "ppc64le" or platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "win32" or platform_machine == "WIN32") and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") and python_full_version >= "3.5.0" 30 | gunicorn==20.1.0; python_version >= "3.5" 31 | h11==0.13.0; python_version >= "3.7" 32 | hachoir==3.1.3 33 | httptools==0.4.0; python_version >= "3.7" and python_full_version >= "3.5.0" 34 | idna==3.3; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" and python_version >= "3.5") 35 | kombu==5.2.4; python_version >= "3.7" 36 | multidict==6.0.2; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.7" 37 | packaging==21.3; python_version >= "3.6" and python_version < "4.0" 38 | pillow==9.1.0; python_version >= "3.7" 39 | prompt-toolkit==3.0.29; python_full_version >= "3.6.2" and python_version >= "3.7" 40 | pyaes==1.6.1; python_version >= "3.5" 41 | pyasn1==0.4.8; python_version >= "3.6" and python_version < "4" 42 | pycparser==2.21; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" 43 | pydantic==1.9.0; python_full_version >= "3.7.2" and python_full_version < "4.0.0" 44 | pyparsing==3.0.8; python_version >= "3.6" and python_version < "4.0" and python_full_version >= "3.6.8" 45 | python-dotenv==0.20.0; python_version >= "3.7" 46 | pytz==2022.1; python_version >= "3.7" 47 | pyyaml==6.0; python_version >= "3.7" 48 | requests==2.27.1; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" 49 | rsa==4.8; python_version >= "3.6" and python_version < "4" 50 | six==1.16.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7" 51 | sniffio==1.2.0; python_version >= "3.6" and python_full_version >= "3.6.2" 52 | sqlalchemy==1.4.35; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.6.0") 53 | starlette==0.17.1; python_version >= "3.6" and python_full_version >= "3.6.1" 54 | telethon==1.24.0; python_version >= "3.5" 55 | toml==0.10.2; python_version >= "3.6" and python_full_version < "3.0.0" and python_version < "4.0" or python_full_version >= "3.5.0" and python_version < "4" and python_version >= "3.6" 56 | typing-extensions==4.2.0; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.7" and python_version < "4.0" 57 | urllib3==1.26.9; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" 58 | uvicorn==0.17.6; python_version >= "3.7" 59 | uvloop==0.16.0; sys_platform != "win32" and sys_platform != "cygwin" and platform_python_implementation != "PyPy" and python_version >= "3.7" 60 | vbml==1.1.post1; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.7.2" and python_full_version < "4.0.0" 61 | vine==5.0.0; python_version >= "3.7" 62 | vkaudiotoken @ git+https://github.com/Bizordec/vkaudiotoken-python.git@master ; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.5.0" and python_version < "4") 63 | vkbottle-types==5.131.146.1; python_full_version >= "3.7.2" and python_full_version < "4.0.0" 64 | vkbottle==4.2.2; python_full_version >= "3.7.2" and python_full_version < "4.0.0" 65 | watchgod==0.7; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.7" 66 | wcwidth==0.2.5; python_full_version >= "3.6.2" and python_version >= "3.7" 67 | websockets==10.3; python_version >= "3.7" 68 | yarl==1.7.2; python_full_version >= "3.7.2" and python_full_version < "4.0.0" and python_version >= "3.6" 69 | -------------------------------------------------------------------------------- /app/handlers/playlist.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import Optional 3 | 4 | from aiohttp import ClientSession 5 | from telethon.client.telegramclient import TelegramClient 6 | from telethon.tl.custom.button import Button 7 | from telethon.tl.types import Message 8 | from vkaudiotoken import supported_clients 9 | from vkbottle import AiohttpClient 10 | from vkbottle.api.api import API 11 | 12 | from app.config import _, settings 13 | from app.handlers.text import PlaylistTextHandler 14 | from app.schemas.vk import AudioPlaylist 15 | from app.utils.downloader import Downloader 16 | from app.utils.telegram import get_message_link 17 | from app.utils.vk import VkLangRequestValidator, get_playlist 18 | 19 | logger = logging.getLogger(__name__) 20 | 21 | PL_READY = _("PL_READY") 22 | PL_GO_TO_WALL = _("PL_GO_TO_WALL") 23 | PL_OF = _("PL_OF") 24 | 25 | 26 | class PlaylistHandler: 27 | def __init__( 28 | self, 29 | owner_id: int, 30 | playlist_id: int, 31 | access_key: Optional[str], 32 | tgm_bot: TelegramClient, 33 | kate_token: str, 34 | main_channel_id: Optional[int] = None, 35 | main_message_id: Optional[int] = None, 36 | ) -> None: 37 | self.pl_channel_id = settings.TGM_PL_CHANNEL_ID 38 | self.owner_id = owner_id 39 | self.playlist_id = playlist_id 40 | self.access_key = access_key 41 | self.main_channel_id = main_channel_id 42 | self.main_message_id = main_message_id 43 | self.tgm_bot = tgm_bot 44 | self.kate_user = API( 45 | token=kate_token, 46 | http_client=AiohttpClient( 47 | session=ClientSession( 48 | headers={"User-agent": supported_clients.KATE.user_agent}, 49 | ), 50 | ), 51 | ) 52 | self.kate_user.request_validators.append(VkLangRequestValidator()) 53 | 54 | self.vk_user = API( 55 | token=settings.VK_OFFICIAL_TOKEN, 56 | http_client=AiohttpClient( 57 | session=ClientSession( 58 | headers={"User-agent": supported_clients.VK_OFFICIAL.user_agent}, 59 | ), 60 | ), 61 | ) 62 | self.vk_user.request_validators.append(VkLangRequestValidator()) 63 | 64 | async def __aenter__(self): 65 | return self 66 | 67 | async def __aexit__(self, exc_type, exc_value, traceback): 68 | await self.kate_user.http_client.close() 69 | await self.vk_user.http_client.close() 70 | 71 | async def get_text( 72 | self, 73 | playlist: AudioPlaylist, 74 | ): 75 | text = PlaylistTextHandler(self.kate_user, playlist) 76 | await text.process_text() 77 | return text 78 | 79 | async def run(self) -> str: 80 | playlist = await get_playlist( 81 | self.kate_user, 82 | self.owner_id, 83 | self.playlist_id, 84 | self.access_key, 85 | ) 86 | 87 | if not playlist: 88 | full_id = f"{self.owner_id}_{self.playlist_id}_{self.access_key}" 89 | logger.warning(f"[{full_id}] Playlist not found.") 90 | return "NOT_FOUND" 91 | 92 | logger.info(f"[{playlist.full_id}] Sending main playlist message...") 93 | pl_captions = (await self.get_text(playlist)).caption 94 | pl_captions_first = pl_captions[0] if pl_captions else None 95 | pl_captions_first_text = pl_captions_first[0] if pl_captions_first else "" 96 | pl_captions_first_entities = pl_captions_first[1] if pl_captions_first else None 97 | async with Downloader() as downloader: 98 | downloaded_photo = None 99 | if playlist.photo: 100 | downloaded_photo = await downloader.download_media(playlist.photo) 101 | pl_main_message = await self.tgm_bot.send_message( 102 | self.pl_channel_id, 103 | file=downloaded_photo, 104 | message=pl_captions_first_text, 105 | formatting_entities=pl_captions_first_entities, 106 | link_preview=False, 107 | ) 108 | 109 | if self.main_channel_id and self.main_message_id: 110 | logger.info(f"[{playlist.full_id}] Setting links between playlist and main message...") 111 | main_post_link = get_message_link( 112 | await self.tgm_bot.get_entity(self.main_channel_id), 113 | self.main_message_id, 114 | ) 115 | pl_main_message = await self.tgm_bot.edit_message( 116 | pl_main_message, 117 | buttons=Button.url(f"🔗 {PL_GO_TO_WALL}", main_post_link), 118 | ) 119 | 120 | pl_post_link = get_message_link( 121 | await self.tgm_bot.get_entity(self.pl_channel_id), 122 | pl_main_message.id, 123 | ) 124 | main_message: Message = await self.tgm_bot.get_messages( 125 | self.main_channel_id, 126 | ids=self.main_message_id, 127 | ) 128 | await self.tgm_bot.edit_message( 129 | main_message, 130 | buttons=Button.url(f"🔊 {PL_READY}", pl_post_link), 131 | ) 132 | 133 | logger.info(f"[{playlist.full_id}] Sending rest playlist messages...") 134 | rest_messages = pl_captions[1:] 135 | for text, entities in rest_messages: 136 | await self.tgm_bot.send_message( 137 | self.pl_channel_id, 138 | message=text, 139 | formatting_entities=entities, 140 | link_preview=False, 141 | reply_to=pl_main_message, 142 | ) 143 | 144 | logger.info(f"[{playlist.full_id}] Uploading playlist audios...") 145 | pl_length = len(playlist.audios) 146 | for i in range(0, pl_length, 10): 147 | current_audios = playlist.audios[i : i + 10] # noqa: E203 148 | current_audios_len = len(current_audios) 149 | pl_audio_caption = [""] * (current_audios_len - 1) + [ 150 | f"{i + 1}-{i + current_audios_len} {PL_OF} {pl_length}" 151 | ] 152 | async with Downloader() as downloader: 153 | current_audios_paths = await downloader.download_audios(current_audios, self.vk_user) 154 | await self.tgm_bot.send_file( 155 | self.pl_channel_id, 156 | file=current_audios_paths, 157 | caption=pl_audio_caption, 158 | voice_note=True, 159 | reply_to=pl_main_message, 160 | ) 161 | return get_message_link(await self.tgm_bot.get_entity(self.pl_channel_id), pl_main_message.id) 162 | -------------------------------------------------------------------------------- /app/handlers/text.py: -------------------------------------------------------------------------------- 1 | import html 2 | import re 3 | from typing import List, Optional, Tuple 4 | 5 | from telethon.tl.types import TypeMessageEntity 6 | from vkbottle.api.api import API 7 | from vkbottle_types.objects import GroupsGroupFull, WallPostType, WallWallpostFull 8 | 9 | from app.config import _ 10 | from app.schemas.vk import Attachments, AudioPlaylist 11 | from app.utils.telegram import get_html_link, split_text 12 | 13 | link_pattern = re.compile(r"\[(?P[^\[|]+)\|(?P[^\]]+)\]") 14 | vk_id_pattern = re.compile(r"(id|club)\d+") 15 | vk_link_pattern = re.compile(r"(https?:\/\/)?(m\.)?vk\.com(\/[\w\-\.~:\/?#[\]@&()*+,;%=\"ёЁа-яА-Я]*)?") 16 | 17 | SOURCE = _("SOURCE") 18 | VK_POST = _("VK_POST") 19 | VK_REPOST = _("VK_REPOST") 20 | VK_PLAYLIST = _("VK_PLAYLIST") 21 | 22 | 23 | class BaseTextHandler: 24 | def _convert_to_html_link(self, match: re.Match): 25 | groupdict = match.groupdict() 26 | url: str = groupdict.get("url") 27 | title: str = groupdict.get("title") 28 | 29 | if vk_id_pattern.fullmatch(url): 30 | url = f"https://vk.com/{url}" 31 | 32 | if vk_link_pattern.fullmatch(url): 33 | return f'<a href="{url}">{title}</a>' 34 | 35 | return f"[{url}|{title}]" 36 | 37 | def convert_vk_links(self, text: str): 38 | # Convert VK links to HTML links 39 | safe_text = html.escape(text.encode("raw_unicode_escape").decode("unicode_escape")) 40 | return link_pattern.sub(self._convert_to_html_link, safe_text) 41 | 42 | 43 | class WallTextHandler(BaseTextHandler): 44 | def __init__( 45 | self, 46 | vk_api: API, 47 | wall: WallWallpostFull, 48 | attachments: Attachments, 49 | is_repost=False, 50 | groups: Optional[List[GroupsGroupFull]] = None, 51 | ) -> None: 52 | self._vk_api = vk_api 53 | self._wall = wall 54 | self._groups = groups or [] 55 | self._attachments = attachments 56 | self._is_repost = is_repost 57 | 58 | self.header = "" 59 | self.footer = "" 60 | 61 | self._message = "" 62 | self._caption = "" 63 | 64 | async def process_text(self) -> None: 65 | wall = self._wall 66 | attachments = self._attachments 67 | 68 | header_text = "" 69 | footer_text = "" 70 | 71 | # Videos are at the top for the web page preview 72 | if attachments.videos: 73 | for video in attachments.videos: 74 | if video.platform or video.is_live: 75 | header_text += f"\n📺 {get_html_link(video.url, video.title)}" 76 | 77 | if wall.text: 78 | processed_wall_text = self.convert_vk_links(wall.text) 79 | 80 | if header_text: 81 | header_text += "\n\n" 82 | header_text += processed_wall_text 83 | 84 | post_type = wall.post_type 85 | if post_type == WallPostType.REPLY: 86 | commentator_id = wall.from_id 87 | if commentator_id < 0: 88 | group_id = str(abs(commentator_id)) 89 | commentator = (await self._vk_api.groups.get_by_id(group_id=group_id))[0] 90 | commentator_href = f"https://vk.com/public{group_id}" 91 | commentator_fullname = commentator.name 92 | else: 93 | commentator = (await self._vk_api.users.get(user_ids=[commentator_id]))[0] 94 | commentator_href = f"https://vk.com/id{commentator_id}" 95 | commentator_fullname = f"{commentator.first_name} {commentator.last_name}" 96 | footer_text += f"\n\n📝 {get_html_link(commentator_href, commentator_fullname)}" 97 | 98 | if attachments.market: 99 | att_market = attachments.market 100 | owner_id = att_market.owner_id 101 | market_link = f"https://vk.com/market{owner_id}?w=product{owner_id}_{att_market.id}" 102 | footer_text += f"\n\n🛍️ {get_html_link(market_link, att_market.title)}" 103 | 104 | if attachments.link: 105 | att_link = attachments.link 106 | footer_text += f"\n\n🔗 {get_html_link(att_link.url, att_link.caption)}" 107 | 108 | if wall.copyright: 109 | copyright = wall.copyright 110 | footer_text += f'\n\n📎 {get_html_link(copyright.link, f"{SOURCE}: {copyright.name}")}' 111 | 112 | if wall.signer_id: 113 | signer_id = wall.signer_id 114 | signer = (await self._vk_api.users.get(user_ids=[signer_id]))[0] 115 | signer_fullname = f"{signer.first_name} {signer.last_name}" 116 | footer_text += f'\n\n👤 {get_html_link(f"https://vk.com/id{signer_id}", signer_fullname)}' 117 | 118 | vk_link = "" 119 | post_href = f"https://vk.com/wall{wall.owner_id}_{wall.id}" 120 | if self._is_repost: 121 | if post_type == WallPostType.VIDEO: 122 | post_href = f"https://vk.com/video{wall.owner_id}_{wall.id}" 123 | elif post_type == WallPostType.PHOTO: 124 | post_href = f"https://vk.com/photo{wall.owner_id}_{wall.id}" 125 | 126 | repost_text = VK_REPOST 127 | group_name = next((group.name for group in self._groups if group.id == abs(wall.owner_id)), None) 128 | if group_name: 129 | repost_text += f": {group_name}" 130 | vk_link = f"\n\n🔁 {get_html_link(post_href, repost_text)}" 131 | else: 132 | vk_link = f"\n\n📌 {get_html_link(post_href, VK_POST)}" 133 | footer_text += vk_link 134 | 135 | self.header = header_text 136 | self.footer = footer_text 137 | 138 | @property 139 | def message(self) -> List[Tuple[str, List[TypeMessageEntity]]]: 140 | return split_text(self.header, self.footer) 141 | 142 | @property 143 | def caption(self) -> List[Tuple[str, List[TypeMessageEntity]]]: 144 | return split_text(self.header, self.footer, is_caption=True) 145 | 146 | 147 | class PlaylistTextHandler(BaseTextHandler): 148 | def __init__( 149 | self, 150 | vk_api: API, 151 | playlist: AudioPlaylist, 152 | ) -> None: 153 | self._vk_api = vk_api 154 | self._playlist = playlist 155 | 156 | self.header = "" 157 | self.footer = "" 158 | 159 | self._caption = "" 160 | 161 | async def process_text(self) -> None: 162 | header = self._playlist.title 163 | if self._playlist.description: 164 | header += f"\n\n{self.convert_vk_links(self._playlist.description)}" 165 | 166 | post_href = f"https://vk.com/music/playlist/{self._playlist.owner_id}_{self._playlist.id}" 167 | if self._playlist.access_key: 168 | post_href += f"_{self._playlist.access_key}" 169 | vk_link = f"\n\n📌 {get_html_link(post_href, VK_PLAYLIST)}" 170 | 171 | self.header = header 172 | self.footer = vk_link 173 | 174 | @property 175 | def caption(self) -> List[Tuple[str, List[TypeMessageEntity]]]: 176 | return split_text(self.header, self.footer, is_caption=True) 177 | -------------------------------------------------------------------------------- /app/bot/plugins/playlist.py: -------------------------------------------------------------------------------- 1 | import re 2 | from urllib.parse import parse_qs, urlparse 3 | 4 | from telethon import events 5 | from telethon.client.telegramclient import TelegramClient 6 | from telethon.events import StopPropagation 7 | from telethon.tl.custom.button import Button 8 | from telethon.tl.functions.messages import SearchRequest 9 | from telethon.tl.patched import Message 10 | from telethon.tl.types import InputMessagesFilterUrl 11 | from telethon.tl.types.messages import ChannelMessages 12 | from vkbottle.api.api import API 13 | 14 | from app.bot.plugins.common import NewMessageEvent, check_permission, check_state, state_manager 15 | from app.bot.state_manager import State 16 | from app.celery_worker import forward_playlist 17 | from app.config import _, settings 18 | from app.utils.database import VttTaskType, get_queued_task 19 | from app.utils.telegram import get_entity_by_id 20 | from app.utils.vk import get_playlist 21 | 22 | PL_NOT_READY = _("PL_NOT_READY") 23 | PL_SEARCHING = _("PL_SEARCHING") 24 | PL_NOT_FOUND_IN_VK = _("PL_NOT_FOUND_IN_VK") 25 | PL_ALREADY_IN_THE_QUEUE = _("PL_ALREADY_IN_THE_QUEUE") 26 | PL_ALREADY_STARTED = _("PL_ALREADY_STARTED") 27 | PL_FOUND_IN_TGM = _("PL_FOUND_IN_TGM") 28 | PL_NOT_FOUND_IN_TGM = _("PL_NOT_FOUND_IN_TGM") 29 | PL_ADDED_TO_THE_QUEUE = _("PL_ADDED_TO_THE_QUEUE") 30 | PL_UNKNOWN_CHANNEL = _("PL_UNKNOWN_CHANNEL") 31 | PL_YES = _("PL_YES") 32 | PL_CANCEL = _("PL_CANCEL") 33 | 34 | pl_link_pattern = re.compile( 35 | r"(https:\/\/)?(www\.)?(m\.)?vk\.com\/(music(/(playlist|album)|/?\?.+audio_playlist)|\w+/?\?.+audio_playlist)" 36 | ) 37 | 38 | playlist_full_id = re.compile(r"(?P<owner_id>-?\d+)_(?P<playlist_id>\d+)((_|\/)(?P<access_key>[a-z0-9]+))?") 39 | 40 | 41 | async def init(bot: TelegramClient, client: TelegramClient, vk_api: API): 42 | 43 | # Callback for playlist button in main channel 44 | @bot.on(events.CallbackQuery(data=b"wait_for_pl_link")) 45 | async def wait_for_pl_link(event: events.CallbackQuery.Event): 46 | await event.answer(PL_NOT_READY) 47 | 48 | @bot.on(events.CallbackQuery(data=b"pl_confirm", func=lambda e: check_state(e, State.WAITING_FOR_CHOISE))) 49 | async def new_pl(event: events.CallbackQuery.Event): 50 | await event.edit(buttons=Button.clear()) 51 | if not await check_permission(event): 52 | raise events.StopPropagation 53 | 54 | data = state_manager.get_info(event.sender_id)[1] 55 | forward_playlist.delay( 56 | owner_id=data["owner_id"], 57 | playlist_id=data["playlist_id"], 58 | access_key=data["access_key"], 59 | ) 60 | state_manager.clear_info(event.sender_id) 61 | await event.respond(PL_ADDED_TO_THE_QUEUE) 62 | raise StopPropagation 63 | 64 | @bot.on(events.NewMessage(pattern=pl_link_pattern, func=lambda e: check_state(e, State.WAITING_FOR_LINK))) 65 | async def on_new_pl(event: NewMessageEvent): 66 | if not await check_permission(event): 67 | raise events.StopPropagation 68 | 69 | await event.respond(PL_SEARCHING) 70 | sender = event.sender_id 71 | parsed_url = urlparse(event.message.message) 72 | url_path = parsed_url.path 73 | url_query = parse_qs(parsed_url.query) 74 | full_id = "" 75 | 76 | if url_path.startswith("/music/playlist/"): 77 | full_id = url_path.split("/music/playlist/")[1] 78 | elif url_path.startswith("/music/album/"): 79 | full_id = url_path.split("/music/album/")[1] 80 | elif url_query: 81 | z = url_query.get("z") 82 | act = url_query.get("act") 83 | pl_unparsed = "" 84 | 85 | if z and z[0].startswith("audio_playlist"): 86 | pl_unparsed = z[0] 87 | elif act and act[0].startswith("audio_playlist"): 88 | pl_unparsed = act[0] 89 | 90 | if pl_unparsed: 91 | full_id = pl_unparsed.split("audio_playlist")[1] 92 | else: 93 | await event.respond("Icorrect link!") 94 | raise StopPropagation 95 | match = playlist_full_id.search(full_id) 96 | groupdict = match.groupdict() 97 | owner_id = groupdict.get("owner_id") 98 | playlist_id = groupdict.get("playlist_id") 99 | access_key = groupdict.get("access_key") 100 | 101 | playlist = await get_playlist(vk_api, owner_id, playlist_id, access_key, with_audios=False) 102 | 103 | if not playlist: 104 | await event.respond(PL_NOT_FOUND_IN_VK) 105 | raise StopPropagation 106 | 107 | queued_task = get_queued_task(owner_id, playlist_id, VttTaskType.playlist) 108 | if queued_task: 109 | if queued_task.status == "SENT": 110 | waiting_text = PL_ALREADY_IN_THE_QUEUE 111 | else: 112 | waiting_text = PL_ALREADY_STARTED 113 | message = await event.respond( 114 | waiting_text, 115 | buttons=[ 116 | Button.inline(PL_YES, data="pl_confirm"), 117 | Button.inline(PL_CANCEL, data=b"cancel"), 118 | ], 119 | ) 120 | state_manager.set_info( 121 | sender, 122 | State.WAITING_FOR_CHOISE, 123 | { 124 | "choice_message": message.id, 125 | "owner_id": owner_id, 126 | "playlist_id": playlist_id, 127 | "access_key": access_key, 128 | }, 129 | ) 130 | raise StopPropagation 131 | 132 | peer = await get_entity_by_id(client, settings.TGM_PL_CHANNEL_ID) 133 | if peer is None: 134 | message = await event.respond(PL_UNKNOWN_CHANNEL) 135 | state_manager.clear_info(event.sender_id) 136 | raise StopPropagation 137 | filter = InputMessagesFilterUrl() 138 | search_result: ChannelMessages = await client( 139 | SearchRequest( 140 | peer=peer, 141 | q=f"https://vk.com/music/playlist/{owner_id}_{playlist_id}", 142 | filter=filter, 143 | min_date=None, 144 | max_date=None, 145 | offset_id=0, 146 | add_offset=0, 147 | limit=1, 148 | max_id=0, 149 | min_id=0, 150 | hash=0, 151 | from_id=None, 152 | ) 153 | ) 154 | waiting_text = PL_NOT_FOUND_IN_TGM 155 | if search_result.messages: 156 | waiting_text = PL_FOUND_IN_TGM 157 | message: Message = search_result.messages[0] 158 | await bot.forward_messages(sender, message.id, from_peer=message.chat_id) 159 | message = await event.respond( 160 | waiting_text, 161 | buttons=[ 162 | Button.inline(PL_YES, data="pl_confirm"), 163 | Button.inline(PL_CANCEL, data=b"cancel"), 164 | ], 165 | ) 166 | 167 | state_manager.set_info( 168 | sender, 169 | State.WAITING_FOR_CHOISE, 170 | { 171 | "choice_message": message.id, 172 | "owner_id": owner_id, 173 | "playlist_id": playlist_id, 174 | "access_key": access_key, 175 | }, 176 | ) 177 | raise StopPropagation 178 | -------------------------------------------------------------------------------- /tunnel/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tunnel", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "ansi-regex": { 8 | "version": "5.0.0", 9 | "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", 10 | "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" 11 | }, 12 | "ansi-styles": { 13 | "version": "4.3.0", 14 | "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", 15 | "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", 16 | "requires": { 17 | "color-convert": "^2.0.1" 18 | } 19 | }, 20 | "axios": { 21 | "version": "0.21.1", 22 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz", 23 | "integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==", 24 | "requires": { 25 | "follow-redirects": "^1.10.0" 26 | } 27 | }, 28 | "cliui": { 29 | "version": "7.0.4", 30 | "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", 31 | "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", 32 | "requires": { 33 | "string-width": "^4.2.0", 34 | "strip-ansi": "^6.0.0", 35 | "wrap-ansi": "^7.0.0" 36 | } 37 | }, 38 | "color-convert": { 39 | "version": "2.0.1", 40 | "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", 41 | "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", 42 | "requires": { 43 | "color-name": "~1.1.4" 44 | } 45 | }, 46 | "color-name": { 47 | "version": "1.1.4", 48 | "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", 49 | "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" 50 | }, 51 | "debug": { 52 | "version": "4.3.1", 53 | "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", 54 | "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", 55 | "requires": { 56 | "ms": "2.1.2" 57 | } 58 | }, 59 | "emoji-regex": { 60 | "version": "8.0.0", 61 | "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", 62 | "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" 63 | }, 64 | "envfile": { 65 | "version": "6.17.0", 66 | "resolved": "https://registry.npmjs.org/envfile/-/envfile-6.17.0.tgz", 67 | "integrity": "sha512-RnhtVw3auDZeeh5VtaNrbE7s6Kq8BoRtGIzcbMpMsJ+wIpRgs5jiDG4gQjW+vfws5QPlizE57/fUU0Tj6Nrs8A==" 68 | }, 69 | "escalade": { 70 | "version": "3.1.1", 71 | "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", 72 | "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" 73 | }, 74 | "follow-redirects": { 75 | "version": "1.14.2", 76 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.2.tgz", 77 | "integrity": "sha512-yLR6WaE2lbF0x4K2qE2p9PEXKLDjUjnR/xmjS3wHAYxtlsI9MLLBJUZirAHKzUZDGLxje7w/cXR49WOUo4rbsA==" 78 | }, 79 | "get-caller-file": { 80 | "version": "2.0.5", 81 | "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", 82 | "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" 83 | }, 84 | "is-fullwidth-code-point": { 85 | "version": "3.0.0", 86 | "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", 87 | "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" 88 | }, 89 | "localtunnel": { 90 | "version": "2.0.1", 91 | "resolved": "https://registry.npmjs.org/localtunnel/-/localtunnel-2.0.1.tgz", 92 | "integrity": "sha512-LiaI5wZdz0xFkIQpXbNI62ZnNn8IMsVhwxHmhA+h4vj8R9JG/07bQHWwQlyy7b95/5fVOCHJfIHv+a5XnkvaJA==", 93 | "requires": { 94 | "axios": "0.21.1", 95 | "debug": "4.3.1", 96 | "openurl": "1.1.1", 97 | "yargs": "16.2.0" 98 | } 99 | }, 100 | "ms": { 101 | "version": "2.1.2", 102 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", 103 | "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" 104 | }, 105 | "openurl": { 106 | "version": "1.1.1", 107 | "resolved": "https://registry.npmjs.org/openurl/-/openurl-1.1.1.tgz", 108 | "integrity": "sha1-OHW0sO96UsFW8NtB1GCduw+Us4c=" 109 | }, 110 | "require-directory": { 111 | "version": "2.1.1", 112 | "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", 113 | "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" 114 | }, 115 | "string-width": { 116 | "version": "4.2.2", 117 | "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", 118 | "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", 119 | "requires": { 120 | "emoji-regex": "^8.0.0", 121 | "is-fullwidth-code-point": "^3.0.0", 122 | "strip-ansi": "^6.0.0" 123 | } 124 | }, 125 | "strip-ansi": { 126 | "version": "6.0.0", 127 | "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", 128 | "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", 129 | "requires": { 130 | "ansi-regex": "^5.0.0" 131 | } 132 | }, 133 | "wrap-ansi": { 134 | "version": "7.0.0", 135 | "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", 136 | "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", 137 | "requires": { 138 | "ansi-styles": "^4.0.0", 139 | "string-width": "^4.1.0", 140 | "strip-ansi": "^6.0.0" 141 | } 142 | }, 143 | "y18n": { 144 | "version": "5.0.8", 145 | "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", 146 | "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" 147 | }, 148 | "yargs": { 149 | "version": "16.2.0", 150 | "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", 151 | "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", 152 | "requires": { 153 | "cliui": "^7.0.2", 154 | "escalade": "^3.1.1", 155 | "get-caller-file": "^2.0.5", 156 | "require-directory": "^2.1.1", 157 | "string-width": "^4.2.0", 158 | "y18n": "^5.0.5", 159 | "yargs-parser": "^20.2.2" 160 | } 161 | }, 162 | "yargs-parser": { 163 | "version": "20.2.9", 164 | "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", 165 | "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==" 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /functions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | prompt_yn() { 4 | local prompt=$1 5 | 6 | while true; do 7 | read -rp "-> $prompt [Y/n]: " yn 8 | case $yn in 9 | [yY][eE][sS]|[yY]|"") 10 | ret_val=1 11 | break 12 | ;; 13 | [nN][oO]|[nN]) 14 | ret_val=0 15 | break 16 | ;; 17 | *) 18 | echo Invalid input, try again... 19 | esac 20 | done 21 | } 22 | 23 | prompt_text() { 24 | local prompt=$1 25 | local regex=$2 26 | local default=$3 27 | 28 | if [ -n "$default" ]; then 29 | prompt="$prompt [$default]" 30 | fi 31 | 32 | while true; do 33 | read -rp "-> $prompt: " ANSWER 34 | if echo "$ANSWER" | grep -qP "$regex"; then 35 | ret_val=$ANSWER 36 | break 37 | elif [ "$ANSWER" == "" ] && [ -n "$default" ]; then 38 | ret_val=$default 39 | break 40 | else 41 | echo Invalid input, try again... 42 | fi 43 | done 44 | } 45 | 46 | set_setting() { 47 | local file=$1 48 | local key=$2 49 | local value=$3 50 | local add_quotes=$4 51 | 52 | if [ "$add_quotes" == "y" ]; then 53 | value="\"$value\"" 54 | fi 55 | 56 | if grep -q "$key=" "$file"; then 57 | # Escape sed characters. 58 | value=$(echo "$value" | sed 's/[\/&]/\\&/g') 59 | sed -i "s/^\s*$key=.*/$key=$value/" "$file" 60 | else 61 | echo "$key=$value" | tee -a "$file" &> /dev/null 62 | fi 63 | } 64 | 65 | 66 | set_env() { 67 | if [ -f ".env" ]; then 68 | prompt_yn "Found .env file. Load it?" 69 | LOAD_ENV=$ret_val 70 | if [ "$LOAD_ENV" -eq 1 ]; then 71 | # Clean from comments and spaces and make all variables in single quotes. 72 | # shellcheck source=/dev/null 73 | if ! source <(sed -e '/^#/d;/^\s*$/d' -e "s/='\(.*\)'/=\1/g" -e "s/=\"\(.*\)\"/=\1/g" -e "s/=\(.*\)/='\1'/g" .env); then 74 | echo "Failed to load .env file." 75 | exit 1 76 | fi 77 | fi 78 | fi 79 | 80 | if [ -z "$VTT_LANGUAGE" ]; then 81 | prompt_text "Enter app's language (available: 'en', 'ru')" "^(en|ru)$" "en" 82 | VTT_LANGUAGE=$ret_val 83 | fi 84 | 85 | if [ -z "$TGM_CHANNEL_USERNAME" ] && [ -z "$TGM_CHANNEL_ID" ]; then 86 | prompt_yn "Is your main Telegram channel public?" 87 | IS_MAIN_PUBLIC=$ret_val 88 | if [[ "$IS_MAIN_PUBLIC" -eq 1 ]]; then 89 | prompt_text "Enter your main Telegram channel name" "^\w+$" 90 | TGM_CHANNEL_USERNAME=$ret_val 91 | else 92 | prompt_text "Enter your main Telegram channel id (starts with '-100')" "^-100\d+$" 93 | TGM_CHANNEL_ID=$ret_val 94 | fi 95 | fi 96 | 97 | if [[ -z "$TGM_PL_CHANNEL_USERNAME" && -z "$TGM_PL_CHANNEL_ID" ]]; then 98 | prompt_yn "Do you want to forward audio playlists (additional Telegram channel required)?" 99 | HAS_PL=$ret_val 100 | if [[ "$HAS_PL" -eq 1 ]]; then 101 | prompt_yn "Is your playlist Telegram channel public?" 102 | IS_PL_PUBLIC=$ret_val 103 | if [[ "$IS_PL_PUBLIC" -eq 1 ]]; then 104 | prompt_text "Enter your playlist Telegram channel name" "^\w+$" 105 | TGM_PL_CHANNEL_USERNAME=$ret_val 106 | else 107 | prompt_text "Enter your playlist Telegram channel id (starts with '-100')" "^-100\d+$" 108 | TGM_PL_CHANNEL_ID=$ret_val 109 | fi 110 | fi 111 | fi 112 | 113 | if [ -z "$SERVER_URL" ]; then 114 | prompt_text "Enter your server URL" "^https?:\/\/.+$" 115 | SERVER_URL=$ret_val 116 | fi 117 | 118 | if [ -z "$VK_COMMUNITY_ID" ]; then 119 | prompt_text "Enter your VK community id" "^[0-9]+$" 120 | VK_COMMUNITY_ID=$ret_val 121 | fi 122 | 123 | if [ -z "$VK_COMMUNITY_TOKEN" ]; then 124 | prompt_text "Enter your VK community token" "^.+$" 125 | VK_COMMUNITY_TOKEN=$ret_val 126 | fi 127 | 128 | if [ -z "$VK_SERVER_TITLE" ]; then 129 | prompt_text "Enter title for your VK Callback API server (1-14 characters)" "^.{1,14}$" 130 | VK_SERVER_TITLE=$ret_val 131 | fi 132 | 133 | if [ -z "$TGM_BOT_TOKEN" ]; then 134 | prompt_text "Enter your Telegram bot token" "^.+$" 135 | TGM_BOT_TOKEN=$ret_val 136 | fi 137 | 138 | if [ -z "$TGM_API_ID" ]; then 139 | prompt_text "Enter your Telegram app id" "^[0-9]+$" 140 | TGM_API_ID=$ret_val 141 | fi 142 | 143 | if [ -z "$TGM_API_HASH" ]; then 144 | prompt_text "Enter your Telegram app hash" "^.+$" 145 | TGM_API_HASH=$ret_val 146 | fi 147 | 148 | if [ -z "$TGM_CLIENT_PHONE" ]; then 149 | prompt_text "Enter your Telegram phone number" "^\+?[0-9]+$" 150 | TGM_CLIENT_PHONE=$ret_val 151 | fi 152 | 153 | if [ -z "$VK_LOGIN" ]; then 154 | prompt_text "Enter your VK login" "^.+$" 155 | VK_LOGIN=$ret_val 156 | fi 157 | 158 | if [ -z "$VK_PASSWORD" ]; then 159 | prompt_text "Enter your VK password" "^.+$" 160 | VK_PASSWORD=$ret_val 161 | fi 162 | 163 | echo "Setting up .env variables..." 164 | if [ ! -f ".env" ]; then 165 | touch .env 166 | fi 167 | set_setting ".env" "VTT_LANGUAGE" "$VTT_LANGUAGE" "y" 168 | if [ -z "$TGM_CHANNEL_USERNAME" ]; then 169 | set_setting ".env" "TGM_CHANNEL_USERNAME" "$TGM_CHANNEL_USERNAME" "y" 170 | fi 171 | if [ -z "$TGM_CHANNEL_ID" ]; then 172 | set_setting ".env" "TGM_CHANNEL_ID" "$TGM_CHANNEL_ID" "y" 173 | fi 174 | if [[ "$HAS_PL" -eq 1 ]]; then 175 | if [[ "$IS_PL_PUBLIC" -eq 1 ]]; then 176 | set_setting ".env" "TGM_PL_CHANNEL_USERNAME" "$TGM_PL_CHANNEL_USERNAME" "y" 177 | else 178 | set_setting ".env" "TGM_PL_CHANNEL_ID" "$TGM_PL_CHANNEL_ID" "y" 179 | fi 180 | fi 181 | set_setting ".env" "SERVER_URL" "$SERVER_URL" "y" 182 | set_setting ".env" "VK_COMMUNITY_ID" "$VK_COMMUNITY_ID" "y" 183 | set_setting ".env" "VK_COMMUNITY_TOKEN" "$VK_COMMUNITY_TOKEN" "y" 184 | set_setting ".env" "VK_SERVER_TITLE" "$VK_SERVER_TITLE" "y" 185 | set_setting ".env" "TGM_BOT_TOKEN" "$TGM_BOT_TOKEN" "y" 186 | set_setting ".env" "TGM_API_ID" "$TGM_API_ID" "y" 187 | set_setting ".env" "TGM_API_HASH" "$TGM_API_HASH" "y" 188 | set_setting ".env" "TGM_CLIENT_PHONE" "$TGM_CLIENT_PHONE" "y" 189 | set_setting ".env" "VK_LOGIN" "$VK_LOGIN" "y" 190 | set_setting ".env" "VK_PASSWORD" "$VK_PASSWORD" "y" 191 | 192 | NGINX_HOST=$(echo "$SERVER_URL" | grep -Po 'https?://\K[^/]+') 193 | set_setting ".env" "NGINX_HOST" "$NGINX_HOST" "y" 194 | echo "Environment variables are set." 195 | } 196 | 197 | setup_nginx() { 198 | if ! command -v nginx &> /dev/null; then 199 | echo "Nginx is not installed! Aborting." 200 | exit 1 201 | fi 202 | 203 | if [ -z "$NGINX_HOST" ]; then 204 | prompt_text "Enter your server name" "^.+$" 205 | NGINX_HOST=$ret_val 206 | fi 207 | 208 | echo "Setting up Nginx config..." 209 | 210 | sudo mkdir -p /etc/nginx/sites-available 211 | sudo cp -f "setup/nginx/vtt-cb-receiver.conf" "/etc/nginx/sites-available/" 212 | 213 | if ! grep -qx "\s*server_name\s*$NGINX_HOST;" "/etc/nginx/sites-available/vtt-cb-receiver.conf"; then 214 | sudo sed -i "/^\s*server {/a \ \ \ \ server_name $NGINX_HOST;" "/etc/nginx/sites-available/vtt-cb-receiver.conf" 215 | fi 216 | 217 | sudo mkdir -p /etc/nginx/sites-enabled 218 | sudo ln -sf "/etc/nginx/sites-available/vtt-cb-receiver.conf" "/etc/nginx/sites-enabled/" 219 | 220 | echo "Reloading Nginx..." 221 | sudo systemctl reload nginx 222 | } 223 | -------------------------------------------------------------------------------- /app/utils/vk.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from typing import Callable, List, Optional, Union 4 | 5 | from vkbottle import AiohttpClient, VKAPIError 6 | from vkbottle.api.api import API 7 | from vkbottle.api.request_validator import ABCRequestValidator 8 | from vkbottle_types import API_VERSION 9 | from vkbottle_types.methods.groups import GroupsCategory 10 | from vkbottle_types.objects import ( 11 | AudioAudio, 12 | GroupsCallbackServer, 13 | PhotosPhotoSizes, 14 | PhotosPhotoSizesType, 15 | VideoVideoFiles, 16 | ) 17 | from vkbottle_types.responses.wall import GetByIdExtendedResponseModel 18 | 19 | from app.config import settings 20 | from app.schemas.vk import AudioPlaylist, VkApiAudioPlaylist 21 | 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | async def setup_vk_server(): 26 | logger.info("[VK] Setting up callback server...") 27 | vk_group = GroupsCategory( 28 | API( 29 | token=settings.VK_COMMUNITY_TOKEN, 30 | http_client=AiohttpClient(), 31 | ), 32 | ) 33 | group_id = settings.VK_COMMUNITY_ID 34 | server_url = settings.SERVER_URL 35 | server_title = settings.VK_SERVER_TITLE 36 | try: 37 | confirm = await vk_group.get_callback_confirmation_code(group_id=group_id) 38 | os.environ.setdefault("VK_CONFIRM_CODE", confirm.code) 39 | logger.info(f"[VK] Callback code to confirm: {confirm.code}") 40 | 41 | server_id: Optional[int] = None 42 | secret_key = settings.VK_SERVER_SECRET 43 | 44 | servs = await vk_group.get_callback_servers(group_id=group_id) 45 | if not servs.items: 46 | new_serv = await vk_group.add_callback_server( 47 | group_id=group_id, 48 | url=server_url, 49 | title=server_title, 50 | secret_key=secret_key, 51 | ) 52 | server_id = new_serv.server_id 53 | logger.info("[VK] No callback servers found, added new.") 54 | else: 55 | find_by_title: Callable[[GroupsCallbackServer], GroupsCallbackServer] = lambda x: x.title == server_title 56 | main_serv: Optional[GroupsCallbackServer] = next(filter(find_by_title, servs.items), None) 57 | if main_serv: 58 | await vk_group.edit_callback_server( 59 | group_id=group_id, 60 | server_id=main_serv.id, 61 | url=server_url, 62 | title=main_serv.title, 63 | secret_key=secret_key, 64 | ) 65 | server_id = main_serv.id 66 | logger.info(f"[VK] Using the existing callback server: {main_serv.title}") 67 | else: 68 | new_serv = await vk_group.add_callback_server( 69 | group_id=group_id, 70 | url=server_url, 71 | title=server_title, 72 | secret_key=secret_key, 73 | ) 74 | server_id = new_serv.server_id 75 | logger.info(f'[VK] No callback server found by title "{server_title}", added new.') 76 | 77 | await vk_group.set_callback_settings( 78 | group_id=group_id, 79 | server_id=server_id, 80 | api_version=API_VERSION, 81 | wall_post_new=True, 82 | ) 83 | logger.info("[VK] The callback server settings has been set.") 84 | finally: 85 | await vk_group.api.http_client.close() 86 | 87 | 88 | async def get_playlist( 89 | vk_api: API, 90 | owner_id: int, 91 | playlist_id: int, 92 | access_key: Optional[str] = None, 93 | with_audios: bool = True, 94 | ) -> Union[AudioPlaylist, None]: 95 | playlist_info = None 96 | try: 97 | playlist_info = ( 98 | await vk_api.request( 99 | "audio.getPlaylistById", 100 | { 101 | "owner_id": owner_id, 102 | "playlist_id": playlist_id, 103 | "access_key": access_key, 104 | }, 105 | ) 106 | )["response"] 107 | except VKAPIError as error: 108 | pl_full_id = f"{owner_id}_{playlist_id}" 109 | if access_key: 110 | pl_full_id += f"_{access_key}" 111 | logger.warning(f"Failed to get playlist (https://vk.com/music/album/{pl_full_id}): {error.description}") 112 | 113 | if not playlist_info: 114 | return None 115 | 116 | playlist_info = VkApiAudioPlaylist(**playlist_info) 117 | 118 | full_title = playlist_info.title 119 | if playlist_info.main_artists: 120 | artists = ", ".join([artist.name for artist in playlist_info.main_artists]) 121 | full_title = f"{artists} - {playlist_info.title}" 122 | 123 | playlist_photo = None 124 | if playlist_info.photo: 125 | playlist_photo = playlist_info.photo.photo_1200 126 | elif playlist_info.thumbs: 127 | playlist_photo = playlist_info.thumbs[0].photo_1200 128 | 129 | playlist_audios = [] 130 | if with_audios: 131 | playlist_audios = ( 132 | await vk_api.request( 133 | "audio.get", 134 | { 135 | "owner_id": owner_id, 136 | "playlist_id": playlist_id, 137 | "count": playlist_info.count, 138 | "access_key": access_key, 139 | }, 140 | ) 141 | )["response"]["items"] 142 | playlist_audios = [AudioAudio(**audio) for audio in playlist_audios if audio.get("url")] 143 | return AudioPlaylist( 144 | id=playlist_id, 145 | owner_id=owner_id, 146 | access_key=access_key, 147 | full_id=f"{owner_id}_{playlist_id}_{access_key}", 148 | title=full_title, 149 | description=playlist_info.description, 150 | photo=playlist_photo, 151 | audios=playlist_audios, 152 | ) 153 | 154 | 155 | async def get_extended_wall( 156 | vk_api: API, 157 | owner_id: int, 158 | wall_id: int, 159 | ) -> Union[GetByIdExtendedResponseModel, None]: 160 | try: 161 | wall_info: GetByIdExtendedResponseModel = await vk_api.wall.get_by_id( 162 | posts=[f"{owner_id}_{wall_id}"], 163 | copy_history_depth=100, 164 | extended=True, 165 | ) 166 | if not wall_info.items: 167 | return None 168 | return wall_info 169 | except VKAPIError as error: 170 | logger.warning(f"Failed to get wall post (https://vk.com/wall/{owner_id}_{wall_id}): {error.description}") 171 | return None 172 | 173 | 174 | def get_video_url(formats: Optional[VideoVideoFiles]) -> Union[str, None]: 175 | if not formats: 176 | return None 177 | url = formats.mp4_720 or formats.mp4_480 or formats.mp4_360 or formats.mp4_240 or formats.flv_320 178 | return url 179 | 180 | 181 | # Filter cropped photo sizes 182 | photo_sizes = [ 183 | size 184 | for size in PhotosPhotoSizesType 185 | if size 186 | not in ( 187 | PhotosPhotoSizesType.O, 188 | PhotosPhotoSizesType.P, 189 | PhotosPhotoSizesType.Q, 190 | PhotosPhotoSizesType.R, 191 | ) 192 | ] 193 | 194 | 195 | def get_photo_url(sizes: Optional[List[PhotosPhotoSizes]]) -> Union[str, None]: 196 | if not sizes: 197 | return None 198 | 199 | max_photo = (None, None) 200 | for size in sizes: 201 | try: 202 | current_index = photo_sizes.index(size.type) 203 | except ValueError: 204 | continue 205 | if not max_photo[0] or (current_index > photo_sizes.index(max_photo[0])): 206 | max_photo = (size.type, size.url) 207 | return max_photo[1] 208 | 209 | 210 | class VkLangRequestValidator(ABCRequestValidator): 211 | async def validate(self, request: dict) -> dict: 212 | request["lang"] = settings.VK_API_LANGUAGE 213 | return request 214 | -------------------------------------------------------------------------------- /app/config.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import gettext 3 | import logging 4 | import re 5 | import secrets 6 | import sys 7 | from typing import Callable 8 | 9 | from aiohttp import ClientSession 10 | from dotenv.main import set_key 11 | from pydantic import BaseSettings, root_validator, validator 12 | from telethon import TelegramClient 13 | from telethon.sessions import MemorySession 14 | from telethon.utils import get_peer_id 15 | from vkaudiotoken import TwoFAHelper, get_kate_token, get_vk_official_token, supported_clients 16 | from vkaudiotoken.CommonParams import CommonParams 17 | from vkaudiotoken.TokenException import TokenException 18 | from vkbottle import AiohttpClient 19 | from vkbottle.api.api import API 20 | from vkbottle.exception_factory import VKAPIError 21 | 22 | from app.utils.telegram import get_entity_by_username 23 | 24 | logger = logging.getLogger(__name__) 25 | 26 | vk_lang_pattern = re.compile(r"^(ru|uk|be|en|es|fi|de|it)$") 27 | 28 | 29 | async def get_tgm_channel_id(client: TelegramClient, key_to_set: str, channel_username: str): 30 | entity = await get_entity_by_username(client, channel_username) 31 | if not entity: 32 | raise ValueError(f"Failed to get {key_to_set}.") 33 | channel_id = get_peer_id(entity) 34 | set_key(".env", key_to_set, channel_id, quote_mode="never") 35 | return channel_id 36 | 37 | 38 | def handle_2fa( 39 | user_agent: str, 40 | t_name: str, 41 | validation_sid: str, 42 | ) -> str: 43 | params = CommonParams(user_agent) 44 | try: 45 | TwoFAHelper(params).validate_phone(validation_sid) 46 | logger.warning("SMS should be sent") 47 | except TokenException as error: 48 | error_extra: dict = error.extra or {} 49 | error_obj: dict = error_extra.get("error", {}) 50 | error_code = error_obj.get("error_code") if error_obj else None 51 | if error_code is None or error_code != 103: 52 | raise 53 | while True: 54 | try: 55 | return str(int(input(f"[{t_name}] Enter auth code: "))) 56 | except ValueError: 57 | logger.warning("Please enter integer code.") 58 | 59 | 60 | def get_new_vk_token( 61 | login: str, 62 | password: str, 63 | user_agent: str, 64 | get_token: Callable[[str, str, str, str, str], str], 65 | t_name: str, 66 | ): 67 | if not login and not password: 68 | logger.critical("Environment variables VK_LOGIN and VK_PASSWORD are required.") 69 | sys.exit(1) 70 | logger.info(f"[{t_name}] Getting new token...") 71 | auth_code = "GET_CODE" 72 | captcha_sid = None 73 | captcha_key = None 74 | while True: 75 | try: 76 | current_token = get_token( 77 | login, 78 | password, 79 | auth_code=auth_code, 80 | captcha_sid=captcha_sid, 81 | captcha_key=captcha_key, 82 | )["token"] 83 | if current_token: 84 | set_key(".env", t_name, current_token) 85 | break 86 | except TokenException as err: 87 | err_code: int = err.code 88 | err_extra: dict = err.extra or {} 89 | if err_code == TokenException.TOKEN_NOT_RECEIVED: 90 | auth_code = "GET_CODE" 91 | captcha_sid = None 92 | captcha_key = None 93 | continue 94 | if err_code == TokenException.CAPTCHA_REQ and "captcha_sid" in err_extra: 95 | captcha_sid = err_extra["captcha_sid"] 96 | captcha_key = input("Enter captcha key from image (" + err_extra["captcha_img"] + "): ") 97 | continue 98 | if err_code == TokenException.TWOFA_REQ and "validation_sid" in err_extra: 99 | auth_code = handle_2fa(user_agent, t_name, err_extra["validation_sid"]) 100 | else: 101 | raise 102 | return current_token 103 | 104 | 105 | async def get_validated_vk_token( 106 | login: str, 107 | password: str, 108 | user_agent: str, 109 | t_name: str, 110 | current_token: str = "", 111 | exit_on_error: bool = False, 112 | is_kate: bool = True, 113 | ) -> str: 114 | vk_user = API( 115 | token=current_token, 116 | http_client=AiohttpClient(session=ClientSession(headers={"User-agent": user_agent})), 117 | ) 118 | try: 119 | logger.info(f"[{t_name}] Checking if token is valid...") 120 | await vk_user.users.get() 121 | logger.info(f"[{t_name}] Token is valid.") 122 | except VKAPIError[5] as error: 123 | err_msg = error.description 124 | logger.warning(f"[{t_name}] Token is not valid: {err_msg}") 125 | if exit_on_error: 126 | sys.exit(err_msg) 127 | else: 128 | current_token = await get_vk_token(login, password, "", exit_on_error=True, is_kate=is_kate) 129 | finally: 130 | await vk_user.http_client.close() 131 | return current_token 132 | 133 | 134 | async def get_vk_token( 135 | login: str, 136 | password: str, 137 | current_token: str = "", 138 | exit_on_error: bool = False, 139 | is_kate: bool = True, 140 | ): 141 | if is_kate: 142 | user_agent = supported_clients.KATE.user_agent 143 | get_token = get_kate_token 144 | t_name = "KATE_TOKEN" 145 | else: 146 | user_agent = supported_clients.VK_OFFICIAL.user_agent 147 | get_token = get_vk_official_token 148 | t_name = "VK_OFFICIAL_TOKEN" 149 | if not current_token: 150 | current_token = get_new_vk_token(login, password, user_agent, get_token, t_name) 151 | 152 | return await get_validated_vk_token( 153 | login, 154 | password, 155 | user_agent, 156 | t_name, 157 | current_token, 158 | exit_on_error, 159 | is_kate, 160 | ) 161 | 162 | 163 | class Settings(BaseSettings): 164 | VK_LOGIN: str = "" 165 | VK_PASSWORD: str = "" 166 | 167 | VK_COMMUNITY_ID: int 168 | VK_COMMUNITY_TOKEN: str 169 | 170 | VK_SERVER_TITLE: str 171 | VK_SERVER_SECRET: str = secrets.token_hex(25) 172 | 173 | # Id is 0 by default for root_validator 174 | TGM_CHANNEL_ID: int = 0 175 | TGM_CHANNEL_USERNAME: str = "" 176 | TGM_PL_CHANNEL_ID: int = 0 177 | TGM_PL_CHANNEL_USERNAME: str = "" 178 | 179 | TGM_CLIENT_PHONE: str = "" 180 | TGM_BOT_TOKEN: str 181 | 182 | TGM_API_ID: int 183 | TGM_API_HASH: str 184 | 185 | SERVER_URL: str 186 | 187 | KATE_TOKEN: str = "" 188 | VK_OFFICIAL_TOKEN: str = "" 189 | 190 | VTT_LANGUAGE: str = "en" 191 | VK_API_LANGUAGE: str = "" 192 | 193 | VK_IGNORE_ADS: bool = True 194 | 195 | CELERY_BROKER_URL: str = "amqp://guest:guest@localhost:5672//" 196 | CELERY_RESULT_BACKEND: str = "db+sqlite:///celery-results.db" 197 | 198 | @validator("VK_SERVER_TITLE") 199 | def check_vk_server_title(cls, value: str): 200 | title_length = len(value) 201 | if title_length < 1 or title_length > 14: 202 | raise ValueError("VK_SERVER_TITLE must have length of 1-14 characters.") 203 | return value 204 | 205 | @validator("SERVER_URL") 206 | def check_server_url(cls, value: str): 207 | if not re.fullmatch(r"^https?://.*", value): 208 | raise ValueError("SERVER_URL must start with 'http[s]://'.") 209 | if not value.endswith("/"): 210 | value = f"{value}/" 211 | return value 212 | 213 | @validator("VTT_LANGUAGE") 214 | def check_vtt_lang(cls, value: str): 215 | if not gettext.find("vtt", "locale", languages=[value]): 216 | raise ValueError("No such locale available for VTT_LANGUAGE.") 217 | return value 218 | 219 | @validator("VK_API_LANGUAGE") 220 | def check_vk_api_lang(cls, value: str): 221 | if value and not vk_lang_pattern.fullmatch(value): 222 | raise ValueError("No such locale available for VK_API_LANGUAGE.") 223 | return value 224 | 225 | @staticmethod 226 | async def _async_check_all(values: dict): 227 | if not values["VK_API_LANGUAGE"]: 228 | VTT_LANGUAGE: str = values["VTT_LANGUAGE"] 229 | if vk_lang_pattern.fullmatch(VTT_LANGUAGE): 230 | values["VK_API_LANGUAGE"] = VTT_LANGUAGE 231 | else: 232 | values["VK_API_LANGUAGE"] = "en" 233 | 234 | TGM_CHANNEL_ID: str = values["TGM_CHANNEL_ID"] 235 | TGM_PL_CHANNEL_ID: str = values["TGM_PL_CHANNEL_ID"] 236 | if not TGM_CHANNEL_ID or not TGM_PL_CHANNEL_ID: 237 | client = TelegramClient(MemorySession(), values["TGM_API_ID"], values["TGM_API_HASH"]) 238 | async with await client.start(bot_token=values["TGM_BOT_TOKEN"]): # type: ignore 239 | if not TGM_CHANNEL_ID: 240 | TGM_CHANNEL_USERNAME: str = values["TGM_CHANNEL_USERNAME"] 241 | if not TGM_CHANNEL_USERNAME: 242 | raise ValueError("TGM_CHANNEL_ID or TGM_CHANNEL_USERNAME is required.") 243 | values["TGM_CHANNEL_ID"] = await get_tgm_channel_id( 244 | client=client, 245 | key_to_set="TGM_CHANNEL_ID", 246 | channel_username=TGM_CHANNEL_USERNAME, 247 | ) 248 | 249 | TGM_PL_CHANNEL_USERNAME: str = values["TGM_PL_CHANNEL_USERNAME"] 250 | if not TGM_PL_CHANNEL_ID and TGM_PL_CHANNEL_USERNAME: 251 | TGM_PL_CHANNEL_ID = await get_tgm_channel_id( 252 | client=client, 253 | key_to_set="TGM_PL_CHANNEL_ID", 254 | channel_username=TGM_PL_CHANNEL_USERNAME, 255 | ) 256 | 257 | KATE_TOKEN: str = values["KATE_TOKEN"] 258 | VK_OFFICIAL_TOKEN: str = values["VK_OFFICIAL_TOKEN"] 259 | if not KATE_TOKEN or not VK_OFFICIAL_TOKEN: 260 | VK_LOGIN: str = values["VK_LOGIN"] 261 | VK_PASSWORD: str = values["VK_PASSWORD"] 262 | if not VK_LOGIN or not VK_PASSWORD: 263 | raise ValueError("Either VK_LOGIN and VK_PASSWORD or KATE_TOKEN and VK_OFFICIAL_TOKEN are required.") 264 | values["KATE_TOKEN"] = await get_vk_token( 265 | VK_LOGIN, 266 | VK_PASSWORD, 267 | KATE_TOKEN, 268 | ) 269 | values["VK_OFFICIAL_TOKEN"] = await get_vk_token( 270 | VK_LOGIN, 271 | VK_PASSWORD, 272 | VK_OFFICIAL_TOKEN, 273 | is_kate=False, 274 | ) 275 | 276 | @root_validator(skip_on_failure=True) 277 | def check_all(cls, values: dict): 278 | loop = asyncio.get_event_loop() 279 | if loop.is_running(): 280 | loop.create_task(cls._async_check_all(values)) 281 | else: 282 | loop.run_until_complete(cls._async_check_all(values)) 283 | return values 284 | 285 | def __init__(self, **kwargs) -> None: 286 | super().__init__(**kwargs) 287 | 288 | class Config: 289 | env_file = ".env" 290 | env_file_encoding = "utf-8" 291 | 292 | 293 | settings = Settings() 294 | 295 | _ = gettext.translation("vtt", "locale", languages=[settings.VTT_LANGUAGE]).gettext 296 | -------------------------------------------------------------------------------- /app/handlers/wall.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import re 3 | from typing import List, Optional 4 | from urllib.parse import parse_qs, urlparse 5 | 6 | import vkbottle_types 7 | from aiohttp import ClientSession 8 | from telethon.client.telegramclient import TelegramClient 9 | from telethon.extensions import html 10 | from telethon.tl.custom.button import Button 11 | from telethon.tl.types import InputGeoPoint, InputMediaGeoLive, InputMediaPoll, Message, Poll, PollAnswer 12 | from vkaudiotoken import supported_clients 13 | from vkbottle import AiohttpClient 14 | from vkbottle.api.api import API 15 | from vkbottle_types.objects import ( 16 | AudioAudio, 17 | BasePropertyExists, 18 | GroupsGroupFull, 19 | WallWallpostAttachmentType, 20 | WallWallpostFull, 21 | ) 22 | 23 | from app.config import _, settings 24 | from app.handlers.text import PlaylistTextHandler, WallTextHandler 25 | from app.schemas.vk import Attachments, AudioPlaylist, Document, VttLink, VttMarket, VttVideo 26 | from app.utils.downloader import Downloader 27 | from app.utils.telegram import get_message_link 28 | from app.utils.vk import VkLangRequestValidator, get_extended_wall, get_photo_url, get_playlist, get_video_url 29 | 30 | logger = logging.getLogger(__name__) 31 | 32 | PL_SOON = _("PL_SOON") 33 | 34 | 35 | class WallHandler: 36 | API_VERSION = vkbottle_types.API_VERSION 37 | MAX_MESSAGE_LENGTH = 4096 38 | 39 | def __init__( 40 | self, 41 | owner_id: int, 42 | id: int, 43 | tgm_bot: TelegramClient, 44 | ) -> None: 45 | self.channel_id = settings.TGM_CHANNEL_ID 46 | self.pl_channel_id = settings.TGM_PL_CHANNEL_ID 47 | self.tgm_bot = tgm_bot 48 | 49 | self.owner_id = owner_id 50 | self.wall_id = id 51 | self.groups: Optional[List[GroupsGroupFull]] = None 52 | 53 | self.kate_user = API( 54 | token=settings.KATE_TOKEN, 55 | http_client=AiohttpClient( 56 | session=ClientSession( 57 | headers={"User-agent": supported_clients.KATE.user_agent}, 58 | ), 59 | ), 60 | ) 61 | self.kate_user.request_validators.append(VkLangRequestValidator()) 62 | 63 | self.vk_user = API( 64 | token=settings.VK_OFFICIAL_TOKEN, 65 | http_client=AiohttpClient( 66 | session=ClientSession( 67 | headers={"User-agent": supported_clients.VK_OFFICIAL.user_agent}, 68 | ), 69 | ), 70 | ) 71 | self.vk_user.request_validators.append(VkLangRequestValidator()) 72 | 73 | async def __aenter__(self): 74 | return self 75 | 76 | async def __aexit__(self, exc_type, exc_value, traceback): 77 | await self.kate_user.http_client.close() 78 | await self.vk_user.http_client.close() 79 | 80 | async def collect_attachments(self, wall: WallWallpostFull) -> Attachments: 81 | attachments = Attachments() 82 | 83 | if not wall.attachments: 84 | return attachments 85 | logger.info("Collecting attachments...") 86 | 87 | audio_ids: List[str] = [] 88 | video_ids: List[str] = [] 89 | for attachment in wall.attachments: 90 | attachment_type = attachment.type 91 | if attachment_type == WallWallpostAttachmentType.PHOTO: 92 | photo = attachment.photo 93 | if not photo: 94 | continue 95 | photo_url = get_photo_url(photo.sizes) 96 | if not photo_url: 97 | continue 98 | attachments.photos.append(photo_url) 99 | elif attachment_type == WallWallpostAttachmentType.AUDIO: 100 | audio = attachment.audio 101 | if not audio: 102 | continue 103 | audio_ids.append(f"{audio.owner_id}_{audio.id}_{audio.access_key}") 104 | elif attachment_type == WallWallpostAttachmentType.VIDEO: 105 | video = attachment.video 106 | if not video: 107 | continue 108 | video_ids.append(f"{video.owner_id}_{video.id}_{video.access_key}") 109 | elif attachment_type == WallWallpostAttachmentType.DOC: 110 | document = attachment.doc 111 | if not (document and document.url): 112 | continue 113 | attachments.documents.append( 114 | Document( 115 | url=document.url, 116 | extension=document.ext, 117 | ) 118 | ) 119 | elif attachment_type == WallWallpostAttachmentType.MARKET: 120 | market = attachment.market 121 | if not market: 122 | continue 123 | attachments.market = VttMarket( 124 | id=market.id, 125 | owner_id=market.owner_id, 126 | title=market.title, 127 | ) 128 | elif attachment_type == WallWallpostAttachmentType.POLL: 129 | poll = attachment.poll 130 | if not poll: 131 | continue 132 | answers = [PollAnswer(answer.text, str(index).encode()) for index, answer in enumerate(poll.answers)] 133 | attachments.poll = InputMediaPoll( 134 | poll=Poll( 135 | id=1, 136 | question=poll.question, 137 | answers=answers, 138 | multiple_choice=poll.multiple, 139 | ) 140 | ) 141 | elif attachment_type == WallWallpostAttachmentType.LINK: 142 | link = attachment.link 143 | if not link: 144 | continue 145 | parsed_link = urlparse(link.url) 146 | 147 | # Not a VK link 148 | if parsed_link.netloc not in {"vk.com", "m.vk.com"}: 149 | attachments.link = VttLink( 150 | caption=link.caption or parsed_link.netloc, 151 | url=link.url, 152 | ) 153 | continue 154 | 155 | if parsed_link.netloc == "m.vk.com": 156 | parsed_link = parsed_link._replace(netloc="vk.com") 157 | 158 | # Playlist 159 | query = parse_qs(parsed_link.query) 160 | if settings.TGM_PL_CHANNEL_ID and "act" in query and query["act"][0].startswith("audio_playlist"): 161 | pattern = re.compile(r"(?P<owner_id>-?\d+)_(?P<playlist_id>\d+)") 162 | match = pattern.search(query["act"][0]) 163 | if not match: 164 | continue 165 | owner_id = match.group("owner_id") 166 | if not owner_id: 167 | continue 168 | playlist_id = match.group("playlist_id") 169 | if not playlist_id: 170 | continue 171 | 172 | access_key = None 173 | if "access_hash" in query: 174 | access_key = query["access_hash"][0] 175 | 176 | playlist = await get_playlist( 177 | self.kate_user, 178 | owner_id, 179 | playlist_id, 180 | access_key, 181 | with_audios=False, 182 | ) 183 | if playlist: 184 | attachments.audio_playlist = playlist 185 | continue 186 | 187 | # Everything else 188 | attachments.link = VttLink( 189 | caption=parsed_link.netloc, 190 | url=parsed_link.geturl(), 191 | ) 192 | 193 | if audio_ids: 194 | audios: List[dict] = ( 195 | await self.kate_user.request( 196 | "audio.getById", 197 | { 198 | "audios": ",".join(audio_ids), 199 | }, 200 | ) 201 | )["response"] 202 | attachments.audios = [AudioAudio(**audio) for audio in audios if audio.get("url")] 203 | 204 | if video_ids: 205 | videos = (await self.kate_user.video.get(videos=video_ids)).items or [] 206 | 207 | for video in videos: 208 | url = "" 209 | is_live = video.live is BasePropertyExists.property_exists 210 | if is_live: 211 | logger.warning("Found live stream.") 212 | url = f"https://vk.com/video{video.owner_id}_{video.id}" 213 | elif video.platform: 214 | url = video.files and video.files.external 215 | if not url: 216 | logger.warning("External video url not found.") 217 | continue 218 | else: 219 | url = get_video_url(video.files) 220 | if not url: 221 | logger.warning("VK video url not found, trying with another token...") 222 | video_full_id = "{}_{}_{}".format(video.owner_id, video.id, video.access_key) 223 | video = next(iter((await self.vk_user.video.get(videos=[video_full_id])).items or []), None) 224 | if not video: 225 | logger.warning("VK video url not found.") 226 | continue 227 | url = get_video_url(video.files) 228 | if not url: 229 | logger.warning("VK video url not found.") 230 | continue 231 | attachments.videos.append( 232 | VttVideo( 233 | title=video.title or "", 234 | url=url, 235 | platform=video.platform, 236 | is_live=is_live, 237 | ), 238 | ) 239 | return attachments 240 | 241 | async def get_text( 242 | self, 243 | wall: WallWallpostFull, 244 | attachments: Attachments, 245 | is_repost: bool = False, 246 | ): 247 | text = WallTextHandler(self.kate_user, wall, attachments, is_repost, self.groups) 248 | await text.process_text() 249 | return text 250 | 251 | async def get_pl_text( 252 | self, 253 | playlist: AudioPlaylist, 254 | ): 255 | text = PlaylistTextHandler(self.kate_user, playlist) 256 | await text.process_text() 257 | return text 258 | 259 | async def send_main_message( 260 | self, 261 | wall_text: WallTextHandler, 262 | attachments: Attachments, 263 | reply_to_message_id: Optional[int] = None, 264 | ) -> Message: 265 | logger.info("Handling main message...") 266 | caption = wall_text.caption 267 | caption_first = caption[0] if caption else None 268 | caption_first_text = caption_first[0] if caption_first else None 269 | caption_first_entities = caption_first[1] if caption_first else None 270 | caption_first_html = html.unparse(*caption_first) if caption_first else "" 271 | 272 | message = wall_text.message 273 | message_first = message[0] if message else None 274 | message_first_text = message_first[0] if message_first else "" 275 | message_first_entities = message_first[1] if message_first else None 276 | 277 | vk_videos = [v for v in attachments.videos if (v.platform is None and not v.is_live)] 278 | 279 | has_link_preview = attachments.link or any((v.platform or v.is_live) for v in attachments.videos) 280 | 281 | is_caption = False 282 | if attachments.photos: 283 | is_caption = True 284 | async with Downloader() as downloader: 285 | files = await downloader.download_medias(attachments.photos) 286 | if vk_videos: 287 | files += await downloader.download_videos(vk_videos) 288 | main_msg: Message = ( 289 | await self.tgm_bot.send_file( 290 | self.channel_id, 291 | file=files, 292 | caption=caption_first_html, 293 | video_note=True, 294 | link_preview=has_link_preview, 295 | reply_to=reply_to_message_id, 296 | ) 297 | )[0] 298 | elif vk_videos: 299 | is_caption = True 300 | async with Downloader() as downloader: 301 | current_videos = await downloader.download_videos(vk_videos) 302 | main_msg = ( 303 | await self.tgm_bot.send_file( 304 | self.channel_id, 305 | file=current_videos, 306 | caption=caption_first_html, 307 | video_note=True, 308 | link_preview=has_link_preview, 309 | reply_to=reply_to_message_id, 310 | ) 311 | )[0] 312 | elif has_link_preview: 313 | main_msg = await self.tgm_bot.send_message( 314 | self.channel_id, 315 | message=message_first_text, 316 | formatting_entities=message_first_entities, 317 | link_preview=True, 318 | reply_to=reply_to_message_id, 319 | ) 320 | elif attachments.documents: 321 | is_caption = True 322 | document = attachments.documents.pop(0) 323 | async with Downloader() as downloader: 324 | downloaded_documents = await downloader.download_media(document.url) 325 | main_msg = await self.tgm_bot.send_file( 326 | self.channel_id, 327 | file=downloaded_documents, 328 | caption=caption_first_text, 329 | formatting_entities=caption_first_entities, 330 | reply_to=reply_to_message_id, 331 | ) 332 | elif attachments.audios: 333 | is_caption = True 334 | async with Downloader() as downloader: 335 | downloaded_audios = await downloader.download_audios(attachments.audios[:10], self.vk_user) 336 | main_msg = ( 337 | await self.tgm_bot.send_file( 338 | self.channel_id, 339 | caption=[""] * (len(downloaded_audios) - 1) + [caption_first_html], 340 | file=downloaded_audios, 341 | voice_note=True, 342 | reply_to=reply_to_message_id, 343 | ) 344 | )[0] 345 | attachments.audios = attachments.audios[10:] 346 | else: 347 | main_msg = await self.tgm_bot.send_message( 348 | self.channel_id, 349 | message=message_first_text, 350 | formatting_entities=message_first_entities, 351 | link_preview=has_link_preview, 352 | reply_to=reply_to_message_id, 353 | ) 354 | 355 | # Send rest messages 356 | rest_messages = caption[1:] if is_caption else message[1:] 357 | for text, entities in rest_messages: 358 | await self.tgm_bot.send_message( 359 | self.channel_id, 360 | message=text, 361 | formatting_entities=entities, 362 | link_preview=False, 363 | reply_to=main_msg, 364 | ) 365 | logger.info("Main message sent successfully.") 366 | return main_msg 367 | 368 | async def send_replies( 369 | self, 370 | wall: WallWallpostFull, 371 | attachments: Attachments, 372 | main_message_id: int, 373 | ) -> None: 374 | if wall.geo: 375 | logger.info("Sending geo location...") 376 | geo = wall.geo 377 | latitude, longitude = [float(x) for x in geo.coordinates.split(" ")] 378 | await self.tgm_bot.send_file( 379 | self.channel_id, 380 | file=InputMediaGeoLive(geo_point=InputGeoPoint(lat=latitude, long=longitude)), 381 | reply_to=main_message_id, 382 | ) 383 | if attachments.poll: 384 | logger.info("Sending poll...") 385 | await self.tgm_bot.send_file( 386 | self.channel_id, 387 | file=attachments.poll, 388 | reply_to=main_message_id, 389 | ) 390 | if attachments.audios: 391 | logger.info("Sending audios...") 392 | async with Downloader() as downloader: 393 | current_audios = await downloader.download_audios(attachments.audios, self.vk_user) 394 | await self.tgm_bot.send_file( 395 | self.channel_id, 396 | file=current_audios, 397 | voice_note=True, 398 | reply_to=main_message_id, 399 | ) 400 | logger.info("Audios sent successfully.") 401 | if attachments.documents: 402 | logger.info("Sending documents...") 403 | document_urls = [doc.url for doc in attachments.documents] 404 | async with Downloader() as downloader: 405 | document_paths = await downloader.download_medias(document_urls) 406 | await self.tgm_bot.send_file( 407 | self.channel_id, 408 | file=document_paths, 409 | force_document=True, 410 | reply_to=main_message_id, 411 | ) 412 | logger.info("Documents sent successfully.") 413 | if attachments.audio_playlist: 414 | logger.info("Sending playlist...") 415 | playlist = attachments.audio_playlist 416 | 417 | # Send playlist link to the main channel 418 | playlist_text = await self.get_pl_text(playlist) 419 | main_pl_caption = playlist_text.caption 420 | main_pl_caption_first = main_pl_caption[0] if main_pl_caption else None 421 | main_pl_caption_html = html.unparse(*main_pl_caption_first) if main_pl_caption_first else "" 422 | async with Downloader() as downloader: 423 | downloaded_photo = None 424 | if playlist.photo: 425 | downloaded_photo = await downloader.download_media(playlist.photo) 426 | main_pl_link_message = await self.tgm_bot.send_message( 427 | self.channel_id, 428 | message=main_pl_caption_html, 429 | file=downloaded_photo, 430 | buttons=Button.inline(PL_SOON, b"wait_for_pl_link"), 431 | reply_to=main_message_id, 432 | ) 433 | 434 | from app.celery_worker import forward_playlist 435 | 436 | forward_playlist.delay( 437 | owner_id=playlist.owner_id, 438 | playlist_id=playlist.id, 439 | access_key=playlist.access_key, 440 | reply_channel_id=self.channel_id, 441 | reply_message_id=main_pl_link_message.id, 442 | ) 443 | 444 | rest_messages = main_pl_caption[1:] 445 | for text, entities in rest_messages: 446 | await self.tgm_bot.send_message( 447 | self.channel_id, 448 | message=text, 449 | formatting_entities=entities, 450 | link_preview=False, 451 | reply_to=main_pl_link_message, 452 | ) 453 | logger.info(f"[{playlist.full_id}] Playlist sent successfully.") 454 | 455 | async def run(self) -> str: 456 | extended_wall = await get_extended_wall(self.kate_user, self.owner_id, self.wall_id) 457 | if not (extended_wall and extended_wall.items): 458 | return "NOT_FOUND" 459 | 460 | wall = extended_wall.items[0] 461 | if wall.donut and wall.donut.is_donut: 462 | return "IS_DONUT" 463 | 464 | self.groups = extended_wall.groups 465 | 466 | main_attachments = await self.collect_attachments(wall) 467 | main_text = await self.get_text(wall, main_attachments) 468 | 469 | if not wall.copy_history: 470 | main_message = await self.send_main_message(main_text, main_attachments) 471 | reply_id = main_message.id 472 | await self.send_replies(wall, main_attachments, reply_id) 473 | else: 474 | reversed_posts = wall.copy_history[::-1] 475 | reply_id = None 476 | for repost in reversed_posts[:-1]: 477 | repost_attachments = await self.collect_attachments(repost) 478 | 479 | repost_text = await self.get_text( 480 | repost, 481 | repost_attachments, 482 | is_repost=True, 483 | ) 484 | 485 | repost_message = await self.send_main_message( 486 | repost_text, 487 | repost_attachments, 488 | reply_to_message_id=reply_id, 489 | ) 490 | reply_id = repost_message.id 491 | await self.send_replies(repost, repost_attachments, reply_id) 492 | 493 | repost = reversed_posts[-1] 494 | repost_attachments = await self.collect_attachments(repost) 495 | 496 | repost_text = await self.get_text( 497 | repost, 498 | repost_attachments, 499 | is_repost=True, 500 | ) 501 | if not main_text.header: 502 | repost_text.footer += main_text.footer 503 | 504 | main_message = await self.send_main_message( 505 | repost_text, 506 | repost_attachments, 507 | reply_to_message_id=reply_id, 508 | ) 509 | reply_id = main_message.id 510 | await self.send_replies(repost, repost_attachments, reply_id) 511 | 512 | if main_text.header: 513 | await self.send_main_message( 514 | main_text, 515 | main_attachments, 516 | reply_to_message_id=reply_id, 517 | ) 518 | return get_message_link(await self.tgm_bot.get_entity(self.channel_id), main_message.id) 519 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 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 | <one line to give the program's name and a brief idea of what it does.> 635 | Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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 | <program> Copyright (C) <year> <name of author> 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 | <https://www.gnu.org/licenses/>. 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 | <https://www.gnu.org/licenses/why-not-lgpl.html>. 675 | --------------------------------------------------------------------------------