So bro, this my code.
from aiohttp import web
from pyrogram import Client, filters
Create an instance of the Pyrogram client
client = None
async def stream_video(request):
global client
try:
client = await Client("my_account").start()
except Exception:
pass
# Extract the Range header, if exists
range_header = request.headers.get('Range', None)
# Default values if Range is not provided
start = 0
end = None
cid = int(request.match_info['cid'])
mid = int(request.match_info['mid'])
message = await client.get_messages(cid, mid)
video_size = message.video.file_size
# Default values if Range is not provided
start = 0
end = video_size - 1
if range_header:
# Parse the range headers
start, end = range_header.replace('bytes=', '').split('-')
start = int(start)
# Convert to int, if end is not empty
end = int(end) if end else video_size - 1
# Now that you have start and end, calculate offset and limit
chunk_size = 1024 * 1024
offset = start // chunk_size
# Calculate the number of chunk_sizes to limit the stream
limit = ((end - start) // chunk_size) + 1
response = web.StreamResponse()
response.headers['Content-Type'] = 'video/mp4'
response.headers['Accept-Ranges'] = 'bytes'
response_content_length = end - start + 1
response.headers['Content-Length'] = str(response_content_length)
response.headers['Content-Range'] = f'bytes {start}-{end}/{video_size}'
if range_header:
response.set_status(206, reason='Partial Content')
else:
response.set_status(200, reason='OK')
await response.prepare(request)
# Stream the media from pyrogram
async for chunk in client.stream_media(message, limit=limit, offset=offset):
# Check if chunk needs to be trimmed
chunk_start = offset * chunk_size
chunk_end = chunk_start + len(chunk) - 1
# Trim front
if chunk_start < start:
chunk = chunk[start - chunk_start:]
# Trim end
if end and chunk_end > end:
chunk = chunk[:end - chunk_start + 1]
# Write chunk to response
await response.write(chunk)
offset += 1 # Move to the next chunk
if chunk_end >= end:
break
await response.write_eof()
return response
async def serve_player(request):
# Serve the player.html file
with open('player.html', 'rb') as f:
content = f.read()
return web.Response(body=content, content_type='text/html')
app = web.Application()
Set up the web server routes
app.router.add_get('/video/{cid}/{mid}', stream_video)
app.router.add_route('GET', '/player', serve_player)
Run the web application
web.run_app(app, port=8080)
=======
My question is that, Let's say if user stopped playing video and closed the video player or browser. Then will this stop my pyrogram fetching chunks via stream_media too?
I want it to stop unnesscary fetching. If user has broken the connection, then stop fetching it....
If it's already like that, then I guess no need for any code changes...