Merge pull request #26 from paul-nameless/humanize

Humanize size and duration fields
This commit is contained in:
Nameless 2020-05-09 18:48:22 +08:00 committed by GitHub
commit 50c84bb087
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 8 deletions

View file

@ -1,4 +1,5 @@
import logging import logging
from tg import utils
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -60,14 +61,14 @@ class MsgProxy:
@property @property
def size(self): def size(self):
doc = self.get_doc(self.msg) doc = self.get_doc(self.msg)
return doc["size"] return utils.humanize_size(doc["size"])
@property @property
def duration(self): def duration(self):
if self.type not in ("audio", "voice"): if self.type not in ("audio", "voice", "video", "recording"):
return None return None
doc = self.get_doc(self.msg, deep=1) doc = self.get_doc(self.msg, deep=1)
return doc["duration"] return utils.humanize_duration(doc["duration"])
@property @property
def file_name(self): def file_name(self):

View file

@ -1,14 +1,35 @@
import logging
import os
from typing import Optional
import subprocess
from functools import wraps
import curses import curses
import logging
import math
import os
import subprocess
from datetime import datetime
from functools import wraps
from typing import Optional
from tg import config from tg import config
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def humanize_size(
num, suffix="B", suffixes=("", "K", "M", "G", "T", "P", "E", "Z")
):
magnitude = int(math.floor(math.log(num, 1024)))
val = num / math.pow(1024, magnitude)
if magnitude > 7:
return "{:.1f}{}{}".format(val, "Yi", suffix)
return "{:3.1f}{}{}".format(val, suffixes[magnitude], suffix)
def humanize_duration(seconds):
dt = datetime.utcfromtimestamp(seconds)
fmt = "%-M:%S"
if seconds >= 3600:
fmt = "%-H:%M:%S"
return dt.strftime(fmt)
def num(value: str, default: Optional[int] = None) -> Optional[int]: def num(value: str, default: Optional[int] = None) -> Optional[int]:
try: try:
return int(value) return int(value)