-
Notifications
You must be signed in to change notification settings - Fork 386
/
TGStreamer.py
253 lines (206 loc) · 8.57 KB
/
TGStreamer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# Author: MoeClub.org
# pip3 install pyrogram tgcrypto aiohttp
import os
import math
import asyncio
from aiohttp import web
from typing import Union
from pyrogram import Client, raw
from pyrogram.session import Session, Auth
from pyrogram import file_id
class TGSteamer:
# https://my.telegram.org/ # apiId, apiHash
# https://telegram.me/BotFather # botToken
cacheFileId = {}
lock = asyncio.Lock()
@classmethod
async def chunk_size(cls, length):
return 2 ** max(min(math.ceil(math.log2(length / 1024)), 10), 2) * 1024
@classmethod
async def offset_fix(cls, offset, chunkSize):
offset -= offset % chunkSize
return offset
@classmethod
async def get_client(cls, apiId, apiHash, botToken, appName=os.path.basename(os.path.abspath(__file__)).split(".")[0]):
_client = Client(
name=appName,
api_id=int(str(apiId).strip()),
api_hash=str(apiHash).strip(),
bot_token=str(botToken).strip(),
in_memory=True,
)
await _client.start()
assert _client.is_connected and _client.is_initialized
return _client
@classmethod
async def get_file_properties(cls, fileId):
async with cls.lock:
fileProperties = cls.cacheFileId.get(fileId, None)
if fileProperties is None:
fileProperties = file_id.FileId.decode(fileId)
setattr(fileProperties, "file_size", getattr(fileProperties, "file_size", 0))
setattr(fileProperties, "file_name", getattr(fileProperties, "file_name", ""))
cls.cacheFileId[fileId] = fileProperties
return fileProperties
@classmethod
async def get_session(cls, client: Client, data: file_id.FileId):
async with client.media_sessions_lock:
session = client.media_sessions.get(data.dc_id, None)
if session is None:
test_mode = await client.storage.test_mode()
dc_id = await client.storage.dc_id()
if data.dc_id != dc_id:
auth = await Auth(client, data.dc_id, test_mode).create()
else:
auth = await client.storage.auth_key()
session = Session(client, data.dc_id, auth, test_mode, is_media=True, is_cdn=False)
try:
await session.start()
if data.dc_id != dc_id:
exported = await client.invoke(raw.functions.auth.ExportAuthorization(dc_id=data.dc_id))
await session.invoke(raw.functions.auth.ImportAuthorization(id=exported.id, bytes=exported.bytes))
client.media_sessions[data.dc_id] = session
except Exception as e:
session = None
return session
@classmethod
async def get_location(cls, data: file_id.FileId):
file_type = data.file_type
if file_type == file_id.FileType.PHOTO:
location = raw.types.InputPhotoFileLocation(
id=data.media_id,
access_hash=data.access_hash,
file_reference=data.file_reference,
thumb_size=data.thumbnail_size
)
else:
location = raw.types.InputDocumentFileLocation(
id=data.media_id,
access_hash=data.access_hash,
file_reference=data.file_reference,
thumb_size=data.thumbnail_size
)
return location
@classmethod
async def yield_bytes(cls, client: Client, fileId: file_id.FileId, offset: int, chunkSize: int) -> Union[str, None]:
data = cls.get_file_properties(fileId) if isinstance(fileId, str) else fileId
location = await cls.get_location(data)
session = await cls.get_session(client, data)
if session is None:
raise Exception("InvalidSession")
r = await session.send(
raw.functions.upload.GetFile(
location=location,
offset=offset,
limit=chunkSize
),
)
if isinstance(r, raw.types.upload.File):
while True:
chunk = r.bytes
if not chunk:
break
offset += chunkSize
yield chunk
r = await session.send(
raw.functions.upload.GetFile(
location=location,
offset=offset,
limit=chunkSize
),
)
@classmethod
async def download_as_bytesio(cls, client, fileId, chunkSize=1024 * 1024):
data = cls.get_file_properties(fileId) if isinstance(fileId, str) else fileId
location = await cls.get_location(data)
session = await cls.get_session(client, data)
if session is None:
raise Exception("InvalidSession")
offset = 0
r = await session.send(
raw.functions.upload.GetFile(
location=location,
offset=offset,
limit=chunkSize
)
)
Bytes = []
if isinstance(r, raw.types.upload.File):
while True:
chunk = r.bytes
if not chunk:
break
Bytes += chunk
offset += chunkSize
r = await session.send(
raw.functions.upload.GetFile(
location=location,
offset=offset,
limit=chunkSize
)
)
return Bytes
class Web:
TelegramFile = TGSteamer()
TelegramFileClient = None
Index = "TelegramFile"
@classmethod
def Headers(cls, **kwargs):
headers = {
"Server": "TelegramFile"
}
for item in kwargs:
headers[item] = kwargs[item]
return headers
@classmethod
async def fileHandler(cls, request: web.Request):
try:
_fileId = str(request.match_info["fileId"]).strip("/")
assert len(_fileId) > 0
try:
fileId = await cls.TelegramFile.get_file_properties(_fileId)
except Exception as e:
raise Exception("Invalid FileId")
return await cls.streamer(request=request, fileId=fileId)
except Exception as e:
return web.Response(text=str(e).strip(), status=404, headers={"Server": cls.Index}, content_type="text/plain")
@classmethod
async def streamer(cls, request: web.Request, fileId: file_id.FileId):
range_header = request.headers.get("Range", 0)
file_size = fileId.file_size
rangeSupport = True if file_size > 0 else False
file_name = str(fileId.media_id).strip() if fileId.file_name == "" else str(fileId.file_name).strip()
headers = {
"Content-Type": "application/octet-stream",
"Content-Disposition": f'attachment; filename="{file_name}"',
"Server": cls.Index,
}
try:
assert range_header and rangeSupport
from_bytes, until_bytes = range_header.replace("bytes=", "").split("-")
from_bytes = int(from_bytes) if int(from_bytes) >= 0 else 0
until_bytes = int(until_bytes) if until_bytes and int(until_bytes) > from_bytes else file_size - 1
req_length = until_bytes - from_bytes + 1
headers["Accept-Ranges"] = "bytes"
headers["Content-Length"] = str(req_length),
headers["Content-Range"] = f"bytes {from_bytes}-{until_bytes}/{file_size}"
except:
from_bytes = 0
chunk_size = 1024 * 1024 if file_size <= 0 else cls.TelegramFile.chunk_size(file_size)
offset = from_bytes - (from_bytes % chunk_size)
body = cls.TelegramFile.yield_bytes(cls.TelegramFileClient, fileId, offset, chunk_size)
code = 206 if rangeSupport else 200
return web.Response(status=code, body=body, headers=headers)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
Web.TelegramFileClient = loop.run_until_complete(Web.TelegramFile.get_client(
int("appId"),
str("appHash"),
str("botToken")
))
app = web.Application()
app.add_routes([web.get(path=str("/{}").format(str(Web.Index).strip("/")) + '{fileId:/[-_\w]+}', handler=Web.fileHandler, allow_head=False)])
logging_format = '%t %a %s %r [%Tfs]'
web.run_app(app=app, host="0.0.0.0", port=63838, access_log_format=logging_format, loop=loop)