98 lines
2.4 KiB
Python
98 lines
2.4 KiB
Python
''' Utilities '''
|
|
|
|
import os
|
|
import time
|
|
import glob
|
|
import shutil
|
|
import hashlib
|
|
import mimetypes
|
|
import traceback
|
|
|
|
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
|
|
|
|
def pex() -> None:
|
|
''' Print last exception '''
|
|
traceback.print_exc()
|
|
|
|
def ensure_dir(path: str) -> bool:
|
|
''' Ensure directory existance.
|
|
'path' must NOT have trailing slash!
|
|
'''
|
|
try:
|
|
os.makedirs(path, exist_ok=True)
|
|
return True
|
|
except:
|
|
return False
|
|
|
|
def get_script_dir() -> str:
|
|
''' Returns path of this script (utils.py) '''
|
|
return os.path.dirname(os.path.abspath(__file__))
|
|
|
|
def get_all_mods() -> list[str]:
|
|
''' Get list of all supported mods '''
|
|
sd = get_script_dir()
|
|
res = [f for f in os.listdir(sd) if os.path.isfile(os.path.join(sd, f))]
|
|
res = [f.split('.')[0] for f in res if f.startswith('mod_') and f.endswith('.py')]
|
|
return res
|
|
|
|
def get_md5(data: str) -> str:
|
|
''' Returns MD5 for data '''
|
|
md5_hash = hashlib.md5()
|
|
md5_hash.update(str(data).encode('ascii', errors='ignore'))
|
|
return md5_hash.hexdigest()
|
|
|
|
|
|
def get_unique_md5() -> str:
|
|
''' Returns unique MD5 '''
|
|
md5_hash = hashlib.md5()
|
|
md5_hash.update(str(time.time()).encode('ascii'))
|
|
return md5_hash.hexdigest()
|
|
|
|
def which(cmd: str) -> str:
|
|
''' Analogue to UNIX which '''
|
|
return shutil.which(cmd)
|
|
|
|
def get_mime(ext) -> str:
|
|
''' ext must not start with dot '''
|
|
try:
|
|
mime_type, _ = mimetypes.guess_type('file.%s' % ext)
|
|
return mime_type
|
|
except:
|
|
return 'video/%s' % ext
|
|
|
|
def rm_glob(path_glob: str) -> None:
|
|
''' Delete files using glob (files only) '''
|
|
try:
|
|
files = glob.glob(path_glob)
|
|
for f in files:
|
|
try:
|
|
os.remove(f)
|
|
except:
|
|
pass
|
|
except:
|
|
pass
|
|
|
|
def id_to_peer(id: str):
|
|
s = id[0]
|
|
try:
|
|
if s == 'u':
|
|
return PeerUser(user_id=int(id[1:]))
|
|
elif s == 'c':
|
|
return PeerChat(chat_id=int(id[1:]))
|
|
elif s == 's':
|
|
return PeerChannel(channel_id=int(id[1:]))
|
|
else:
|
|
return int(id)
|
|
except:
|
|
return 'me'
|
|
|
|
def peer_to_id(peer) -> str:
|
|
t = type(peer)
|
|
if t is PeerUser:
|
|
return 'u%s' % peer.user_id
|
|
elif t is PeerChat:
|
|
return 'c%s' % peer.chat_id
|
|
elif t is PeerChannel:
|
|
return 's%s' % peer.channel_id
|
|
return str(peer)
|