Skip to content

Commit

Permalink
tweaked @Harsh-br0's PR
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed May 30, 2021
1 parent 6a555f9 commit 32b9355
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 40 deletions.
6 changes: 3 additions & 3 deletions userge/plugins/misc/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from rarfile import RarFile, is_rarfile

from userge import userge, Message, Config, pool
from userge.utils import check_numerical_order, humanbytes, time_formatter
from userge.utils import humanbytes, time_formatter
from userge.utils.exceptions import ProcessCanceled

_LOG = userge.getLogger(__name__)
Expand Down Expand Up @@ -347,7 +347,7 @@ async def ls_dir(message: Message) -> None:
if path_.is_dir():
folders = ''
files = ''
for p_s in sorted(path_.iterdir(), key=lambda a: check_numerical_order(a.name)):
for p_s in sorted(path_.iterdir()):
if p_s.is_file():
if str(p_s).endswith((".mp3", ".flac", ".wav", ".m4a")):
files += '🎵'
Expand Down Expand Up @@ -385,7 +385,7 @@ async def dset_(message: Message) -> None:
Config.DOWN_PATH = path.rstrip('/') + '/'
await message.edit(f"set `{path}` as **working directory** successfully!", del_in=5)
except Exception as p_e:
await message.err(p_e)
await message.err(str(p_e))


@userge.on_cmd('dreset', about={
Expand Down
4 changes: 2 additions & 2 deletions userge/plugins/misc/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from pyrogram.errors.exceptions import FloodWait

from userge import userge, Config, Message
from userge.utils import check_numerical_order, progress, take_screen_shot, humanbytes
from userge.utils import sort_file_name_key, progress, take_screen_shot, humanbytes
from userge.utils.exceptions import ProcessCanceled
from userge.plugins.misc.download import tg_download, url_download

Expand Down Expand Up @@ -126,7 +126,7 @@ def explorer(_path: Path) -> None:
if _path.is_file() and _path.stat().st_size:
file_paths.append(_path)
elif _path.is_dir():
for i in sorted(_path.iterdir(), key=lambda a: check_numerical_order(a.name)):
for i in sorted(_path.iterdir(), key=lambda a: sort_file_name_key(a.name)):
explorer(i)
explorer(path)
else:
Expand Down
2 changes: 1 addition & 1 deletion userge/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from .progress import progress # noqa
from .sys_tools import SafeDict, get_import_path, terminate, secure_text # noqa
from .tools import (check_numerical_order, # noqa
from .tools import (sort_file_name_key, # noqa
demojify,
get_file_id_of_media,
humanbytes,
Expand Down
68 changes: 34 additions & 34 deletions userge/utils/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,49 @@
#
# All rights reserved.

import os
import re
import shlex
import asyncio
from os.path import basename
from typing import Tuple, List, Optional, Union
from os.path import basename, splitext, join, exists
from emoji import get_emoji_regexp
from typing import Tuple, List, Optional

from html_telegraph_poster import TelegraphPoster
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup

import userge

_LOG = userge.logging.getLogger(__name__)
_EMOJI_PATTERN = re.compile(
"["
"\U0001F1E0-\U0001F1FF" # flags (iOS)
"\U0001F300-\U0001F5FF" # symbols & pictographs
"\U0001F600-\U0001F64F" # emoticons
"\U0001F680-\U0001F6FF" # transport & map symbols
"\U0001F700-\U0001F77F" # alchemical symbols
"\U0001F780-\U0001F7FF" # Geometric Shapes Extended
"\U0001F800-\U0001F8FF" # Supplemental Arrows-C
"\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs
"\U0001FA00-\U0001FA6F" # Chess Symbols
"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A
"\U00002702-\U000027B0" # Dingbats
"]+")
_BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)]\[buttonurl:(?:/{0,2})(.+?)(:same)?])")


def check_numerical_order(a: str) -> Union[float, str]:
r = getattr(re.search(r"^\d+(?:\.\d+)?", a),
"group",
lambda: None)()
if r:
return float(r)
return a


# https://github.com/UsergeTeam/Userge-Plugins/blob/master/plugins/tweet.py
_BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)]\[buttonurl:/{0,2}(.+?)(:same)?])")


def sort_file_name_key(file_name: str) -> float:
if not isinstance(file_name, str):
raise TypeError(f"Invalid type provided: {type(file_name)}")

prefix, suffix = splitext(file_name)

val = 0.0
inc = 2

i = 0
for c in list(prefix)[::-1]:
if not c.isdigit():
i += inc
val += ord(c) * 10 ** i

i = 0
for c in list(suffix):
if not c.isdigit():
i += inc
val += ord(c) * 10 ** i

return val


def demojify(string: str) -> str:
""" Remove emojis and other non-safe characters from string """
return re.sub(_EMOJI_PATTERN, '', string)
return get_emoji_regexp().sub(u'', string)


def get_file_id_of_media(message: 'userge.Message') -> Optional[str]:
Expand Down Expand Up @@ -120,19 +120,19 @@ async def take_screen_shot(video_file: str, duration: int, path: str = '') -> Op
""" take a screenshot """
_LOG.info('[[[Extracting a frame from %s ||| Video duration => %s]]]', video_file, duration)
ttl = duration // 2
thumb_image_path = path or os.path.join(userge.Config.DOWN_PATH, f"{basename(video_file)}.jpg")
thumb_image_path = path or join(userge.Config.DOWN_PATH, f"{basename(video_file)}.jpg")
command = f'''ffmpeg -ss {ttl} -i "{video_file}" -vframes 1 "{thumb_image_path}"'''
err = (await runcmd(command))[1]
if err:
_LOG.error(err)
return thumb_image_path if os.path.exists(thumb_image_path) else None
return thumb_image_path if exists(thumb_image_path) else None


def parse_buttons(markdown_note: str) -> Tuple[str, Optional[InlineKeyboardMarkup]]:
""" markdown_note to string and buttons """
prev = 0
note_data = ""
buttons: List[Tuple[str, str, str]] = []
buttons: List[Tuple[str, str, bool]] = []
for match in _BTN_URL_REGEX.finditer(markdown_note):
n_escapes = 0
to_check = match.start(1) - 1
Expand Down

0 comments on commit 32b9355

Please sign in to comment.