start_video.py

59 lines · 2087 bytes

 1import os
 2import json
 3import socket
 4import subprocess
 5
 6def start_video(link, salt:str, args:list=[]):
 7    print(f"SALT IS {salt}")
 8
 9    args_str = ' '.join(args)
10    
11    # Build the complete command string
12    command = f"mpv {args_str} --input-ipc-server=/tmp/mpvsocket{salt} {link}"
13
14    subprocess.Popen(['alacritty', '-e', 'bash', '-c', command])
15    # os.system()
16    # Path to the MPV socket
17    # socket_path = f'/tmp/mpvsocket{salt}'
18    # Connect to the MPV IPC socket
19    # client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
20    # client.connect(socket_path)
21
22def send_command(ipc_socket_path, command):
23    """
24    Sends a command to the MPV IPC socket and returns the response.
25    """
26    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
27        s.connect(ipc_socket_path)
28        command_str = json.dumps({"command": command}) + "\n"
29        s.sendall(command_str.encode())
30        response = s.recv(4096).decode()
31
32        try:
33            response_data = json.loads(response)
34            if 'data' in response_data:
35                return response_data['data']
36        except json.JSONDecodeError:
37            return None
38    return None
39
40def get_percentage_watched(ipc_socket_path):
41    """
42    Calculates the percentage watched of the currently playing video.
43    """
44    # Get current playback time and total duration
45    current_time = send_command(ipc_socket_path, ["get_property", "time-pos"])
46    duration = send_command(ipc_socket_path, ["get_property", "duration"])
47
48    if current_time is not None and duration is not None and duration > 0:
49        percentage_watched = (current_time / duration) * 100
50        return percentage_watched
51    return None
52
53def percentage_watched(playback_time:int, duration:int):
54    if playback_time is not None and duration is not None and duration > 0:
55        video_percentage_watched = (playback_time/duration) * 100
56        return video_percentage_watched
57    return None
58
59# start_video("https://video.wixstatic.com/video/36bbae_bef5207b465447f19c0f9366f3ee1c27/720p/mp4/file.mp4", "10", ['--start=100'])