split thumbnail from fileserve handler

This commit is contained in:
odysseusmax 2020-09-01 12:59:32 +05:30
parent fc7146cc30
commit f0e474a877
4 changed files with 75 additions and 41 deletions

View File

@ -65,7 +65,6 @@ async def setup_routes(app, handler):
web.get(p + r"/{id:\d+}/download", h.download_get), web.get(p + r"/{id:\d+}/download", h.download_get),
web.head(p + r"/{id:\d+}/download", h.download_head), web.head(p + r"/{id:\d+}/download", h.download_head),
web.get(p + r"/{id:\d+}/thumbnail", h.thumbnail_get), web.get(p + r"/{id:\d+}/thumbnail", h.thumbnail_get),
web.head(p + r"/{id:\d+}/thumbnail", h.thumbnail_head),
] ]
routes += r routes += r
log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}") log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}")
@ -81,7 +80,6 @@ async def setup_routes(app, handler):
web.get(p + r"/{id:\d+}/download", h.download_get), web.get(p + r"/{id:\d+}/download", h.download_get),
web.head(p + r"/{id:\d+}/download", h.download_head), web.head(p + r"/{id:\d+}/download", h.download_head),
web.get(p + r"/{id:\d+}/thumbnail", h.thumbnail_get), web.get(p + r"/{id:\d+}/thumbnail", h.thumbnail_get),
web.head(p + r"/{id:\d+}/thumbnail", h.thumbnail_head),
] ]
routes += r routes += r
log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}") log.debug(f"Index added for {chat.id} :: {chat.title} at /{alias_id}")

View File

@ -2,7 +2,7 @@ import math
import logging import logging
import asyncio import asyncio
from telethon import TelegramClient from telethon import TelegramClient, utils
from telethon.sessions import StringSession from telethon.sessions import StringSession
class Client(TelegramClient): class Client(TelegramClient):
@ -13,7 +13,8 @@ class Client(TelegramClient):
async def download(self, file, file_size, offset, limit): async def download(self, file, file_size, offset, limit):
part_size = 1024 * 1024 part_size_kb = utils.get_appropriated_part_size(file_size)
part_size = int(part_size_kb * 1024)
first_part_cut = offset % part_size first_part_cut = offset % part_size
first_part = math.floor(offset / part_size) first_part = math.floor(offset / part_size)
last_part_cut = part_size - (limit % part_size) last_part_cut = part_size - (limit % part_size)
@ -21,7 +22,7 @@ class Client(TelegramClient):
part_count = math.ceil(file_size / part_size) part_count = math.ceil(file_size / part_size)
part = first_part part = first_part
try: try:
async for chunk in self.iter_download(file, offset=first_part * part_size, file_size=file_size, request_size=part_size): async for chunk in self.iter_download(file, offset=first_part * part_size, request_size=part_size):
if part == first_part: if part == first_part:
yield chunk[first_part_cut:] yield chunk[first_part_cut:]
elif part == last_part: elif part == last_part:

View File

