增加新设置:压缩过大图片

This commit is contained in:
2022-09-02 05:11:29 +00:00
parent ab54a5f5ae
commit 474a2bf22c
4 changed files with 99 additions and 21 deletions

View File

@@ -47,10 +47,11 @@ class RSSConfig:
self.send_origin_file_name = False self.send_origin_file_name = False
self.send_ugoira_with_origin_pix_fmt = False self.send_ugoira_with_origin_pix_fmt = False
self.send_ugoira_method = SendUgoiraMethod(0) self.send_ugoira_method = SendUgoiraMethod(0)
self.compress_big_image = True
self.update(d) self.update(d)
def toJson(self): def toJson(self):
return dumps({'disable_web_page_preview': self.disable_web_page_preview, 'show_RSS_title': self.show_RSS_title, 'show_Content_title': self.show_Content_title, 'show_content': self.show_content, 'send_media': self.send_media, 'display_entry_link': self.display_entry_link, 'send_img_as_file': self.send_img_as_file, 'send_ugoira_with_origin_pix_fmt': self.send_ugoira_with_origin_pix_fmt, 'send_ugoira_method': self.send_ugoira_method.value}, ensure_ascii=False) return dumps({'disable_web_page_preview': self.disable_web_page_preview, 'show_RSS_title': self.show_RSS_title, 'show_Content_title': self.show_Content_title, 'show_content': self.show_content, 'send_media': self.send_media, 'display_entry_link': self.display_entry_link, 'send_img_as_file': self.send_img_as_file, 'send_ugoira_with_origin_pix_fmt': self.send_ugoira_with_origin_pix_fmt, 'send_ugoira_method': self.send_ugoira_method.value, "compress_big_image": self.compress_big_image}, ensure_ascii=False)
def update(self, d: dict): def update(self, d: dict):
if d is not None: if d is not None:

View File

