telegram: Refactor download media code.
patch 8167f7dfd2712a9a103504fe7763e2a497adf723
Author: E. Bosch <presidev@AT@gmail.com>
Date: Sun Nov 19 00:43:04 CET 2023
* telegram: Refactor download media code.
If named media files already downloaded, don't try to download again
hunk ./telegram.py 691
+ filename = None
+
+ def scan_doc_attributes(document):
+ attrib_file = attrib_video = filename = None
+ size = document.size
+ h_size = get_human_size(size)
+ for x in document.attributes:
+ if isinstance(x, tgty.DocumentAttributeVideo):
+ attrib_video = x
+ if isinstance(x, tgty.DocumentAttributeFilename):
+ attrib_file = x
+ filename = attrib_file.file_name if attrib_file else None
+
+ return size, h_size, attrib_video, filename
hunk ./telegram.py 733
- size = message.media.document.size
- h_size = get_human_size(size)
- attrib = next(x for x in message.media.document.attributes if isinstance(x, tgty.DocumentAttributeVideo))
- dur = get_human_duration(attrib.duration)
+ size, h_size, attrib_video, filename = scan_doc_attributes(message.media.document)
+ dur = get_human_duration(attrib_video.duration) if attrib_video else ''
hunk ./telegram.py 740
- size = message.media.document.size
- h_size = get_human_size(size)
+ size, h_size, _, filename = scan_doc_attributes(message.media.document)
hunk ./telegram.py 795
- if self.download and size > self.notice_size:
- await self.relay_telegram_message(message, user, '[{}] [{}] [Downloading]'.format(mid, media_type))
-
- media_url_or_data = await self.download_telegram_media(message)
+ relay_attr = (message, user, mid, media_type)
+ media_url_or_data = await self.download_telegram_media(message, filename, size, relay_attr)
hunk ./telegram.py 847
- async def download_telegram_media(self, message):
- local_path = None
- if self.download:
+ async def download_telegram_media(self, message, filename=None, size=0, relay_attr=None):
+ if not self.download:
+ return ''
+ if filename:
+ new_file = sanitize_filename(filename)
+ new_path = os.path.join(self.telegram_media_dir, new_file)
+ if os.path.exists(new_path):
+ local_path = new_path
+ else:
+ await self.notice_downloading(size, relay_attr)
+ local_path = await message.download_media(new_path)
+ if not local_path: return ''
+ else:
+ await self.notice_downloading(size, relay_attr)
hunk ./telegram.py 862
- if not local_path: return ''
-
- if message.document:
- new_file = sanitize_filename(os.path.basename(local_path))
- else:
+ if not local_path: return ''
hunk ./telegram.py 866
-
- new_path = os.path.join(self.telegram_media_dir, new_file)
+ new_path = os.path.join(self.telegram_media_dir, new_file)
+
hunk ./telegram.py 874
+ async def notice_downloading(self, size, relay_attr):
+ if relay_attr and size > self.notice_size:
+ message, user, mid, media_type = relay_attr
+ await self.relay_telegram_message(message, user, '[{}] [{}] [Downloading]'.format(mid, media_type))
+