File size: 4,479 Bytes
c0e9d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import asyncio
import json
import os
import time

try:
    from pyUltroid import LOGS as LOGGER, udB, Var
except ImportError:
    import logging

    logging.basicConfig(
        level=logging.INFO,
        format="[%(asctime)s - %(levelname)s] - %(name)s - %(filename)s:%(lineno)d - %(message)s",
        datefmt="%d-%b-%y %H:%M:%S",
        handlers=[logging.StreamHandler(), logging.FileHandler("vc.log")],
    )

    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("apscheduler").setLevel(logging.WARNING)

    # logging.getLogger('pytgcalls').setLevel(logging.DEBUG)
    # logging.getLogger('ffmpeg').setLevel(logging.DEBUG)
    # logging.getLogger('ntgcalls').setLevel(logging.DEBUG)
    # logging.getLogger('webrtc').setLevel(logging.DEBUG)

    LOGGER = logging.getLogger("VC")
    udB = None
    Var = None

# mutagen is a declared dependency (requirements.txt) and is imported directly
# by the vc modules that need it (vc/_spotify.py, vc/_jiosaavn.py). The old
# utils.tools.import_library("mutagen") call pip-installed at import time and
# dragged utils/tools.py's heavy import chain (psutil, PIL, requests) into
# every vc import — both removed deliberately (W1-A). The canonical helper
# now lives in pyUltroid.fns.tools.import_library and does not pip-install at
# runtime (W4-B).

DOWNLOADS_DIR = "./temp"
# API credentials are sourced from pyUltroid.Var / udB / environment variables
# instead of being hardcoded.
API_KEY = (
    (udB.get_key("MUSIC_API_KEY") if udB else None)
    or (getattr(Var, "MUSIC_API_KEY", None) if Var else None)
    or os.environ.get("MUSIC_API_KEY", "")
)
API_URL = (
    (udB.get_key("MUSIC_API_URL") if udB else None)
    or (getattr(Var, "MUSIC_API_URL", None) if Var else None)
    or os.environ.get("MUSIC_API_URL", "")
)


def sec_to_min(seconds):
    """
    Convert seconds to minutes:second format.
    """
    try:
        minutes = int(seconds // 60)
        remaining_seconds = int(seconds % 60)
        return f"{minutes}:{remaining_seconds:02}"
    except Exception as e:
        LOGGER.warning("Failed to convert seconds to minutes:seconds format: %s", e)
        return None


async def get_audio_duration(file_path):
    try:
        proc = await asyncio.create_subprocess_exec(
            "ffprobe",
            "-v",
            "quiet",
            "-print_format",
            "json",
            "-show_format",
            "-show_streams",
            file_path,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, _ = await proc.communicate()
        data = json.loads(stdout)
        duration = float(data["format"]["duration"])
        return int(duration)
    except Exception as e:
        LOGGER.warning("Failed to get audio duration using ffprobe: %s", e)
        return 0


def cleanup_downloads_dir(
    directory: str = DOWNLOADS_DIR, older_than_seconds: int = 3600
) -> int:
    """Remove stale temporary files from the downloads directory.

    Only files older than ``older_than_seconds`` (default 1 hour) are deleted so
    that tracks currently being streamed in other chats are never removed.
    Returns the number of files removed.
    """
    removed = 0
    if not directory or not os.path.isdir(directory):
        return removed
    now = time.time()
    try:
        for name in os.listdir(directory):
            path = os.path.join(directory, name)
            if not os.path.isfile(path):
                continue
            try:
                if now - os.path.getmtime(path) > older_than_seconds:
                    os.remove(path)
                    removed += 1
            except OSError:
                continue
    except OSError as e:
        LOGGER.warning("cleanup_downloads_dir failed: %s", e)
    return removed


def ms_to_seconds(value):
    """Convert a pytgcalls group-call timestamp to whole seconds.

    ``PyTgCalls.time()`` returns the raw stream timestamp
    (``channels[0].last_timestamp_ms``), which is milliseconds, even though
    it is usually consumed as if it were seconds. Returning it raw made every
    progress calculation 1000x too large.

    Values at or below 1000 pass through, so a bound client that already
    reports seconds is not mangled.
    """
    if value is None:
        return 0
    try:
        value = int(value)
    except (TypeError, ValueError):
        return 0
    if value <= 1000:
        return value
    return value // 1000