-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
209 lines (147 loc) · 4.86 KB
/
main.py
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import os
import socketio
from dotenv import load_dotenv
import vlc
import time
import requests
import logging
import traceback
import math
from threading import Thread
from urllib.parse import urljoin
load_dotenv()
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO').upper()
logging.basicConfig(level=LOG_LEVEL)
namespace = '/audio'
running = True
sio = socketio.Client(logger=True)
player: vlc.MediaPlayer | None = None
sync_thread: Thread | None = None
sync_thread_running = False
last_audio_sync = 0
auth_cookie = ''
audio_listener_id = -1
def get_headers():
global auth_cookie
return {'cookie': 'connect.sid=' + auth_cookie}
def sync_audio_timings():
global sync_thread_running, last_audio_sync
while sync_thread_running:
now = time.time()
# Synchronize every 30 seconds if audio is playing
if now - last_audio_sync >= 30 and player is not None and player.is_playing() and player.get_time() >= 0:
last_audio_sync = now
player_ms = player.get_time()
now_ms = math.floor(time.time_ns() / 1000000)
sio.emit('sync_audio_timings', {
'startTime': now_ms,
'timestamp': player_ms,
}, namespace=namespace)
time.sleep(0.1)
def create_sync_loop():
global sync_thread, sync_thread_running
sync_thread_running = True
sync_thread = Thread(target=sync_audio_timings)
sync_thread.daemon = True
sync_thread.start()
def stop_sync_loop():
global sync_thread, sync_thread_running
if sync_thread is None:
return
sync_thread_running = False
sync_thread.join()
def main():
global sio, player, running, auth_cookie, audio_listener_id
url = urljoin(os.environ['URL'], '/api/auth/key')
result = requests.post(url, {'key': os.environ['API_KEY']})
json = result.json()
if result.status_code != 200:
raise Exception("Could not authenticate with core: [HTTP {}]: {}".format(
result.status_code,
json['details'] if json['details'] else json['message']),
)
audio_listener_id = json['audioId']
auth_cookie = result.cookies.get('connect.sid')
# Initialize SocketIO
sio.connect(os.environ['URL'], headers=get_headers,
namespaces=['/', namespace])
logging.info('Connected')
try:
while running:
time.sleep(0.5)
except KeyboardInterrupt:
running = False
stop_audio()
def set_audio_playing(playing: bool):
url = urljoin(os.environ['URL'], "/api/audio/{}/playing".format(audio_listener_id))
try:
requests.post(url, { 'playing': playing }, headers=get_headers())
except Exception as e:
logging.error(e)
@sio.event(namespace=namespace)
def play_audio(url: str, seconds=0):
global player
logging.info('receive play event')
load_audio(url)
if player is None:
return
if player.play() < 0:
raise Exception('Could not start playback')
if seconds is not None:
skip_to(seconds)
# Start a synchronization worker
create_sync_loop()
set_audio_playing(True)
@sio.event(namespace=namespace)
def stop_audio():
global player
logging.info('receive stop event')
# Stop the synchronization thread
stop_sync_loop()
if player is not None and player.is_playing():
player.pause()
set_audio_playing(False)
@sio.event(namespace=namespace)
def skip_to(seconds):
global player
logging.info('receive skip event: ' + str(seconds))
if player is None:
return
position = int(seconds * 1000)
player.set_time(position)
def load_audio(url: str):
global player
if url.startswith('http'):
full_url = url
else:
full_url = urljoin(os.environ['URL'], url)
logging.info('load audio: ' + full_url)
if player:
player.stop()
try:
# creating a vlc instance
vlc_instance: vlc.Instance = vlc.Instance()
# creating a media player
player = vlc_instance.media_player_new()
# creating a media
media: vlc.Media = vlc_instance.media_new(full_url)
# setting media to the player
player.set_media(media)
logging.info('Audio file initialized!')
except Exception as e:
logging.error(traceback.format_exc())
@sio.event
def disconnect():
global player
if player:
player.stop()
player = None
set_audio_playing(False)
if __name__ == '__main__':
while running:
try:
main()
except Exception as e:
logging.error(traceback.format_exc())
print('Something went wrong. Try again after 5 seconds...')
time.sleep(5)