@@ -78,6 +78,7 @@ def getMediaInfo(m: dict, config: RSSConfig = RSSConfig()) -> str:
if have_rssbotlib: if have_rssbotlib:
s += f"\n发送原始像素格式的Pixiv动图:{config.send_ugoira_with_origin_pix_fmt}" s += f"\n发送原始像素格式的Pixiv动图:{config.send_ugoira_with_origin_pix_fmt}"
s += f'\n发送Pixiv动图为{config.send_ugoira_method}' s += f'\n发送Pixiv动图为{config.send_ugoira_method}'
s += f"\n发送时压缩过大图片:{config.compress_big_image}"
s += f"\nRSS全局设置:" s += f"\nRSS全局设置:"
s += f"\n发送时使用原文件名:{config.send_origin_file_name}" s += f"\n发送时使用原文件名:{config.send_origin_file_name}"
return s return s
@@ -102,6 +103,7 @@ class InlineKeyBoardCallBack(Enum):
SendOriginFileName = 14 SendOriginFileName = 14
SendUgoiraWithOriginPixFmt = 15 SendUgoiraWithOriginPixFmt = 15
SendUgoiraMethod = 16 SendUgoiraMethod = 16
CompressBigImage = 17
def getInlineKeyBoardWhenRSS(hashd: str, m: dict, isOwn: bool) -> dict: def getInlineKeyBoardWhenRSS(hashd: str, m: dict, isOwn: bool) -> dict:
@@ -173,6 +175,8 @@ def getInlineKeyBoardWhenRSS2(hashd: str, config: RSSConfig) -> str:
temp2 = SendUgoiraMethod((config.send_ugoira_method.value + 1) % 4) temp2 = SendUgoiraMethod((config.send_ugoira_method.value + 1) % 4)
temp = f'发送Pixiv动图为{temp2}' temp = f'发送Pixiv动图为{temp2}'
d[i].append({'text': temp, 'callback_data': f'0,{hashd},{InlineKeyBoardCallBack.SendUgoiraMethod.value},{temp2.value}'}) d[i].append({'text': temp, 'callback_data': f'0,{hashd},{InlineKeyBoardCallBack.SendUgoiraMethod.value},{temp2.value}'})
temp = f"{'禁用' if config.compress_big_image else '启用'}压缩过大图片"
d[i].append({'text': temp, 'callback_data': f'0,{hashd},{InlineKeyBoardCallBack.CompressBigImage.value}'})
d.append([]) d.append([])
i += 1 i += 1
d[i].append( d[i].append(
@@ -282,15 +286,31 @@ class main:
content['imgList'][0], config) content['imgList'][0], config)
if not fileEntry.ok: if not fileEntry.ok:
continue continue
should_use_file = False if fileEntry._fileSize < MAX_PHOTO_SIZE and not config.send_img_as_file else True should_use_file = False if not config.send_img_as_file else True
is_supported_photo = None is_supported_photo = None
is_too_big = None
compressed_file = None
if self._rssbotLib is not None: if self._rssbotLib is not None:
is_supported_photo = self._rssbotLib.is_supported_photo(fileEntry._abspath) ttmp = self._rssbotLib.is_supported_photo(fileEntry)
if ttmp is not None:
is_supported_photo = ttmp[0]
is_too_big = ttmp[1]
if not should_use_file and is_supported_photo is not None: if not should_use_file and is_supported_photo is not None:
should_use_file = not is_supported_photo should_use_file = not is_supported_photo
if is_too_big is True and config.compress_big_image:
compressed_file = self._rssbotLib.compress_image(fileEntry)
if compressed_file is not None:
should_use_file = False
elif fileEntry._fileSize >= MAX_PHOTO_SIZE:
should_use_file = True
elif fileEntry._fileSize >= MAX_PHOTO_SIZE:
should_use_file = True
if self._setting.sendFileURLScheme: if self._setting.sendFileURLScheme:
if not should_use_file: if not should_use_file:
di['photo'] = fileEntry._localURI if compressed_file is None:
di['photo'] = fileEntry._localURI
else:
di['photo'] = compressed_file._localURI
re = self._request('sendPhoto', 'post', json=di) re = self._request('sendPhoto', 'post', json=di)
else: else:
di['document'] = fileEntry._localURI di['document'] = fileEntry._localURI
@@ -300,10 +320,11 @@ class main:
di['thumb'] = thumb_file._localURI di['thumb'] = thumb_file._localURI
re = self._request('sendDocument', 'post', json=di) re = self._request('sendDocument', 'post', json=di)
else: else:
fileEntry.open() ttmp = fileEntry if compressed_file is None else compressed_file
ttmp.open()
if not should_use_file: if not should_use_file:
re = self._request('sendPhoto', 'post', json=di, files={ re = self._request('sendPhoto', 'post', json=di, files={
'photo': (fileEntry._fullfn, fileEntry._f)}) 'photo': (ttmp._fullfn, ttmp._f)})
else: else:
send_files = {'document': (fileEntry._fullfn, fileEntry._f)} send_files = {'document': (fileEntry._fullfn, fileEntry._f)}
if is_supported_photo is False or (self._rssbotLib is not None and fileEntry._fileSize >= MAX_PHOTO_SIZE): if is_supported_photo is False or (self._rssbotLib is not None and fileEntry._fileSize >= MAX_PHOTO_SIZE):
@@ -697,12 +718,25 @@ class main:
fileEntry = self._tempFileEntries.add(i, config) fileEntry = self._tempFileEntries.add(i, config)
if not fileEntry.ok: if not fileEntry.ok:
return None return None
should_use_file = False if fileEntry._fileSize < MAX_PHOTO_SIZE and not config.send_img_as_file else True should_use_file = False if not config.send_img_as_file else True
is_supported_photo = None is_supported_photo = None
is_too_big = None
compressed_file = None
if self._rssbotLib is not None: if self._rssbotLib is not None:
is_supported_photo = self._rssbotLib.is_supported_photo(fileEntry._abspath) ttmp = self._rssbotLib.is_supported_photo(fileEntry)
if ttmp is not None:
is_supported_photo = ttmp[0]
is_too_big = ttmp[1]
if not should_use_file and is_supported_photo is not None: if not should_use_file and is_supported_photo is not None:
should_use_file = not is_supported_photo should_use_file = not is_supported_photo
if is_too_big is True and config.compress_big_image:
compressed_file = self._rssbotLib.compress_image(fileEntry)
if compressed_file is not None:
should_use_file = False
elif fileEntry._fileSize >= MAX_PHOTO_SIZE:
should_use_file = True
elif fileEntry._fileSize >= MAX_PHOTO_SIZE:
should_use_file = True
if should_use_file: if should_use_file:
if contain_nonfiles: if contain_nonfiles:
send_file_in_list() send_file_in_list()
@@ -723,11 +757,15 @@ class main:
send_file_in_list() send_file_in_list()
contain_nonfiles = True contain_nonfiles = True
if self._setting.sendFileURLScheme: if self._setting.sendFileURLScheme:
di2['media'] = fileEntry._localURI if compressed_file is None:
di2['media'] = fileEntry._localURI
else:
di2['media'] = compressed_file._localURI
else: else:
fileEntry.open() ttmp = fileEntry if compressed_file is None else compressed_file
ttmp.open()
di2['media'] = f'attach://file{ind2}' di2['media'] = f'attach://file{ind2}'
di3[f'file{ind2}'] = (fileEntry._fullfn, fileEntry._f) di3[f'file{ind2}'] = (ttmp._fullfn, ttmp._f)
ind2 = ind2 + 1 ind2 = ind2 + 1
if len(di['media']) == 0: if len(di['media']) == 0:
di2['caption'] = text.tostr(1024) di2['caption'] = text.tostr(1024)
@@ -1479,7 +1517,7 @@ class callbackQueryHandle(Thread):
self._main._request("editMessageText", "post", json=di) self._main._request("editMessageText", "post", json=di)
self.answer() self.answer()
return return
elif self._inlineKeyBoardCommand in [InlineKeyBoardCallBack.DisableWebPagePreview, InlineKeyBoardCallBack.ShowRSSTitle, InlineKeyBoardCallBack.ShowContentTitle, InlineKeyBoardCallBack.ShowContent, InlineKeyBoardCallBack.SendMedia, InlineKeyBoardCallBack.DisplayEntryLink, InlineKeyBoardCallBack.SendImgAsFile, InlineKeyBoardCallBack.SendUgoiraWithOriginPixFmt, InlineKeyBoardCallBack.SendUgoiraMethod]: elif self._inlineKeyBoardCommand in [InlineKeyBoardCallBack.DisableWebPagePreview, InlineKeyBoardCallBack.ShowRSSTitle, InlineKeyBoardCallBack.ShowContentTitle, InlineKeyBoardCallBack.ShowContent, InlineKeyBoardCallBack.SendMedia, InlineKeyBoardCallBack.DisplayEntryLink, InlineKeyBoardCallBack.SendImgAsFile, InlineKeyBoardCallBack.SendUgoiraWithOriginPixFmt, InlineKeyBoardCallBack.SendUgoiraMethod, InlineKeyBoardCallBack.CompressBigImage]:
if self._inlineKeyBoardCommand == InlineKeyBoardCallBack.DisableWebPagePreview: if self._inlineKeyBoardCommand == InlineKeyBoardCallBack.DisableWebPagePreview:
self._rssMeta.config.disable_web_page_preview = not self._rssMeta.config.disable_web_page_preview self._rssMeta.config.disable_web_page_preview = not self._rssMeta.config.disable_web_page_preview
elif self._inlineKeyBoardCommand == InlineKeyBoardCallBack.ShowRSSTitle: elif self._inlineKeyBoardCommand == InlineKeyBoardCallBack.ShowRSSTitle:
@@ -1498,6 +1536,8 @@ class callbackQueryHandle(Thread):
self._rssMeta.config.send_ugoira_with_origin_pix_fmt = not self._rssMeta.config.send_ugoira_with_origin_pix_fmt self._rssMeta.config.send_ugoira_with_origin_pix_fmt = not self._rssMeta.config.send_ugoira_with_origin_pix_fmt
elif self._inlineKeyBoardCommand == InlineKeyBoardCallBack.SendUgoiraMethod: elif self._inlineKeyBoardCommand == InlineKeyBoardCallBack.SendUgoiraMethod:
self._rssMeta.config.send_ugoira_method = SendUgoiraMethod(int(self._inputList[3])) self._rssMeta.config.send_ugoira_method = SendUgoiraMethod(int(self._inputList[3]))
elif self._inlineKeyBoardCommand == InlineKeyBoardCallBack.CompressBigImage:
self._rssMeta.config.compress_big_image = not self._rssMeta.config.compress_big_image
di = {'chat_id': self._rssMeta.chatId, di = {'chat_id': self._rssMeta.chatId,
'message_id': self._rssMeta.messageId} 'message_id': self._rssMeta.messageId}
di['text'] = getMediaInfo( di['text'] = getMediaInfo(
@@ -1684,7 +1724,7 @@ class callbackQueryHandle(Thread):
self._main._request("editMessageText", "post", json=di) self._main._request("editMessageText", "post", json=di)
self.answer() self.answer()
return return
elif self._inlineKeyBoardForRSSListCommand in [InlineKeyBoardForRSSList.DisableWebPagePreview, InlineKeyBoardForRSSList.ShowRSSTitle, InlineKeyBoardForRSSList.ShowContentTitle, InlineKeyBoardForRSSList.ShowContent, InlineKeyBoardForRSSList.SendMedia, InlineKeyBoardForRSSList.DisplayEntryLink, InlineKeyBoardForRSSList.SendImgAsFile, InlineKeyBoardForRSSList.SendUgoiraWithOriginPixFmt, InlineKeyBoardForRSSList.SendUgoiraMethod]: elif self._inlineKeyBoardForRSSListCommand in [InlineKeyBoardForRSSList.DisableWebPagePreview, InlineKeyBoardForRSSList.ShowRSSTitle, InlineKeyBoardForRSSList.ShowContentTitle, InlineKeyBoardForRSSList.ShowContent, InlineKeyBoardForRSSList.SendMedia, InlineKeyBoardForRSSList.DisplayEntryLink, InlineKeyBoardForRSSList.SendImgAsFile, InlineKeyBoardForRSSList.SendUgoiraWithOriginPixFmt, InlineKeyBoardForRSSList.SendUgoiraMethod, InlineKeyBoardForRSSList.CompressBigImage]:
di = {'chat_id': self._data['message']['chat']['id'], di = {'chat_id': self._data['message']['chat']['id'],
'message_id': self._data['message']['message_id']} 'message_id': self._data['message']['message_id']}
rssList = self._main._db.getRSSListByChatId(chatId) rssList = self._main._db.getRSSListByChatId(chatId)
@@ -1715,6 +1755,8 @@ class callbackQueryHandle(Thread):
config.send_ugoira_with_origin_pix_fmt = not config.send_ugoira_with_origin_pix_fmt config.send_ugoira_with_origin_pix_fmt = not config.send_ugoira_with_origin_pix_fmt
elif self._inlineKeyBoardForRSSListCommand == InlineKeyBoardForRSSList.SendUgoiraMethod: elif self._inlineKeyBoardForRSSListCommand == InlineKeyBoardForRSSList.SendUgoiraMethod:
config.send_ugoira_method = SendUgoiraMethod(int(self._inputList[5])) config.send_ugoira_method = SendUgoiraMethod(int(self._inputList[5]))
elif self._inlineKeyBoardForRSSListCommand == InlineKeyBoardForRSSList.CompressBigImage:
config.compress_big_image = not config.compress_big_image
updated = self._main._db.updateChatConfig(chatEntry) updated = self._main._db.updateChatConfig(chatEntry)
if updated: if updated:
self.answer('修改设置成功') self.answer('修改设置成功')

View File

@@ -15,14 +15,14 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import unique, Enum from enum import unique, Enum
from traceback import print_exc from traceback import print_exc
from typing import Optional from typing import Optional, Tuple
try: try:
from _rssbotlib import version, VideoInfo, convert_ugoira_to_mp4, AVDict, convert_to_tg_thumbnail from _rssbotlib import version, VideoInfo, convert_ugoira_to_mp4, AVDict, convert_to_tg_thumbnail, tg_image_compress
have_rssbotlib = True have_rssbotlib = True
except ImportError: except ImportError:
have_rssbotlib = False have_rssbotlib = False
if have_rssbotlib: if have_rssbotlib:
from fileEntry import FileEntry, remove from fileEntry import FileEntry, SubFileEntry, remove
@unique @unique
@@ -35,10 +35,11 @@ class AddVideoInfoResult(Enum):
if have_rssbotlib: if have_rssbotlib:
class RSSBotLib: class RSSBotLib:
def __init__(self, m): def __init__(self, m):
from rssbot import main from rssbot import main, MAX_PHOTO_SIZE
self._main: main = m self._main: main = m
self._max_photo_size = MAX_PHOTO_SIZE
self._version = version() self._version = version()
if self._version is None or self._version > [1, 0, 0, 2]: if self._version is None or self._version >= [1, 2, 0, 0] or self._version < [1, 1, 0, 0]:
raise ValueError('RSSBotLib Version unknown or not supported.') raise ValueError('RSSBotLib Version unknown or not supported.')
def addVideoInfo(self, url: str, data: dict, loc: str = None) -> AddVideoInfoResult: def addVideoInfo(self, url: str, data: dict, loc: str = None) -> AddVideoInfoResult:
@@ -113,10 +114,35 @@ if have_rssbotlib:
print_exc() print_exc()
return False return False
def is_supported_photo(self, f: str) -> Optional[bool]: def compress_image(self, f: FileEntry, format: str = 'jpeg', max_len: int = 1920, force_yuv420p: bool = True) -> Optional[SubFileEntry]:
try:
na = f'_compressed_{max_len}' if force_yuv420p else f'_compressed_origin_{max_len}'
if f.getSubFile(na, format) is not None:
return f.getSubFile(na, format)
dst = f.getSubPath(na, format)
opt = AVDict()
if not force_yuv420p:
opt['force_yuv420p'] = '0'
if not tg_image_compress(f._abspath, dst, format, max_len, opt):
return None
f.addSubFile(na, format)
return f.getSubFile(na, format)
except Exception:
print_exc()
try:
remove(dst)
except Exception:
print_exc()
return None
def is_supported_photo(self, f: FileEntry) -> Optional[Tuple[bool, bool]]:
"""
第一个返回是否符合TG图片的要求
第二个返回图片解析度过大时返回True
"""
try: try:
v = VideoInfo() v = VideoInfo()
if not v.parse(f): if not v.parse(f._abspath):
return None return None
streams = v.streams streams = v.streams
width = None width = None
@@ -128,7 +154,12 @@ if have_rssbotlib:
break break
if width is None or height is None: if width is None or height is None:
return None return None
return False if width + height > 10000 or width / height > 20 or height / width > 20 else True if width / height >= 20 or height / width >= 20:
return False, False
elif width + height >= 10000 or f._fileSize >= self._max_photo_size:
return False, True
else:
return True, False
except Exception: except Exception:
print_exc() print_exc()
return None return None

View File

@@ -49,6 +49,7 @@ class InlineKeyBoardForRSSList(Enum):
SendOriginFileName = 21 SendOriginFileName = 21
SendUgoiraWithOriginPixFmt = 22 SendUgoiraWithOriginPixFmt = 22
SendUgoiraMethod = 23 SendUgoiraMethod = 23
CompressBigImage = 24
def getTextContentForRSSInList(rssEntry: RSSEntry, s: settings) -> str: def getTextContentForRSSInList(rssEntry: RSSEntry, s: settings) -> str:
@@ -83,6 +84,7 @@ def getTextContentForRSSInList(rssEntry: RSSEntry, s: settings) -> str:
if have_rssbotlib: if have_rssbotlib:
text += f'发送原始像素格式的Pixiv动图:{config.send_ugoira_with_origin_pix_fmt}' text += f'发送原始像素格式的Pixiv动图:{config.send_ugoira_with_origin_pix_fmt}'
text += f'发送Pixiv动图为{config.send_ugoira_method}' text += f'发送Pixiv动图为{config.send_ugoira_method}'
text += f"发送时压缩过大图片:{config.compress_big_image}"
text += f"RSS全局设置:" text += f"RSS全局设置:"
text += f"发送时使用原文件名:{config.send_origin_file_name}" text += f"发送时使用原文件名:{config.send_origin_file_name}"
return text.tostr() return text.tostr()
@@ -219,6 +221,8 @@ def getInlineKeyBoardForRSSSettingsInList(chatId: int, rssEntry: RSSEntry, index
temp2 = SendUgoiraMethod((config.send_ugoira_method.value + 1) % 4) temp2 = SendUgoiraMethod((config.send_ugoira_method.value + 1) % 4)
temp = f'发送Pixiv动图为{temp2}' temp = f'发送Pixiv动图为{temp2}'
d[i].append({'text': temp, 'callback_data': f'1,{chatId},{InlineKeyBoardForRSSList.SendUgoiraMethod.value},{index},{rssEntry.id},{temp2.value}'}) d[i].append({'text': temp, 'callback_data': f'1,{chatId},{InlineKeyBoardForRSSList.SendUgoiraMethod.value},{index},{rssEntry.id},{temp2.value}'})
temp = f"{'禁用' if config.compress_big_image else '启用'}压缩过大图片"
d[i].append({'text': temp, 'callback_data': f'1,{chatId},{InlineKeyBoardForRSSList.CompressBigImage.value},{index},{rssEntry.id}'})
d.append([]) d.append([])
i = i + 1 i = i + 1
d[i].append( d[i].append(