├── .gitattributes
├── requirements.txt
├── .dockerignore
├── WebStreamer
├── server
│ ├── exceptions.py
│ ├── __init__.py
│ └── stream_routes.py
├── __init__.py
├── utils
│ ├── __init__.py
│ ├── time_format.py
│ ├── keepalive.py
│ ├── file_properties.py
│ └── custom_dl.py
├── bot
│ ├── plugins
│ │ ├── start.py
│ │ └── stream.py
│ ├── __init__.py
│ └── clients.py
├── vars.py
└── __main__.py
├── Dockerfile
├── .github
└── workflows
│ └── publish-docker.yml
├── docker-compose.yml
├── .gitignore
├── README.md
├── .pylintrc
└── LICENSE
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiohttp<=3.8.1
2 | pyrogram<=2.0.93
3 | python-dotenv<=0.20.0
4 | TgCrypto<=1.2.5
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .vscode
2 | .git
3 | .gitattributes
4 | .gitignore
5 | .github
6 | LICENSE
7 | README.md
8 |
--------------------------------------------------------------------------------
/WebStreamer/server/exceptions.py:
--------------------------------------------------------------------------------
1 |
2 | class InvalidHash(Exception):
3 | message = "Invalid hash"
4 |
5 | class FIleNotFound(Exception):
6 | message = "File not found"
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.9-alpine
2 |
3 | WORKDIR /app
4 |
5 | COPY requirements.txt ./
6 |
7 | RUN apk add build-base
8 |
9 | RUN pip install --no-cache-dir -r requirements.txt
10 |
11 | COPY . .
12 |
13 | CMD ["python3","-m","WebStreamer"]
14 |
--------------------------------------------------------------------------------
/WebStreamer/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 |
5 | import time
6 | from .vars import Var
7 | from WebStreamer.bot.clients import StreamBot
8 |
9 | __version__ = "2.2.4"
10 | StartTime = time.time()
11 |
--------------------------------------------------------------------------------
/WebStreamer/utils/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | from .keepalive import ping_server
5 | from .time_format import get_readable_time
6 | from .file_properties import get_hash, get_name
7 | from .custom_dl import ByteStreamer
--------------------------------------------------------------------------------
/WebStreamer/server/__init__.py:
--------------------------------------------------------------------------------
1 | # Taken from megadlbot_oss
2 | # Thanks to Eyaadh
3 | # This file is a part of TG-FileStreamBot
4 | # Coding : Jyothis Jayanth [@EverythingSuckz]
5 |
6 | import logging
7 | from aiohttp import web
8 | from .stream_routes import routes
9 |
10 | logger = logging.getLogger("server")
11 |
12 | def web_server():
13 | logger.info("Initializing..")
14 | web_app = web.Application(client_max_size=30000000)
15 | web_app.add_routes(routes)
16 | logger.info("Added routes")
17 | return web_app
18 |
--------------------------------------------------------------------------------
/.github/workflows/publish-docker.yml:
--------------------------------------------------------------------------------
1 | name: Publish Docker
2 |
3 | on:
4 | push:
5 | branches:
6 | - release
7 | workflow_dispatch:
8 |
9 | jobs:
10 | publish-docker:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout repository
15 | uses: actions/checkout@v3
16 |
17 | - name: Login to DockerHub
18 | uses: docker/login-action@v2
19 | with:
20 | username: ${{ secrets.DOCKER_USERNAME }}
21 | password: ${{ secrets.DOCKER_PASSWORD }}
22 |
23 | - name: Build 和 push
24 | uses: docker/build-push-action@v3
25 | with:
26 | context: .
27 | push: true
28 | tags: ${{ secrets.DOCKER_USERNAME }}/tg-filestreambot:latest
29 |
--------------------------------------------------------------------------------
/WebStreamer/bot/plugins/start.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | from pyrogram import filters
5 | from pyrogram.types import Message
6 |
7 | from WebStreamer.vars import Var
8 | from WebStreamer.bot import StreamBot
9 |
10 | @StreamBot.on_message(filters.command(["start", "help"]) & filters.private)
11 | async def start(_, m: Message):
12 | if Var.ALLOWED_USERS and not ((str(m.from_user.id) in Var.ALLOWED_USERS) or (m.from_user.username in Var.ALLOWED_USERS)):
13 | return await m.reply(
14 | "你不在可以使用我的用户的列表中。",
15 | disable_web_page_preview=True, quote=True
16 | )
17 | await m.reply(
18 | f'Hi {m.from_user.mention(style="md")} ,直接发送/转发文件,稍等片刻,机器人将会返回直链。'
19 | )
20 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3.8"
2 |
3 | services:
4 | fsb:
5 | image: rong6233/tg-filestreambot
6 | restart: unless-stopped
7 | container_name: fsb
8 | environment:
9 | - API_ID=0 # 这是您的 Telegram 帐户的 API ID,可以从 my.telegram.org 获取。
10 | - API_HASH=e83e839202 # 这是您的 Telegram 帐户的 API 哈希值,也可以从 my.telegram.org 获取。
11 | - BOT_TOKEN=token # 这是机器人令牌,可以从 @BotFather 获取。
12 | - BIN_CHANNEL=ID # 这是日志通道的通道 ID。
13 | - PORT=9191 # 这是应用程序的端口。
14 | - NO_PORT=true # 这可以是 True 或 False。如果设置为 True,则不会显示端口。
15 | - FQDN=example.com # 完全限定的域名(如果存在)。默认为 WEB_SERVER_BIND_ADDRESS的值
16 | - HAS_SSL=true # 这可以是 True 或 False。如果设置为 True,则将启用 SSL。
17 | ports:
18 | - 127.0.0.1:9191:9191
19 | volumes:
20 | - $HOME/TG-FileStreamBot:/app/.env
--------------------------------------------------------------------------------
/WebStreamer/utils/time_format.py:
--------------------------------------------------------------------------------
1 | def get_readable_time(seconds: int) -> str:
2 | count = 0
3 | readable_time = ""
4 | time_list = []
5 | time_suffix_list = ["s", "m", "h", " days"]
6 | while count < 4:
7 | count += 1
8 | if count < 3:
9 | remainder, result = divmod(seconds, 60)
10 | else:
11 | remainder, result = divmod(seconds, 24)
12 | if seconds == 0 and remainder == 0:
13 | break
14 | time_list.append(int(result))
15 | seconds = int(remainder)
16 | for x in range(len(time_list)):
17 | time_list[x] = str(time_list[x]) + time_suffix_list[x]
18 | if len(time_list) == 4:
19 | readable_time += time_list.pop() + ", "
20 | time_list.reverse()
21 | readable_time += ": ".join(time_list)
22 | return readable_time
23 |
--------------------------------------------------------------------------------
/WebStreamer/utils/keepalive.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | import aiohttp
4 | from WebStreamer import Var
5 |
6 | logger = logging.getLogger("keep_alive")
7 |
8 | async def ping_server():
9 | sleep_time = Var.PING_INTERVAL
10 | logger.info("Started with {}s interval between pings".format(sleep_time))
11 | while True:
12 | await asyncio.sleep(sleep_time)
13 | try:
14 | async with aiohttp.ClientSession(
15 | timeout=aiohttp.ClientTimeout(total=10)
16 | ) as session:
17 | async with session.get(Var.URL) as resp:
18 | logger.info("Pinged server with response: {}".format(resp.status))
19 | except TimeoutError:
20 | logger.warning("Couldn't connect to the site URL..")
21 | except Exception:
22 | logger.error("Unexpected error: ", exc_info=True)
23 |
--------------------------------------------------------------------------------
/WebStreamer/bot/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 |
5 | import os
6 | import os.path
7 | from ..vars import Var
8 | import logging
9 | from pyrogram import Client
10 |
11 | logger = logging.getLogger("bot")
12 |
13 | sessions_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sessions")
14 | if Var.USE_SESSION_FILE:
15 | logger.info("Using session files")
16 | logger.info("Session folder path: {}".format(sessions_dir))
17 | if not os.path.isdir(sessions_dir):
18 | os.makedirs(sessions_dir)
19 |
20 | StreamBot = Client(
21 | name="WebStreamer",
22 | api_id=Var.API_ID,
23 | api_hash=Var.API_HASH,
24 | workdir=sessions_dir if Var.USE_SESSION_FILE else "WebStreamer",
25 | plugins={"root": "WebStreamer/bot/plugins"},
26 | bot_token=Var.BOT_TOKEN,
27 | sleep_threshold=Var.SLEEP_THRESHOLD,
28 | workers=Var.WORKERS,
29 | in_memory=not Var.USE_SESSION_FILE,
30 | )
31 |
32 | multi_clients = {}
33 | work_loads = {}
34 |
--------------------------------------------------------------------------------
/WebStreamer/vars.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | import sys
5 | from os import environ
6 | from dotenv import load_dotenv
7 |
8 | load_dotenv()
9 |
10 |
11 | class Var(object):
12 | MULTI_CLIENT = False
13 | API_ID = int(environ.get("API_ID"))
14 | API_HASH = str(environ.get("API_HASH"))
15 | BOT_TOKEN = str(environ.get("BOT_TOKEN"))
16 | SLEEP_THRESHOLD = int(environ.get("SLEEP_THRESHOLD", "60")) # 1 minte
17 | WORKERS = int(environ.get("WORKERS", "6")) # 6 workers = 6 commands at once
18 | BIN_CHANNEL = int(
19 | environ.get("BIN_CHANNEL", None)
20 | ) # you NEED to use a CHANNEL when you're using MULTI_CLIENT
21 | PORT = int(environ.get("PORT", 8080))
22 | BIND_ADDRESS = str(environ.get("WEB_SERVER_BIND_ADDRESS", "0.0.0.0"))
23 | PING_INTERVAL = int(environ.get("PING_INTERVAL", "1200")) # 20 minutes
24 | HAS_SSL = str(environ.get("HAS_SSL", "0").lower()) in ("1", "true", "t", "yes", "y")
25 | NO_PORT = str(environ.get("NO_PORT", "0").lower()) in ("1", "true", "t", "yes", "y")
26 | HASH_LENGTH = int(environ.get("HASH_LENGTH", 6))
27 | if not 5 < HASH_LENGTH < 64:
28 | sys.exit("Hash length should be greater than 5 and less than 64")
29 | FQDN = str(environ.get("FQDN", BIND_ADDRESS))
30 | URL = "http{}://{}{}/".format(
31 | "s" if HAS_SSL else "", FQDN, "" if NO_PORT else ":" + str(PORT)
32 | )
33 | KEEP_ALIVE = str(environ.get("KEEP_ALIVE", "0").lower()) in ("1", "true", "t", "yes", "y")
34 | DEBUG = str(environ.get("DEBUG", "0").lower()) in ("1", "true", "t", "yes", "y")
35 | USE_SESSION_FILE = str(environ.get("USE_SESSION_FILE", "0").lower()) in ("1", "true", "t", "yes", "y")
36 | ALLOWED_USERS = [x.strip("@ ") for x in str(environ.get("ALLOWED_USERS", "") or "").split(",") if x.strip("@ ")]
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .nox/
42 | .coverage
43 | .coverage.*
44 | .cache
45 | nosetests.xml
46 | coverage.xml
47 | *.cover
48 | .hypothesis/
49 | .pytest_cache/
50 |
51 | # Translations
52 | *.mo
53 | *.pot
54 |
55 | # Django stuff:
56 | *.log
57 | local_settings.py
58 | db.sqlite3
59 |
60 | # Flask stuff:
61 | instance/
62 | .webassets-cache
63 |
64 | # Scrapy stuff:
65 | .scrapy
66 |
67 | # Sphinx documentation
68 | docs/_build/
69 |
70 | # PyBuilder
71 | target/
72 |
73 | # Jupyter Notebook
74 | .ipynb_checkpoints
75 |
76 | # IPython
77 | profile_default/
78 | ipython_config.py
79 |
80 | # pyenv
81 | .python-version
82 |
83 | # celery beat schedule file
84 | celerybeat-schedule
85 |
86 | # SageMath parsed files
87 | *.sage.py
88 |
89 | # Environments
90 | .env
91 | .venv
92 | env/
93 | venv/
94 | ENV/
95 | env.bak/
96 | venv.bak/
97 |
98 | # Spyder project settings
99 | .spyderproject
100 | .spyproject
101 |
102 | # Rope project settings
103 | .ropeproject
104 |
105 | # mkdocs documentation
106 | /site
107 |
108 | # mypy
109 | .mypy_cache/
110 | .dmypy.json
111 | dmypy.json
112 |
113 | # Pyre type checker
114 | .pyre/
115 |
116 | #session files
117 | sessions/
118 | *.session
119 | *.session-journal
120 | .env
121 | test.py
122 |
--------------------------------------------------------------------------------
/WebStreamer/bot/plugins/stream.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | import logging
5 | from pyrogram import filters, errors
6 | from WebStreamer.vars import Var
7 | from urllib.parse import quote_plus
8 | from WebStreamer.bot import StreamBot, logger
9 | from WebStreamer.utils import get_hash, get_name
10 | from pyrogram.enums.parse_mode import ParseMode
11 | from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
12 |
13 |
14 | @StreamBot.on_message(
15 | filters.private
16 | & (
17 | filters.document
18 | | filters.video
19 | | filters.audio
20 | | filters.animation
21 | | filters.voice
22 | | filters.video_note
23 | | filters.photo
24 | | filters.sticker
25 | ),
26 | group=4,
27 | )
28 | async def media_receive_handler(_, m: Message):
29 | if Var.ALLOWED_USERS and not ((str(m.from_user.id) in Var.ALLOWED_USERS) or (m.from_user.username in Var.ALLOWED_USERS)):
30 | return await m.reply("你没有权限使用这个机器人。", quote=True)
31 | log_msg = await m.forward(chat_id=Var.BIN_CHANNEL)
32 | file_hash = get_hash(log_msg, Var.HASH_LENGTH)
33 | stream_link = f"{Var.URL}{log_msg.id}/{quote_plus(get_name(m))}?hash={file_hash}"
34 | short_link = f"{Var.URL}{file_hash}{log_msg.id}"
35 | logger.info(f"直链: {stream_link} for {m.from_user.first_name}")
36 | try:
37 | await m.reply_text(
38 | text="直链已准备好( ̄▽ ̄)/ 单击下面的链接可直接复制:\n{}\n(短链接)".format(
39 | stream_link, short_link
40 | ),
41 | quote=True,
42 | parse_mode=ParseMode.HTML,
43 | reply_markup=InlineKeyboardMarkup(
44 | [[InlineKeyboardButton("打开", url=stream_link)]]
45 | ),
46 | )
47 | except errors.ButtonUrlInvalid:
48 | await m.reply_text(
49 | text="{}\n\n短链: {})".format(
50 | stream_link, short_link
51 | ),
52 | quote=True,
53 | parse_mode=ParseMode.HTML,
54 | )
55 |
--------------------------------------------------------------------------------
/WebStreamer/bot/clients.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | import asyncio
5 | import logging
6 | from os import environ
7 | from ..vars import Var
8 | from pyrogram import Client
9 | from . import multi_clients, work_loads, sessions_dir, StreamBot
10 |
11 | logger = logging.getLogger("multi_client")
12 |
13 | async def initialize_clients():
14 | multi_clients[0] = StreamBot
15 | work_loads[0] = 0
16 | all_tokens = dict(
17 | (c + 1, t)
18 | for c, (_, t) in enumerate(
19 | filter(
20 | lambda n: n[0].startswith("MULTI_TOKEN"), sorted(environ.items())
21 | )
22 | )
23 | )
24 | if not all_tokens:
25 | logger.info("No additional clients found, using default client")
26 | return
27 |
28 | async def start_client(client_id, token):
29 | try:
30 | logger.info(f"Starting - Client {client_id}")
31 | if client_id == len(all_tokens):
32 | await asyncio.sleep(2)
33 | print("This will take some time, please wait...")
34 | client = await Client(
35 | name=str(client_id),
36 | api_id=Var.API_ID,
37 | api_hash=Var.API_HASH,
38 | bot_token=token,
39 | sleep_threshold=Var.SLEEP_THRESHOLD,
40 | workdir=sessions_dir if Var.USE_SESSION_FILE else Client.PARENT_DIR,
41 | no_updates=True,
42 | in_memory=not Var.USE_SESSION_FILE,
43 | ).start()
44 | work_loads[client_id] = 0
45 | return client_id, client
46 | except Exception:
47 | logger.error(f"Failed starting Client - {client_id} Error:", exc_info=True)
48 |
49 | clients = await asyncio.gather(*[start_client(i, token) for i, token in all_tokens.items()])
50 | multi_clients.update(dict(clients))
51 | if len(multi_clients) != 1:
52 | Var.MULTI_CLIENT = True
53 | logger.info("Multi-client mode enabled")
54 | else:
55 | logger.info("No additional clients were initialized, using default client")
--------------------------------------------------------------------------------
/WebStreamer/__main__.py:
--------------------------------------------------------------------------------
1 | # This file is a part of TG-FileStreamBot
2 | # Coding : Jyothis Jayanth [@EverythingSuckz]
3 |
4 | import sys
5 | import asyncio
6 | import logging
7 | from .vars import Var
8 | from aiohttp import web
9 | from pyrogram import idle
10 | from WebStreamer import utils
11 | from WebStreamer import StreamBot
12 | from WebStreamer.server import web_server
13 | from WebStreamer.bot.clients import initialize_clients
14 |
15 |
16 | logging.basicConfig(
17 | level=logging.DEBUG if Var.DEBUG else logging.INFO,
18 | datefmt="%d/%m/%Y %H:%M:%S",
19 | format="[%(asctime)s][%(name)s][%(levelname)s] ==> %(message)s",
20 | handlers=[logging.StreamHandler(stream=sys.stdout),
21 | logging.FileHandler("streambot.log", mode="a", encoding="utf-8")],)
22 |
23 | logging.getLogger("aiohttp").setLevel(logging.DEBUG if Var.DEBUG else logging.ERROR)
24 | logging.getLogger("pyrogram").setLevel(logging.INFO if Var.DEBUG else logging.ERROR)
25 | logging.getLogger("aiohttp.web").setLevel(logging.DEBUG if Var.DEBUG else logging.ERROR)
26 |
27 | server = web.AppRunner(web_server())
28 |
29 | loop = asyncio.get_event_loop()
30 |
31 |
32 |
33 | async def start_services():
34 | logging.info("Initializing Telegram Bot")
35 | await StreamBot.start()
36 | bot_info = await StreamBot.get_me()
37 | logging.debug(bot_info)
38 | StreamBot.username = bot_info.username
39 | logging.info("Initialized Telegram Bot")
40 | await initialize_clients()
41 | if Var.KEEP_ALIVE:
42 | asyncio.create_task(utils.ping_server())
43 | await server.setup()
44 | await web.TCPSite(server, Var.BIND_ADDRESS, Var.PORT).start()
45 | logging.info("Service Started")
46 | logging.info("bot =>> {}".format(bot_info.first_name))
47 | if bot_info.dc_id:
48 | logging.info("DC ID =>> {}".format(str(bot_info.dc_id)))
49 | logging.info("URL =>> {}".format(Var.URL))
50 | await idle()
51 |
52 | async def cleanup():
53 | await server.cleanup()
54 | await StreamBot.stop()
55 |
56 | if __name__ == "__main__":
57 | try:
58 | loop.run_until_complete(start_services())
59 | except KeyboardInterrupt:
60 | pass
61 | except Exception as err:
62 | logging.error(err.with_traceback(None))
63 | finally:
64 | loop.run_until_complete(cleanup())
65 | loop.stop()
66 | logging.info("Stopped Services")
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Telegram File Stream Bot
3 |
4 |
5 |
6 |
7 |
8 | 一个生成Telegram内文件直链的机器人。
9 |
10 |
11 |
12 |
13 |
14 | 此仓库源于[EverythingSuckz/TG-FileStreamBot](https://github.com/EverythingSuckz/TG-FileStreamBot)的[python](https://github.com/EverythingSuckz/TG-FileStreamBot/tree/python)分支,遵循[GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.zh-cn.html)。
15 |
16 | ## 这是啥
17 | 这是一个Telegram机器人,它将为您提供 Telegram 文件的流链接,无需等待下载完成。
18 | 目前原仓库使用Go重构的版本有问题,所以我单独把python分支拎出来并构建了Docker镜像。
19 |
20 | ## 部署
21 | 你可以查看原项目的[README](https://github.com/EverythingSuckz/TG-FileStreamBot/blob/python/README.md)以查看详细的部署教程。此处仅提供docker-compose的部署教程。
22 |
23 | ### docker-compose部署
24 | 拉取镜像:
25 | ```
26 | docker pull rong6233/tg-filestreambot:latest
27 | ```
28 | 编辑```docker-compose.yml```文件,参考配置位于仓库根目录下的```docker-compose.yml```内,环境变量具体的配置说明如下:
29 | #### 必选变量
30 | - `API_ID` :这是您 Telegram 帐户的 API ID,可从 my.telegram.org 获取。
31 |
32 | - `API_HASH` :这是您 Telegram 帐户的 API 哈希,也可以从 my.telegram.org 获取。
33 |
34 | - `BOT_TOKEN` :这是 Telegram Media Streamer Bot 的机器人令牌,可从 [@BotFather](https://telegram.dog/BotFather) 获取。
35 |
36 | - `BIN_CHANNEL` :这是日志频道的频道 ID,机器人将在该频道转发媒体消息并存储这些文件以使生成的直接链接正常工作。要获取频道 ID,请创建一个新的电报频道(公共或私人),在频道中发布一些内容,将消息转发给 [@missrose_bot](https://telegram.dog/MissRose_bot) 并使用 /id 命令 **回复转发的消息**。复制转发的频道 ID 并将其粘贴到此字段中。
37 |
38 | #### 可选变量
39 | - `HASH_LENGTH`:这是生成的 URL 的自定义哈希长度。哈希长度必须大于 5 且小于 64。
40 |
41 | - `SLEEP_THRESHOLD`:这设置了在机器人实例中全局发生的洪水等待异常的睡眠阈值。引发低于此阈值的洪水等待异常的请求将在睡眠所需的时间后自动再次调用。将引发需要更长等待时间的洪水等待异常。默认值为 60 秒。最好将此字段留空。
42 |
43 | - `WORKERS`:这设置了处理传入更新的最大并发工作者数量。默认值为 3。
44 |
45 | - `PORT`:这设置了您的 webapp 将监听的端口。默认值为 8080。
46 |
47 | - `WEB_SERVER_BIND_ADDRESS`:这设置了您的服务器绑定地址。默认值为 0.0.0.0。
48 |
49 | - `NO_PORT` :这可以是 True 或 False。如果设置为 True,则不会显示端口。
50 | > **注意**
51 | > 要使用此设置,您必须将 `PORT` 指向 HTTP 协议的 80 或 HTTPS 协议的 443,以使生成的链接正常工作。
52 |
53 | - `FQDN` :如果存在,则为完全限定域名。默认为 `WEB_SERVER_BIND_ADDRESS`
54 |
55 | - `HAS_SSL` :可以为 True 或 False。如果设置为 True,则生成的链接将采用 HTTPS 格式。
56 |
57 | - `KEEP_ALIVE` :是否要让服务器每 `PING_INTERVAL` 秒 ping 一次自身以避免休眠。在 PaaS 免费层中很有用。默认为 `False`
58 |
59 | - `PING_INTERVAL` :每次您希望服务器 ping 一次的时间(以毫秒为单位),以避免休眠(如果您使用某些 PaaS)。默认为 `1200` 或 20 分钟。
60 |
61 | - `USE_SESSION_FILE` : 使用客户端的会话文件,而不是将 sqlite 数据库存储在内存中。
62 |
63 | #### 多客户端支持
64 | `MULTI_TOKEN1`:在此添加您的第一个机器人令牌。
65 |
66 | `MULTI_TOKEN2`:在此添加您的第二个机器人令牌。
67 |
68 | 您还可以添加任意数量的机器人。(尚未测试最大限制)
69 | `MULTI_TOKEN3`、`MULTI_TOKEN4` 等。
70 |
71 | > **警告**
72 | > 不要忘记将所有这些机器人添加到 `BIN_CHANNEL` 以确保正常运行
73 |
74 |
75 | 启动:
76 | ```
77 | docker-compose up -d
78 | ```
79 |
80 | ## 使用
81 | 直接发送/转发文件,稍等片刻,机器人将会返回直链。
82 | 
--------------------------------------------------------------------------------
/WebStreamer/utils/file_properties.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | from pyrogram import Client
3 | from pyrogram.types import Message
4 | from pyrogram.file_id import FileId
5 | from typing import Any, Optional, Union
6 | from pyrogram.raw.types.messages import Messages
7 | from WebStreamer.server.exceptions import FIleNotFound
8 | from datetime import datetime
9 |
10 |
11 | async def parse_file_id(message: "Message") -> Optional[FileId]:
12 | media = get_media_from_message(message)
13 | if media:
14 | return FileId.decode(media.file_id)
15 |
16 | async def parse_file_unique_id(message: "Messages") -> Optional[str]:
17 | media = get_media_from_message(message)
18 | if media:
19 | return media.file_unique_id
20 |
21 | async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optional[FileId]:
22 | message = await client.get_messages(chat_id, message_id)
23 | if message.empty:
24 | raise FIleNotFound
25 | media = get_media_from_message(message)
26 | file_unique_id = await parse_file_unique_id(message)
27 | file_id = await parse_file_id(message)
28 | setattr(file_id, "file_size", getattr(media, "file_size", 0))
29 | setattr(file_id, "mime_type", getattr(media, "mime_type", ""))
30 | setattr(file_id, "file_name", getattr(media, "file_name", ""))
31 | setattr(file_id, "unique_id", file_unique_id)
32 | return file_id
33 |
34 | def get_media_from_message(message: "Message") -> Any:
35 | media_types = (
36 | "audio",
37 | "document",
38 | "photo",
39 | "sticker",
40 | "animation",
41 | "video",
42 | "voice",
43 | "video_note",
44 | )
45 | for attr in media_types:
46 | media = getattr(message, attr, None)
47 | if media:
48 | return media
49 |
50 |
51 | def get_hash(media_msg: Union[str, Message], length: int) -> str:
52 | if isinstance(media_msg, Message):
53 | media = get_media_from_message(media_msg)
54 | unique_id = getattr(media, "file_unique_id", "")
55 | else:
56 | unique_id = media_msg
57 | long_hash = hashlib.sha256(unique_id.encode("UTF-8")).hexdigest()
58 | return long_hash[:length]
59 |
60 |
61 | def get_name(media_msg: Union[Message, FileId]) -> str:
62 |
63 | if isinstance(media_msg, Message):
64 | media = get_media_from_message(media_msg)
65 | file_name = getattr(media, "file_name", "")
66 |
67 | elif isinstance(media_msg, FileId):
68 | file_name = getattr(media_msg, "file_name", "")
69 |
70 | if not file_name:
71 | if isinstance(media_msg, Message) and media_msg.media:
72 | media_type = media_msg.media.value
73 | elif media_msg.file_type:
74 | media_type = media_msg.file_type.name.lower()
75 | else:
76 | media_type = "file"
77 |
78 | formats = {
79 | "photo": "jpg", "audio": "mp3", "voice": "ogg",
80 | "video": "mp4", "animation": "mp4", "video_note": "mp4",
81 | "sticker": "webp"
82 | }
83 |
84 | ext = formats.get(media_type)
85 | ext = "." + ext if ext else ""
86 |
87 | date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
88 | file_name = f"{media_type}-{date}{ext}"
89 |
90 | return file_name
91 |
--------------------------------------------------------------------------------
/WebStreamer/server/stream_routes.py:
--------------------------------------------------------------------------------
1 | # Taken from megadlbot_oss
2 | # Thanks to Eyaadh
3 |
4 | import re
5 | import time
6 | import math
7 | import logging
8 | import secrets
9 | import mimetypes
10 | from aiohttp import web
11 | from aiohttp.http_exceptions import BadStatusLine
12 | from WebStreamer.bot import multi_clients, work_loads
13 | from WebStreamer.server.exceptions import FIleNotFound, InvalidHash
14 | from WebStreamer import Var, utils, StartTime, __version__, StreamBot
15 |
16 | logger = logging.getLogger("routes")
17 |
18 |
19 | routes = web.RouteTableDef()
20 |
21 | @routes.get("/", allow_head=True)
22 | async def root_route_handler(_):
23 | return web.json_response(
24 | {
25 | "server_status": "running",
26 | "uptime": utils.get_readable_time(time.time() - StartTime),
27 | "telegram_bot": "@" + StreamBot.username,
28 | "connected_bots": len(multi_clients),
29 | "loads": dict(
30 | ("bot" + str(c + 1), l)
31 | for c, (_, l) in enumerate(
32 | sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
33 | )
34 | ),
35 | "version": f"v{__version__}",
36 | }
37 | )
38 |
39 |
40 | @routes.get(r"/{path:\S+}", allow_head=True)
41 | async def stream_handler(request: web.Request):
42 | try:
43 | path = request.match_info["path"]
44 | match = re.search(r"^([0-9a-f]{%s})(\d+)$" % (Var.HASH_LENGTH), path)
45 | if match:
46 | secure_hash = match.group(1)
47 | message_id = int(match.group(2))
48 | else:
49 | message_id = int(re.search(r"(\d+)(?:\/\S+)?", path).group(1))
50 | secure_hash = request.rel_url.query.get("hash")
51 | return await media_streamer(request, message_id, secure_hash)
52 | except InvalidHash as e:
53 | raise web.HTTPForbidden(text=e.message)
54 | except FIleNotFound as e:
55 | raise web.HTTPNotFound(text=e.message)
56 | except (AttributeError, BadStatusLine, ConnectionResetError):
57 | pass
58 | except Exception as e:
59 | logger.critical(str(e), exc_info=True)
60 | raise web.HTTPInternalServerError(text=str(e))
61 |
62 | class_cache = {}
63 |
64 | async def media_streamer(request: web.Request, message_id: int, secure_hash: str):
65 | range_header = request.headers.get("Range", 0)
66 |
67 | index = min(work_loads, key=work_loads.get)
68 | faster_client = multi_clients[index]
69 |
70 | if Var.MULTI_CLIENT:
71 | logger.info(f"Client {index} is now serving {request.remote}")
72 |
73 | if faster_client in class_cache:
74 | tg_connect = class_cache[faster_client]
75 | logger.debug(f"Using cached ByteStreamer object for client {index}")
76 | else:
77 | logger.debug(f"Creating new ByteStreamer object for client {index}")
78 | tg_connect = utils.ByteStreamer(faster_client)
79 | class_cache[faster_client] = tg_connect
80 | logger.debug("before calling get_file_properties")
81 | file_id = await tg_connect.get_file_properties(message_id)
82 | logger.debug("after calling get_file_properties")
83 |
84 |
85 | if utils.get_hash(file_id.unique_id, Var.HASH_LENGTH) != secure_hash:
86 | logger.debug(f"Invalid hash for message with ID {message_id}")
87 | raise InvalidHash
88 |
89 | file_size = file_id.file_size
90 |
91 | if range_header:
92 | from_bytes, until_bytes = range_header.replace("bytes=", "").split("-")
93 | from_bytes = int(from_bytes)
94 | until_bytes = int(until_bytes) if until_bytes else file_size - 1
95 | else:
96 | from_bytes = request.http_range.start or 0
97 | until_bytes = (request.http_range.stop or file_size) - 1
98 |
99 | if (until_bytes > file_size) or (from_bytes < 0) or (until_bytes < from_bytes):
100 | return web.Response(
101 | status=416,
102 | body="416: Range not satisfiable",
103 | headers={"Content-Range": f"bytes */{file_size}"},
104 | )
105 |
106 | chunk_size = 1024 * 1024
107 | until_bytes = min(until_bytes, file_size - 1)
108 |
109 | offset = from_bytes - (from_bytes % chunk_size)
110 | first_part_cut = from_bytes - offset
111 | last_part_cut = until_bytes % chunk_size + 1
112 |
113 | req_length = until_bytes - from_bytes + 1
114 | part_count = math.ceil(until_bytes / chunk_size) - math.floor(offset / chunk_size)
115 | body = tg_connect.yield_file(
116 | file_id, index, offset, first_part_cut, last_part_cut, part_count, chunk_size
117 | )
118 | mime_type = file_id.mime_type
119 | file_name = utils.get_name(file_id)
120 | disposition = "attachment"
121 |
122 | if not mime_type:
123 | mime_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
124 |
125 | if "video/" in mime_type or "audio/" in mime_type or "/html" in mime_type:
126 | disposition = "inline"
127 |
128 | return web.Response(
129 | status=206 if range_header else 200,
130 | body=body,
131 | headers={
132 | "Content-Type": f"{mime_type}",
133 | "Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}",
134 | "Content-Length": str(req_length),
135 | "Content-Disposition": f'{disposition}; filename="{file_name}"',
136 | "Accept-Ranges": "bytes",
137 | },
138 | )
139 |
--------------------------------------------------------------------------------
/WebStreamer/utils/custom_dl.py:
--------------------------------------------------------------------------------
1 | import math
2 | import asyncio
3 | import logging
4 | from WebStreamer import Var
5 | from typing import Dict, Union
6 | from WebStreamer.bot import work_loads
7 | from pyrogram import Client, utils, raw
8 | from .file_properties import get_file_ids
9 | from pyrogram.session import Session, Auth
10 | from pyrogram.errors import AuthBytesInvalid
11 | from WebStreamer.server.exceptions import FIleNotFound
12 | from pyrogram.file_id import FileId, FileType, ThumbnailSource
13 |
14 | logger = logging.getLogger("streamer")
15 |
16 | class ByteStreamer:
17 | def __init__(self, client: Client):
18 | """A custom class that holds the cache of a specific client and class functions.
19 | attributes:
20 | client: the client that the cache is for.
21 | cached_file_ids: a dict of cached file IDs.
22 | cached_file_properties: a dict of cached file properties.
23 |
24 | functions:
25 | generate_file_properties: returns the properties for a media of a specific message contained in Tuple.
26 | generate_media_session: returns the media session for the DC that contains the media file.
27 | yield_file: yield a file from telegram servers for streaming.
28 |
29 | This is a modified version of the
30 | Thanks to Eyaadh
31 | """
32 | self.clean_timer = 30 * 60
33 | self.client: Client = client
34 | self.cached_file_ids: Dict[int, FileId] = {}
35 | asyncio.create_task(self.clean_cache())
36 |
37 | async def get_file_properties(self, message_id: int) -> FileId:
38 | """
39 | Returns the properties of a media of a specific message in a FIleId class.
40 | if the properties are cached, then it'll return the cached results.
41 | or it'll generate the properties from the Message ID and cache them.
42 | """
43 | if message_id not in self.cached_file_ids:
44 | await self.generate_file_properties(message_id)
45 | logger.debug(f"Cached file properties for message with ID {message_id}")
46 | return self.cached_file_ids[message_id]
47 |
48 | async def generate_file_properties(self, message_id: int) -> FileId:
49 | """
50 | Generates the properties of a media file on a specific message.
51 | returns ths properties in a FIleId class.
52 | """
53 | file_id = await get_file_ids(self.client, Var.BIN_CHANNEL, message_id)
54 | logger.debug(f"Generated file ID and Unique ID for message with ID {message_id}")
55 | if not file_id:
56 | logger.debug(f"Message with ID {message_id} not found")
57 | raise FIleNotFound
58 | self.cached_file_ids[message_id] = file_id
59 | logger.debug(f"Cached media message with ID {message_id}")
60 | return self.cached_file_ids[message_id]
61 |
62 | async def generate_media_session(self, client: Client, file_id: FileId) -> Session:
63 | """
64 | Generates the media session for the DC that contains the media file.
65 | This is required for getting the bytes from Telegram servers.
66 | """
67 |
68 | media_session = client.media_sessions.get(file_id.dc_id, None)
69 |
70 | if media_session is None:
71 | if file_id.dc_id != await client.storage.dc_id():
72 | media_session = Session(
73 | client,
74 | file_id.dc_id,
75 | await Auth(
76 | client, file_id.dc_id, await client.storage.test_mode()
77 | ).create(),
78 | await client.storage.test_mode(),
79 | is_media=True,
80 | )
81 | await media_session.start()
82 |
83 | for _ in range(6):
84 | exported_auth = await client.invoke(
85 | raw.functions.auth.ExportAuthorization(dc_id=file_id.dc_id)
86 | )
87 |
88 | try:
89 | await media_session.invoke(
90 | raw.functions.auth.ImportAuthorization(
91 | id=exported_auth.id, bytes=exported_auth.bytes
92 | )
93 | )
94 | break
95 | except AuthBytesInvalid:
96 | logger.debug(
97 | f"Invalid authorization bytes for DC {file_id.dc_id}"
98 | )
99 | continue
100 | else:
101 | await media_session.stop()
102 | raise AuthBytesInvalid
103 | else:
104 | media_session = Session(
105 | client,
106 | file_id.dc_id,
107 | await client.storage.auth_key(),
108 | await client.storage.test_mode(),
109 | is_media=True,
110 | )
111 | await media_session.start()
112 | logger.debug(f"Created media session for DC {file_id.dc_id}")
113 | client.media_sessions[file_id.dc_id] = media_session
114 | else:
115 | logger.debug(f"Using cached media session for DC {file_id.dc_id}")
116 | return media_session
117 |
118 |
119 | @staticmethod
120 | async def get_location(file_id: FileId) -> Union[raw.types.InputPhotoFileLocation,
121 | raw.types.InputDocumentFileLocation,
122 | raw.types.InputPeerPhotoFileLocation,]:
123 | """
124 | Returns the file location for the media file.
125 | """
126 | file_type = file_id.file_type
127 |
128 | if file_type == FileType.CHAT_PHOTO:
129 | if file_id.chat_id > 0:
130 | peer = raw.types.InputPeerUser(
131 | user_id=file_id.chat_id, access_hash=file_id.chat_access_hash
132 | )
133 | else:
134 | if file_id.chat_access_hash == 0:
135 | peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
136 | else:
137 | peer = raw.types.InputPeerChannel(
138 | channel_id=utils.get_channel_id(file_id.chat_id),
139 | access_hash=file_id.chat_access_hash,
140 | )
141 |
142 | location = raw.types.InputPeerPhotoFileLocation(
143 | peer=peer,
144 | volume_id=file_id.volume_id,
145 | local_id=file_id.local_id,
146 | big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG,
147 | )
148 | elif file_type == FileType.PHOTO:
149 | location = raw.types.InputPhotoFileLocation(
150 | id=file_id.media_id,
151 | access_hash=file_id.access_hash,
152 | file_reference=file_id.file_reference,
153 | thumb_size=file_id.thumbnail_size,
154 | )
155 | else:
156 | location = raw.types.InputDocumentFileLocation(
157 | id=file_id.media_id,
158 | access_hash=file_id.access_hash,
159 | file_reference=file_id.file_reference,
160 | thumb_size=file_id.thumbnail_size,
161 | )
162 | return location
163 |
164 | async def yield_file(
165 | self,
166 | file_id: FileId,
167 | index: int,
168 | offset: int,
169 | first_part_cut: int,
170 | last_part_cut: int,
171 | part_count: int,
172 | chunk_size: int,
173 | ) -> Union[str, None]:
174 | """
175 | Custom generator that yields the bytes of the media file.
176 | Modded from
177 | Thanks to Eyaadh
178 | """
179 | client = self.client
180 | work_loads[index] += 1
181 | logger.debug(f"Starting to yielding file with client {index}.")
182 | media_session = await self.generate_media_session(client, file_id)
183 |
184 | current_part = 1
185 | location = await self.get_location(file_id)
186 |
187 | try:
188 | r = await media_session.invoke(
189 | raw.functions.upload.GetFile(
190 | location=location, offset=offset, limit=chunk_size
191 | ),
192 | )
193 | if isinstance(r, raw.types.upload.File):
194 | while True:
195 | chunk = r.bytes
196 | if not chunk:
197 | break
198 | elif part_count == 1:
199 | yield chunk[first_part_cut:last_part_cut]
200 | elif current_part == 1:
201 | yield chunk[first_part_cut:]
202 | elif current_part == part_count:
203 | yield chunk[:last_part_cut]
204 | else:
205 | yield chunk
206 |
207 | current_part += 1
208 | offset += chunk_size
209 |
210 | if current_part > part_count:
211 | break
212 |
213 | r = await media_session.invoke(
214 | raw.functions.upload.GetFile(
215 | location=location, offset=offset, limit=chunk_size
216 | ),
217 | )
218 | except (TimeoutError, AttributeError):
219 | pass
220 | finally:
221 | logger.debug(f"Finished yielding file with {current_part} parts.")
222 | work_loads[index] -= 1
223 |
224 |
225 | async def clean_cache(self) -> None:
226 | """
227 | function to clean the cache to reduce memory usage
228 | """
229 | while True:
230 | await asyncio.sleep(self.clean_timer)
231 | self.cached_file_ids.clear()
232 | logger.debug("Cleaned the cache")
233 |
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [MAIN]
2 |
3 | # Analyse import fallback blocks. This can be used to support both Python 2 and
4 | # 3 compatible code, which means that the block might have code that exists
5 | # only in one or another interpreter, leading to false positives when analysed.
6 | analyse-fallback-blocks=no
7 | extension-pkg-whitelist=pydantic
8 | # Load and enable all available extensions. Use --list-extensions to see a list
9 | # all available extensions.
10 | #enable-all-extensions=
11 |
12 | # In error mode, messages with a category besides ERROR or FATAL are
13 | # suppressed, and no reports are done by default. Error mode is compatible with
14 | # disabling specific errors.
15 | #errors-only=
16 |
17 | # Always return a 0 (non-error) status code, even if lint errors are found.
18 | # This is primarily useful in continuous integration scripts.
19 | #exit-zero=
20 |
21 | # A comma-separated list of package or module names from where C extensions may
22 | # be loaded. Extensions are loading into the active Python interpreter and may
23 | # run arbitrary code.
24 | extension-pkg-allow-list=
25 |
26 | # A comma-separated list of package or module names from where C extensions may
27 | # be loaded. Extensions are loading into the active Python interpreter and may
28 | # run arbitrary code. (This is an alternative name to extension-pkg-allow-list
29 | # for backward compatibility.)
30 | extension-pkg-whitelist=
31 |
32 | # Return non-zero exit code if any of these messages/categories are detected,
33 | # even if score is above --fail-under value. Syntax same as enable. Messages
34 | # specified are enabled, while categories only check already-enabled messages.
35 | fail-on=
36 |
37 | # Specify a score threshold under which the program will exit with error.
38 | fail-under=10
39 |
40 | # Interpret the stdin as a python script, whose filename needs to be passed as
41 | # the module_or_package argument.
42 | #from-stdin=
43 |
44 | # Files or directories to be skipped. They should be base names, not paths.
45 | ignore=CVS
46 |
47 | # Add files or directories matching the regular expressions patterns to the
48 | # ignore-list. The regex matches against paths and can be in Posix or Windows
49 | # format. Because '\' represents the directory delimiter on Windows systems, it
50 | # can't be used as an escape character.
51 | ignore-paths=
52 |
53 | # Files or directories matching the regular expression patterns are skipped.
54 | # The regex matches against base names, not paths. The default value ignores
55 | # Emacs file locks
56 | ignore-patterns=^\.#
57 |
58 | # List of module names for which member attributes should not be checked
59 | # (useful for modules/projects where namespaces are manipulated during runtime
60 | # and thus existing member attributes cannot be deduced by static analysis). It
61 | # supports qualified module names, as well as Unix pattern matching.
62 | ignored-modules=
63 |
64 | # Python code to execute, usually for sys.path manipulation such as
65 | # pygtk.require().
66 | #init-hook=
67 |
68 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
69 | # number of processors available to use, and will cap the count on Windows to
70 | # avoid hangs.
71 | jobs=1
72 |
73 | # Control the amount of potential inferred values when inferring a single
74 | # object. This can help the performance when dealing with large functions or
75 | # complex, nested conditions.
76 | limit-inference-results=100
77 |
78 | # List of plugins (as comma separated values of python module names) to load,
79 | # usually to register additional checkers.
80 | load-plugins=
81 |
82 | # Pickle collected data for later comparisons.
83 | persistent=yes
84 |
85 | # Minimum Python version to use for version dependent checks. Will default to
86 | # the version used to run pylint.
87 | py-version=3.10
88 |
89 | # Discover python modules and packages in the file system subtree.
90 | recursive=no
91 |
92 | # When enabled, pylint would attempt to guess common misconfiguration and emit
93 | # user-friendly hints instead of false-positive error messages.
94 | suggestion-mode=yes
95 |
96 | # Allow loading of arbitrary C extensions. Extensions are imported into the
97 | # active Python interpreter and may run arbitrary code.
98 | unsafe-load-any-extension=no
99 |
100 | # In verbose mode, extra non-checker-related info will be displayed.
101 | #verbose=
102 |
103 |
104 | [REPORTS]
105 |
106 | # Python expression which should return a score less than or equal to 10. You
107 | # have access to the variables 'fatal', 'error', 'warning', 'refactor',
108 | # 'convention', and 'info' which contain the number of messages in each
109 | # category, as well as 'statement' which is the total number of statements
110 | # analyzed. This score is used by the global evaluation report (RP0004).
111 | evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
112 |
113 | # Template used to display messages. This is a python new-style format string
114 | # used to format the message information. See doc for all details.
115 | msg-template=
116 |
117 | # Set the output format. Available formats are text, parseable, colorized, json
118 | # and msvs (visual studio). You can also give a reporter class, e.g.
119 | # mypackage.mymodule.MyReporterClass.
120 | #output-format=
121 |
122 | # Tells whether to display a full report or only the messages.
123 | reports=no
124 |
125 | # Activate the evaluation score.
126 | score=yes
127 |
128 |
129 | [MESSAGES CONTROL]
130 |
131 | # Only show warnings with the listed confidence levels. Leave empty to show
132 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
133 | # UNDEFINED.
134 | confidence=HIGH,
135 | CONTROL_FLOW,
136 | INFERENCE,
137 | INFERENCE_FAILURE,
138 | UNDEFINED
139 |
140 | # Disable the message, report, category or checker with the given id(s). You
141 | # can either give multiple identifiers separated by comma (,) or put this
142 | # option multiple times (only on the command line, not in the configuration
143 | # file where it should appear only once). You can also use "--disable=all" to
144 | # disable everything first and then re-enable specific checks. For example, if
145 | # you want to run only the similarities checker, you can use "--disable=all
146 | # --enable=similarities". If you want to run only the classes checker, but have
147 | # no Warning level messages displayed, use "--disable=all --enable=classes
148 | # --disable=W".
149 | disable=raw-checker-failed,
150 | bad-inline-option,
151 | locally-disabled,
152 | file-ignored,
153 | suppressed-message,
154 | useless-suppression,
155 | deprecated-pragma,
156 | use-symbolic-message-instead,
157 | missing-module-docstring,
158 | missing-class-docstring,
159 | missing-function-docstring,
160 | logging-fstring-interpolation
161 |
162 | # Enable the message, report, category or checker with the given id(s). You can
163 | # either give multiple identifier separated by comma (,) or put this option
164 | # multiple time (only on the command line, not in the configuration file where
165 | # it should appear only once). See also the "--disable" option for examples.
166 | enable=c-extension-no-member
167 |
168 |
169 | [SIMILARITIES]
170 |
171 | # Comments are removed from the similarity computation
172 | ignore-comments=yes
173 |
174 | # Docstrings are removed from the similarity computation
175 | ignore-docstrings=yes
176 |
177 | # Imports are removed from the similarity computation
178 | ignore-imports=yes
179 |
180 | # Signatures are removed from the similarity computation
181 | ignore-signatures=yes
182 |
183 | # Minimum lines number of a similarity.
184 | min-similarity-lines=4
185 |
186 |
187 | [STRING]
188 |
189 | # This flag controls whether inconsistent-quotes generates a warning when the
190 | # character used as a quote delimiter is used inconsistently within a module.
191 | check-quote-consistency=no
192 |
193 | # This flag controls whether the implicit-str-concat should generate a warning
194 | # on implicit string concatenation in sequences defined over several lines.
195 | check-str-concat-over-line-jumps=no
196 |
197 |
198 | [IMPORTS]
199 |
200 | # List of modules that can be imported at any level, not just the top level
201 | # one.
202 | allow-any-import-level=
203 |
204 | # Allow wildcard imports from modules that define __all__.
205 | allow-wildcard-with-all=no
206 |
207 | # Deprecated modules which should not be used, separated by a comma.
208 | deprecated-modules=
209 |
210 | # Output a graph (.gv or any supported image format) of external dependencies
211 | # to the given file (report RP0402 must not be disabled).
212 | ext-import-graph=
213 |
214 | # Output a graph (.gv or any supported image format) of all (i.e. internal and
215 | # external) dependencies to the given file (report RP0402 must not be
216 | # disabled).
217 | import-graph=
218 |
219 | # Output a graph (.gv or any supported image format) of internal dependencies
220 | # to the given file (report RP0402 must not be disabled).
221 | int-import-graph=
222 |
223 | # Force import order to recognize a module as part of the standard
224 | # compatibility libraries.
225 | known-standard-library=
226 |
227 | # Force import order to recognize a module as part of a third party library.
228 | known-third-party=enchant
229 |
230 | # Couples of modules and preferred modules, separated by a comma.
231 | preferred-modules=
232 |
233 |
234 | [TYPECHECK]
235 |
236 | # List of decorators that produce context managers, such as
237 | # contextlib.contextmanager. Add to this list to register other decorators that
238 | # produce valid context managers.
239 | contextmanager-decorators=contextlib.contextmanager
240 |
241 | # List of members which are set dynamically and missed by pylint inference
242 | # system, and so shouldn't trigger E1101 when accessed. Python regular
243 | # expressions are accepted.
244 | generated-members=
245 |
246 | # Tells whether to warn about missing members when the owner of the attribute
247 | # is inferred to be None.
248 | ignore-none=yes
249 |
250 | # This flag controls whether pylint should warn about no-member and similar
251 | # checks whenever an opaque object is returned when inferring. The inference
252 | # can return multiple potential results while evaluating a Python object, but
253 | # some branches might not be evaluated, which results in partial inference. In
254 | # that case, it might be useful to still emit no-member and other checks for
255 | # the rest of the inferred objects.
256 | ignore-on-opaque-inference=yes
257 |
258 | # List of symbolic message names to ignore for Mixin members.
259 | ignored-checks-for-mixins=no-member,
260 | not-async-context-manager,
261 | not-context-manager,
262 | attribute-defined-outside-init
263 |
264 | # List of class names for which member attributes should not be checked (useful
265 | # for classes with dynamically set attributes). This supports the use of
266 | # qualified names.
267 | ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
268 |
269 | # Show a hint with possible names when a member name was not found. The aspect
270 | # of finding the hint is based on edit distance.
271 | missing-member-hint=yes
272 |
273 | # The minimum edit distance a name should have in order to be considered a
274 | # similar match for a missing member name.
275 | missing-member-hint-distance=1
276 |
277 | # The total number of similar names that should be taken in consideration when
278 | # showing a hint for a missing member.
279 | missing-member-max-choices=1
280 |
281 | # Regex pattern to define which classes are considered mixins.
282 | mixin-class-rgx=.*[Mm]ixin
283 |
284 | # List of decorators that change the signature of a decorated function.
285 | signature-mutators=
286 |
287 |
288 | [METHOD_ARGS]
289 |
290 | # List of qualified names (i.e., library.method) which require a timeout
291 | # parameter e.g. 'requests.api.get,requests.api.post'
292 | timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
293 |
294 |
295 | [SPELLING]
296 |
297 | # Limits count of emitted suggestions for spelling mistakes.
298 | max-spelling-suggestions=4
299 |
300 | # Spelling dictionary name. Available dictionaries: none. To make it work,
301 | # install the 'python-enchant' package.
302 | spelling-dict=
303 |
304 | # List of comma separated words that should be considered directives if they
305 | # appear at the beginning of a comment and should not be checked.
306 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
307 |
308 | # List of comma separated words that should not be checked.
309 | spelling-ignore-words=
310 |
311 | # A path to a file that contains the private dictionary; one word per line.
312 | spelling-private-dict-file=
313 |
314 | # Tells whether to store unknown words to the private dictionary (see the
315 | # --spelling-private-dict-file option) instead of raising a message.
316 | spelling-store-unknown-words=no
317 |
318 |
319 | [MISCELLANEOUS]
320 |
321 | # List of note tags to take in consideration, separated by a comma.
322 | notes=FIXME,
323 | XXX,
324 | TODO
325 |
326 | # Regular expression of note tags to take in consideration.
327 | notes-rgx=
328 |
329 |
330 | [BASIC]
331 |
332 | # Naming style matching correct argument names.
333 | argument-naming-style=snake_case
334 |
335 | # Regular expression matching correct argument names. Overrides argument-
336 | # naming-style. If left empty, argument names will be checked with the set
337 | # naming style.
338 | #argument-rgx=
339 |
340 | # Naming style matching correct attribute names.
341 | attr-naming-style=snake_case
342 |
343 | # Regular expression matching correct attribute names. Overrides attr-naming-
344 | # style. If left empty, attribute names will be checked with the set naming
345 | # style.
346 | #attr-rgx=
347 |
348 | # Bad variable names which should always be refused, separated by a comma.
349 | bad-names=foo,
350 | bar,
351 | baz,
352 | toto,
353 | tutu,
354 | tata
355 |
356 | # Bad variable names regexes, separated by a comma. If names match any regex,
357 | # they will always be refused
358 | bad-names-rgxs=
359 |
360 | # Naming style matching correct class attribute names.
361 | class-attribute-naming-style=any
362 |
363 | # Regular expression matching correct class attribute names. Overrides class-
364 | # attribute-naming-style. If left empty, class attribute names will be checked
365 | # with the set naming style.
366 | #class-attribute-rgx=
367 |
368 | # Naming style matching correct class constant names.
369 | class-const-naming-style=UPPER_CASE
370 |
371 | # Regular expression matching correct class constant names. Overrides class-
372 | # const-naming-style. If left empty, class constant names will be checked with
373 | # the set naming style.
374 | #class-const-rgx=
375 |
376 | # Naming style matching correct class names.
377 | class-naming-style=PascalCase
378 |
379 | # Regular expression matching correct class names. Overrides class-naming-
380 | # style. If left empty, class names will be checked with the set naming style.
381 | #class-rgx=
382 |
383 | # Naming style matching correct constant names.
384 | const-naming-style=UPPER_CASE
385 |
386 | # Regular expression matching correct constant names. Overrides const-naming-
387 | # style. If left empty, constant names will be checked with the set naming
388 | # style.
389 | #const-rgx=
390 |
391 | # Minimum line length for functions/classes that require docstrings, shorter
392 | # ones are exempt.
393 | docstring-min-length=-1
394 |
395 | # Naming style matching correct function names.
396 | function-naming-style=snake_case
397 |
398 | # Regular expression matching correct function names. Overrides function-
399 | # naming-style. If left empty, function names will be checked with the set
400 | # naming style.
401 | #function-rgx=
402 |
403 | # Good variable names which should always be accepted, separated by a comma.
404 | good-names=i,
405 | j,
406 | k,
407 | ex,
408 | Run,
409 | _
410 |
411 | # Good variable names regexes, separated by a comma. If names match any regex,
412 | # they will always be accepted
413 | good-names-rgxs=
414 |
415 | # Include a hint for the correct naming format with invalid-name.
416 | include-naming-hint=no
417 |
418 | # Naming style matching correct inline iteration names.
419 | inlinevar-naming-style=any
420 |
421 | # Regular expression matching correct inline iteration names. Overrides
422 | # inlinevar-naming-style. If left empty, inline iteration names will be checked
423 | # with the set naming style.
424 | #inlinevar-rgx=
425 |
426 | # Naming style matching correct method names.
427 | method-naming-style=snake_case
428 |
429 | # Regular expression matching correct method names. Overrides method-naming-
430 | # style. If left empty, method names will be checked with the set naming style.
431 | #method-rgx=
432 |
433 | # Naming style matching correct module names.
434 | module-naming-style=snake_case
435 |
436 | # Regular expression matching correct module names. Overrides module-naming-
437 | # style. If left empty, module names will be checked with the set naming style.
438 | #module-rgx=
439 |
440 | # Colon-delimited sets of names that determine each other's naming style when
441 | # the name regexes allow several styles.
442 | name-group=
443 |
444 | # Regular expression which should only match function or class names that do
445 | # not require a docstring.
446 | no-docstring-rgx=^_
447 |
448 | # List of decorators that produce properties, such as abc.abstractproperty. Add
449 | # to this list to register other decorators that produce valid properties.
450 | # These decorators are taken in consideration only for invalid-name.
451 | property-classes=abc.abstractproperty
452 |
453 | # Regular expression matching correct type variable names. If left empty, type
454 | # variable names will be checked with the set naming style.
455 | #typevar-rgx=
456 |
457 | # Naming style matching correct variable names.
458 | variable-naming-style=snake_case
459 |
460 | # Regular expression matching correct variable names. Overrides variable-
461 | # naming-style. If left empty, variable names will be checked with the set
462 | # naming style.
463 | #variable-rgx=
464 |
465 |
466 | [VARIABLES]
467 |
468 | # List of additional names supposed to be defined in builtins. Remember that
469 | # you should avoid defining new builtins when possible.
470 | additional-builtins=
471 |
472 | # Tells whether unused global variables should be treated as a violation.
473 | allow-global-unused-variables=yes
474 |
475 | # List of names allowed to shadow builtins
476 | allowed-redefined-builtins=
477 |
478 | # List of strings which can identify a callback function by name. A callback
479 | # name must start or end with one of those strings.
480 | callbacks=cb_,
481 | _cb
482 |
483 | # A regular expression matching the name of dummy variables (i.e. expected to
484 | # not be used).
485 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
486 |
487 | # Argument names that match this expression will be ignored.
488 | ignored-argument-names=_.*|^ignored_|^unused_
489 |
490 | # Tells whether we should check for unused import in __init__ files.
491 | init-import=no
492 |
493 | # List of qualified module names which can have objects that can redefine
494 | # builtins.
495 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
496 |
497 |
498 | [REFACTORING]
499 |
500 | # Maximum number of nested blocks for function / method body
501 | max-nested-blocks=5
502 |
503 | # Complete name of functions that never returns. When checking for
504 | # inconsistent-return-statements if a never returning function is called then
505 | # it will be considered as an explicit return statement and no message will be
506 | # printed.
507 | never-returning-functions=sys.exit,argparse.parse_error
508 |
509 |
510 | [DESIGN]
511 |
512 | # List of regular expressions of class ancestor names to ignore when counting
513 | # public methods (see R0903)
514 | exclude-too-few-public-methods=
515 |
516 | # List of qualified class names to ignore when counting class parents (see
517 | # R0901)
518 | ignored-parents=
519 |
520 | # Maximum number of arguments for function / method.
521 | max-args=5
522 |
523 | # Maximum number of attributes for a class (see R0902).
524 | max-attributes=7
525 |
526 | # Maximum number of boolean expressions in an if statement (see R0916).
527 | max-bool-expr=5
528 |
529 | # Maximum number of branch for function / method body.
530 | max-branches=12
531 |
532 | # Maximum number of locals for function / method body.
533 | max-locals=15
534 |
535 | # Maximum number of parents for a class (see R0901).
536 | max-parents=7
537 |
538 | # Maximum number of public methods for a class (see R0904).
539 | max-public-methods=20
540 |
541 | # Maximum number of return / yield for function / method body.
542 | max-returns=6
543 |
544 | # Maximum number of statements in function / method body.
545 | max-statements=50
546 |
547 | # Minimum number of public methods for a class (see R0903).
548 | min-public-methods=2
549 |
550 |
551 | [FORMAT]
552 |
553 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
554 | expected-line-ending-format=
555 |
556 | # Regexp for a line that is allowed to be longer than the limit.
557 | ignore-long-lines=^\s*(# )??$
558 |
559 | # Number of spaces of indent required inside a hanging or continued line.
560 | indent-after-paren=4
561 |
562 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
563 | # tab).
564 | indent-string=' '
565 |
566 | # Maximum number of characters on a single line.
567 | max-line-length=120
568 |
569 | # Maximum number of lines in a module.
570 | max-module-lines=1000
571 |
572 | # Allow the body of a class to be on the same line as the declaration if body
573 | # contains single statement.
574 | single-line-class-stmt=no
575 |
576 | # Allow the body of an if to be on the same line as the test if there is no
577 | # else.
578 | single-line-if-stmt=no
579 |
580 | [LOGGING]
581 |
582 | # The type of string formatting that logging methods do. `old` means using %
583 | # formatting, `new` is for `{}` formatting.
584 | logging-format-style=old
585 |
586 | # Logging modules to check that the string format arguments are in logging
587 | # function parameter format.
588 | logging-modules=logging
589 |
590 |
591 | [CLASSES]
592 |
593 | # Warn about protected attribute access inside special methods
594 | check-protected-access-in-special-methods=no
595 |
596 | # List of method names used to declare (i.e. assign) instance attributes.
597 | defining-attr-methods=__init__,
598 | __new__,
599 | setUp,
600 | __post_init__
601 |
602 | # List of member names, which should be excluded from the protected access
603 | # warning.
604 | exclude-protected=_asdict,
605 | _fields,
606 | _replace,
607 | _source,
608 | _make
609 |
610 | # List of valid names for the first argument in a class method.
611 | valid-classmethod-first-arg=cls
612 |
613 | # List of valid names for the first argument in a metaclass class method.
614 | valid-metaclass-classmethod-first-arg=cls
615 |
616 |
617 | [EXCEPTIONS]
618 |
619 | # Exceptions that will emit a warning when caught.
620 | overgeneral-exceptions=BaseException,
621 | Exception
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 | Telegram File Stream Bot - A simple webserver to stream telegram files over HTTP.
633 | Copyright (C) <2020>
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------