@ -3,7 +3,7 @@
<div class="p-4 space-y-8"> <div class="p-4 space-y-8">
{% if found %} {% if found %}
{% if media %} {% if media %}
<h1 class="text-blue-500 text-center text-lg md:text-xl lg:text-2xl xl:text-3xl w-full break-all"> <h1 class="text-blue-500 text-center text-lg lg:text-xl xl:text-3xl w-full break-all">
Download {{name}} Download {{name}}
</h1> </h1>
@ -15,9 +15,11 @@
<p> Video {{name}} could not be played!</p> <p> Video {{name}} could not be played!</p>
</div> </div>
<div id="my-video-wrapper">
<video id="my-video-player" class="mx-auto rounded" controls poster="../{{id}}/thumbnail"> <video id="my-video-player" class="mx-auto rounded" controls poster="../{{id}}/thumbnail">
<source src="../{{id}}/download" type="video/mp4" /> <source src="../{{id}}/download" type="video/mp4" />
</video> </video>
</div>
<script> <script>
var video = document.querySelector("video"); var video = document.querySelector("video");
@ -25,7 +27,7 @@
src.addEventListener('error', function(evt) { src.addEventListener('error', function(evt) {
console.log(evt); console.log(evt);
document.getElementById('my-video-player').style.display = 'none'; document.getElementById('my-video-wrapper').style.display = 'none';
document.getElementById('video-warning').style.display = 'block'; document.getElementById('video-warning').style.display = 'block';
}); });
var myFP = fluidPlayer( var myFP = fluidPlayer(
@ -49,16 +51,18 @@
<p> Audio {{name}} could not be played!</p> <p> Audio {{name}} could not be played!</p>
</div> </div>
<audio id="my-audio" class="mx-auto" controls muted> <div id="my-audio-wrapper">
<audio class="mx-auto" controls muted>
<source src="../{{id}}/download" type="audio/mpeg" /> <source src="../{{id}}/download" type="audio/mpeg" />
</audio> </audio>
</div>
<script> <script>
var audio = document.querySelector("audio"); var audio = document.querySelector("audio");
var src = audio.firstElementChild var src = audio.firstElementChild
src.addEventListener('error', function(evt) { src.addEventListener('error', function(evt) {
console.log(evt); console.log(evt);
document.getElementById('my-audio').style.display = 'none'; document.getElementById('my-audio-wrapper').style.display = 'none';
document.getElementById('audio-warning').style.display = 'block'; document.getElementById('audio-warning').style.display = 'block';
}); });
</script> </script>
@ -87,7 +91,7 @@
</div> </div>
<div class="text-center text-white text-sm md:text-base xl:text-2xl"> <div class="text-center text-white text-sm xl:text-2xl">
<a class="rounded p-3 bg-indigo-500 hover:bg-indigo-700 shadow-lg" href="../{{id}}/download">Download Now! ({{ size }})</a> <a class="rounded p-3 bg-indigo-500 hover:bg-indigo-700 shadow-lg" href="../{{id}}/download">Download Now! ({{ size }})</a>

View File

@ -232,14 +232,6 @@ class Views:
async def thumbnail_get(self, req): async def thumbnail_get(self, req):
return await self.handle_request(req, thumb=True)
async def thumbnail_head(self, req):
return await self.handle_request(req, head=True, thumb=True)
async def handle_request(self, req, head=False, thumb=False):
file_id = int(req.match_info["id"]) file_id = int(req.match_info["id"])
alias_id = req.rel_url.path.split('/')[1] alias_id = req.rel_url.path.split('/')[1]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0] chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
@ -249,26 +241,65 @@ class Views:
except: except:
log.debug(f"Error in getting message {file_id} in {chat_id}", exc_info=True) log.debug(f"Error in getting message {file_id} in {chat_id}", exc_info=True)
message = None message = None
if not message or not message.file: if not message or not message.file:
log.debug(f"no result for {file_id} in {chat_id}") log.debug(f"no result for {file_id} in {chat_id}")
return web.Response(status=410, text="410: Gone. Access to the target resource is no longer available!") return web.Response(status=410, text="410: Gone. Access to the target resource is no longer available!")
if thumb and message.document: if message.document:
thumbnail = message.document.thumbs media = message.document
if not thumbnail: thumbnails = media.thumbs
location = types.InputDocumentFileLocation
else:
media = message.photo
thumbnails = media.sizes
location = types.InputPhotoFileLocation
if not thumbnails:
log.debug(f"no thumbnail for {file_id} in {chat_id}") log.debug(f"no thumbnail for {file_id} in {chat_id}")
return web.Response(status=404, text="404: Not Found") return web.Response(status=404, text="404: Not Found")
thumbnail = thumbnail[-1]
mime_type = 'image/jpeg' thumb_pos = int(max(0, len(thumbnails)/2))
size = thumbnail.size if hasattr(thumbnail, 'size') else len(thumbnail.bytes) thumbnail = self.client._get_thumb(thumbnails, thumb_pos)
file_name = f"{file_id}_thumbnail.jpg" if not thumbnail or isinstance(thumbnail, types.PhotoSizeEmpty):
media = types.InputDocumentFileLocation( return web.Response(status=410, text="410: Gone. Access to the target resource is no longer available!")
id=message.document.id,
access_hash=message.document.access_hash, if isinstance(thumbnail, (types.PhotoCachedSize, types.PhotoStrippedSize)):
file_reference=message.document.file_reference, body = self.client._download_cached_photo_size(thumbnail, bytes)
else:
actual_file = location(
id=media.id,
access_hash=media.access_hash,
file_reference=media.file_reference,
thumb_size=thumbnail.type thumb_size=thumbnail.type
) )
else:
body = self.client.iter_download(actual_file)
r = web.Response(
status=200,
body=body,
)
r.enable_chunked_encoding()
return r
async def handle_request(self, req, head=False):
file_id = int(req.match_info["id"])
alias_id = req.rel_url.path.split('/')[1]
chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
chat_id = chat['chat_id']
try:
message = await self.client.get_messages(entity=chat_id, ids=file_id)
except:
log.debug(f"Error in getting message {file_id} in {chat_id}", exc_info=True)
message = None
if not message or not message.file:
log.debug(f"no result for {file_id} in {chat_id}")
return web.Response(status=410, text="410: Gone. Access to the target resource is no longer available!")
media = message.media media = message.media
size = message.file.size size = message.file.size
file_name = get_file_name(message) file_name = get_file_name(message)