forked from subinps/VCPlayerBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1810 lines (1682 loc) · 65.4 KB
/
utils.py
File metadata and controls
1810 lines (1682 loc) · 65.4 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (C) @subinps
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from logger import LOGGER
try:
from pyrogram.raw.types import InputChannel
from wrapt_timeout_decorator import timeout
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.jobstores.base import ConflictingIdError
from pyrogram.raw.functions.channels import GetFullChannel
from pytgcalls import StreamType
from youtube_dl import YoutubeDL
from pyrogram import filters
from pymongo import MongoClient
from datetime import datetime
from threading import Thread
from config import Config
from asyncio import sleep
from bot import bot
import subprocess
import asyncio
import random
import re
import ffmpeg
import json
import time
import sys
import os
import math
from pyrogram.errors.exceptions.bad_request_400 import (
BadRequest,
ScheduleDateInvalid
)
from pytgcalls.types.input_stream import (
AudioVideoPiped,
AudioPiped,
AudioImagePiped
)
from pytgcalls.types.input_stream import (
AudioParameters,
VideoParameters
)
from pyrogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message
)
from pyrogram.raw.functions.phone import (
EditGroupCallTitle,
CreateGroupCall,
ToggleGroupCallRecord,
StartScheduledGroupCall
)
from pytgcalls.exceptions import (
GroupCallNotFound,
NoActiveGroupCall,
InvalidVideoProportion
)
from PIL import (
Image,
ImageFont,
ImageDraw
)
from user import (
group_call,
USER
)
except ModuleNotFoundError:
import os
import sys
import subprocess
file=os.path.abspath("requirements.txt")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', file, '--upgrade'])
os.execl(sys.executable, sys.executable, *sys.argv)
if Config.DATABASE_URI:
from database import db
monclient = MongoClient(Config.DATABASE_URI)
jobstores = {
'default': MongoDBJobStore(client=monclient, database=Config.DATABASE_NAME, collection='scheduler')
}
scheduler = AsyncIOScheduler(jobstores=jobstores)
else:
scheduler = AsyncIOScheduler()
scheduler.start()
async def play():
song=Config.playlist[0]
if song[3] == "telegram":
file=Config.GET_FILE.get(song[5])
if not file:
await download(song)
while not file:
await sleep(1)
file=Config.GET_FILE.get(song[5])
LOGGER.info("Downloading the file from TG")
while not os.path.exists(file):
await sleep(1)
elif song[3] == "url":
file=song[2]
else:
file=await get_link(song[2])
if not file:
await skip()
return False
link, seek, pic, width, height = await chek_the_media(file, title=f"{song[1]}")
if not link:
LOGGER.warning("Unsupported link, Skiping from queue.")
return
await sleep(1)
if Config.STREAM_LINK:
Config.STREAM_LINK=False
await join_call(link, seek, pic, width, height)
async def schedule_a_play(job_id, date):
try:
scheduler.add_job(run_schedule, "date", [job_id], id=job_id, run_date=date, max_instances=50, misfire_grace_time=None)
except ConflictingIdError:
LOGGER.warning("This already scheduled")
return
if not Config.CALL_STATUS or not Config.IS_ACTIVE:
if Config.SCHEDULE_LIST[0]['job_id'] == job_id \
and (date - datetime.now()).total_seconds() < 86400:
song=Config.SCHEDULED_STREAM.get(job_id)
if Config.IS_RECORDING:
scheduler.add_job(start_record_stream, "date", id=str(Config.CHAT), run_date=date, max_instances=50, misfire_grace_time=None)
try:
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(Config.CHAT)),
random_id=random.randint(10000, 999999999),
schedule_date=int(date.timestamp()),
title=song['1']
)
)
Config.HAS_SCHEDULE=True
except ScheduleDateInvalid:
LOGGER.error("Unable to schedule VideoChat, since date is invalid")
except Exception as e:
LOGGER.error(f"Error in scheduling voicechat- {e}")
await sync_to_db()
async def run_schedule(job_id):
data=Config.SCHEDULED_STREAM.get(job_id)
if not data:
LOGGER.error("The Scheduled stream was not played, since data is missing")
old=filter(lambda k: k['job_id'] == job_id, Config.SCHEDULE_LIST)
if old:
Config.SCHEDULE_LIST.remove(old)
await sync_to_db()
pass
else:
if Config.HAS_SCHEDULE:
if not await start_scheduled():
LOGGER.error("Scheduled stream skipped, Reason - Unable to start a voice chat.")
return
data_ = [{1:data['1'], 2:data['2'], 3:data['3'], 4:data['4'], 5:data['5']}]
Config.playlist = data_ + Config.playlist
await play()
LOGGER.info("Starting Scheduled Stream")
del Config.SCHEDULED_STREAM[job_id]
old=list(filter(lambda k: k['job_id'] == job_id, Config.SCHEDULE_LIST))
if old:
for old_ in old:
Config.SCHEDULE_LIST.remove(old_)
if not Config.SCHEDULE_LIST:
Config.SCHEDULED_STREAM = {} #clear the unscheduled streams
await sync_to_db()
if len(Config.playlist) <= 1:
return
await download(Config.playlist[1])
async def cancel_all_schedules():
for sch in Config.SCHEDULE_LIST:
job=sch['job_id']
k=scheduler.get_job(job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
if Config.SCHEDULED_STREAM.get(job):
del Config.SCHEDULED_STREAM[job]
Config.SCHEDULE_LIST.clear()
await sync_to_db()
LOGGER.info("All the schedules are removed")
async def skip():
if Config.STREAM_LINK and len(Config.playlist) == 0 and Config.IS_LOOP:
await stream_from_link()
return
elif not Config.playlist \
and Config.IS_LOOP:
LOGGER.info("Loop Play enabled, switching to STARTUP_STREAM, since playlist is empty.")
await start_stream()
return
elif not Config.playlist \
and not Config.IS_LOOP:
LOGGER.info("Loop Play is disabled, leaving call since playlist is empty.")
await leave_call()
return
old_track = Config.playlist.pop(0)
await clear_db_playlist(song=old_track)
if old_track[3] == "telegram":
file=Config.GET_FILE.get(old_track[5])
try:
os.remove(file)
except:
pass
del Config.GET_FILE[old_track[5]]
if not Config.playlist \
and Config.IS_LOOP:
LOGGER.info("Loop Play enabled, switching to STARTUP_STREAM, since playlist is empty.")
await start_stream()
return
elif not Config.playlist \
and not Config.IS_LOOP:
LOGGER.info("Loop Play is disabled, leaving call since playlist is empty.")
await leave_call()
return
LOGGER.info(f"START PLAYING: {Config.playlist[0][1]}")
if Config.DUR.get('PAUSE'):
del Config.DUR['PAUSE']
await play()
if len(Config.playlist) <= 1:
return
await download(Config.playlist[1])
async def check_vc():
a = await bot.send(GetFullChannel(channel=(await bot.resolve_peer(Config.CHAT))))
if a.full_chat.call is None:
try:
LOGGER.info("No active calls found, creating new")
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(Config.CHAT)),
random_id=random.randint(10000, 999999999)
)
)
if Config.WAS_RECORDING:
await start_record_stream()
await sleep(2)
return True
except Exception as e:
LOGGER.error(f"Unable to start new GroupCall :- {e}")
return False
else:
if Config.HAS_SCHEDULE:
await start_scheduled()
return True
async def join_call(link, seek, pic, width, height):
if not await check_vc():
LOGGER.error("No voice call found and was unable to create a new one. Exiting...")
return
if Config.HAS_SCHEDULE:
await start_scheduled()
if Config.CALL_STATUS:
if Config.IS_ACTIVE == False:
Config.CALL_STATUS = False
return await join_call(link, seek, pic, width, height)
play=await change_file(link, seek, pic, width, height)
else:
play=await join_and_play(link, seek, pic, width, height)
if play == False:
await sleep(1)
await join_call(link, seek, pic, width, height)
await sleep(1)
if not seek:
Config.DUR["TIME"]=time.time()
if Config.EDIT_TITLE:
await edit_title()
old=Config.GET_FILE.get("old")
if old:
for file in old:
os.remove(f"./downloads/{file}")
try:
del Config.GET_FILE["old"]
except:
LOGGER.error("Error in Deleting from dict")
pass
await send_playlist()
async def start_scheduled():
try:
await USER.send(
StartScheduledGroupCall(
call=(
await USER.send(
GetFullChannel(
channel=(
await USER.resolve_peer(
Config.CHAT
)
)
)
)
).full_chat.call
)
)
if Config.WAS_RECORDING:
await start_record_stream()
return True
except Exception as e:
if 'GROUPCALL_ALREADY_STARTED' in str(e):
LOGGER.warning("Already Groupcall Exist")
return True
else:
Config.HAS_SCHEDULE=False
return await check_vc()
async def join_and_play(link, seek, pic, width, height):
try:
if seek:
start=str(seek['start'])
end=str(seek['end'])
if not Config.IS_VIDEO:
await group_call.join_group_call(
int(Config.CHAT),
AudioPiped(
link,
audio_parameters=Config.AUDIO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
stream_type=StreamType().pulse_stream,
)
else:
if pic:
await group_call.join_group_call(
int(Config.CHAT),
AudioImagePiped(
link,
pic,
audio_parameters=Config.AUDIO_Q,
video_parameters=Config.VIDEO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}', ),
stream_type=StreamType().pulse_stream,
)
else:
if not width \
or not height:
LOGGER.error("No Valid Video Found and hence removed from playlist.")
return await skip()
if Config.BITRATE and Config.FPS:
await group_call.join_group_call(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=VideoParameters(
width,
height,
Config.FPS,
),
audio_parameters=AudioParameters(
Config.BITRATE
),
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
stream_type=StreamType().pulse_stream,
)
else:
await group_call.join_group_call(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=Config.VIDEO_Q,
audio_parameters=Config.AUDIO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
stream_type=StreamType().pulse_stream,
)
else:
if not Config.IS_VIDEO:
await group_call.join_group_call(
int(Config.CHAT),
AudioPiped(
link,
audio_parameters=Config.AUDIO_Q,
),
stream_type=StreamType().pulse_stream,
)
else:
if pic:
await group_call.join_group_call(
int(Config.CHAT),
AudioImagePiped(
link,
pic,
video_parameters=Config.VIDEO_Q,
audio_parameters=Config.AUDIO_Q,
),
stream_type=StreamType().pulse_stream,
)
else:
if not width \
or not height:
LOGGER.error("No Valid Video Found and hence removed from playlist.")
return await skip()
if Config.FPS and Config.BITRATE:
await group_call.join_group_call(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=VideoParameters(
width,
height,
Config.FPS,
),
audio_parameters=AudioParameters(
Config.BITRATE
),
),
stream_type=StreamType().pulse_stream,
)
else:
await group_call.join_group_call(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=Config.VIDEO_Q,
audio_parameters=Config.AUDIO_Q
),
stream_type=StreamType().pulse_stream,
)
Config.CALL_STATUS=True
return True
except NoActiveGroupCall:
try:
LOGGER.info("No active calls found, creating new")
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(Config.CHAT)),
random_id=random.randint(10000, 999999999)
)
)
if Config.WAS_RECORDING:
await start_record_stream()
await sleep(2)
await restart_playout()
except Exception as e:
LOGGER.error(f"Unable to start new GroupCall :- {e}")
pass
except InvalidVideoProportion:
if not Config.FPS and not Config.BITRATE:
Config.FPS=20
Config.BITRATE=48000
await join_and_play(link, seek, pic, width, height)
Config.FPS=False
Config.BITRATE=False
return True
else:
LOGGER.error("Invalid video")
await skip()
except Exception as e:
LOGGER.error(f"Errors Occured while joining, retrying Error- {e}")
return False
async def change_file(link, seek, pic, width, height):
try:
if seek:
start=str(seek['start'])
end=str(seek['end'])
if not Config.IS_VIDEO:
await group_call.change_stream(
int(Config.CHAT),
AudioPiped(
link,
audio_parameters=Config.AUDIO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
)
else:
if pic:
await group_call.change_stream(
int(Config.CHAT),
AudioImagePiped(
link,
pic,
audio_parameters=Config.AUDIO_Q,
video_parameters=Config.VIDEO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}', ),
)
else:
if not width \
or not height:
LOGGER.error("No Valid Video Found and hence removed from playlist.")
return await skip()
if Config.FPS and Config.BITRATE:
await group_call.change_stream(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=VideoParameters(
width,
height,
Config.FPS,
),
audio_parameters=AudioParameters(
Config.BITRATE
),
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
)
else:
await group_call.change_stream(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=Config.VIDEO_Q,
audio_parameters=Config.AUDIO_Q,
additional_ffmpeg_parameters=f'-ss {start} -atend -t {end}',
),
)
else:
if not Config.IS_VIDEO:
await group_call.change_stream(
int(Config.CHAT),
AudioPiped(
link,
audio_parameters=Config.AUDIO_Q
),
)
else:
if pic:
await group_call.change_stream(
int(Config.CHAT),
AudioImagePiped(
link,
pic,
audio_parameters=Config.AUDIO_Q,
video_parameters=Config.VIDEO_Q,
),
)
else:
if not width \
or not height:
LOGGER.error("No Valid Video Found and hence removed from playlist.")
return await skip()
if Config.FPS and Config.BITRATE:
await group_call.change_stream(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=VideoParameters(
width,
height,
Config.FPS,
),
audio_parameters=AudioParameters(
Config.BITRATE,
),
),
)
else:
await group_call.change_stream(
int(Config.CHAT),
AudioVideoPiped(
link,
video_parameters=Config.VIDEO_Q,
audio_parameters=Config.AUDIO_Q,
),
)
except InvalidVideoProportion:
if not Config.FPS and not Config.BITRATE:
Config.FPS=20
Config.BITRATE=48000
await join_and_play(link, seek, pic, width, height)
Config.FPS=False
Config.BITRATE=False
return True
else:
LOGGER.error("Invalid video, skipped")
await skip()
return True
except Exception as e:
LOGGER.error(f"Error in joining call - {e}")
return False
async def seek_file(seektime):
play_start=int(float(Config.DUR.get('TIME')))
if not play_start:
return False, "Player not yet started"
else:
data=Config.DATA.get("FILE_DATA")
if not data:
return False, "No Streams for seeking"
played=int(float(time.time())) - int(float(play_start))
if data.get("dur", 0) == 0:
return False, "Seems like live stream is playing, which cannot be seeked."
total=int(float(data.get("dur", 0)))
trimend = total - played - int(seektime)
trimstart = played + int(seektime)
if trimstart > total:
return False, "Seeked duration exceeds maximum duration of file"
new_play_start=int(play_start) - int(seektime)
Config.DUR['TIME']=new_play_start
link, seek, pic, width, height = await chek_the_media(data.get("file"), seek={"start":trimstart, "end":trimend})
await join_call(link, seek, pic, width, height)
return True, None
async def leave_call():
try:
await group_call.leave_group_call(Config.CHAT)
except Exception as e:
LOGGER.error(f"Errors while leaving call {e}")
#Config.playlist.clear()
if Config.STREAM_LINK:
Config.STREAM_LINK=False
Config.CALL_STATUS=False
if Config.SCHEDULE_LIST:
sch=Config.SCHEDULE_LIST[0]
if (sch['date'] - datetime.now()).total_seconds() < 86400:
song=Config.SCHEDULED_STREAM.get(sch['job_id'])
if Config.IS_RECORDING:
k=scheduler.get_job(str(Config.CHAT), jobstore=None)
if k:
scheduler.remove_job(str(Config.CHAT), jobstore=None)
scheduler.add_job(start_record_stream, "date", id=str(Config.CHAT), run_date=sch['date'], max_instances=50, misfire_grace_time=None)
try:
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(Config.CHAT)),
random_id=random.randint(10000, 999999999),
schedule_date=int((sch['date']).timestamp()),
title=song['1']
)
)
Config.HAS_SCHEDULE=True
except ScheduleDateInvalid:
LOGGER.error("Unable to schedule VideoChat, since date is invalid")
except Exception as e:
LOGGER.error(f"Error in scheduling voicechat- {e}")
await sync_to_db()
async def restart():
try:
await group_call.leave_group_call(Config.CHAT)
await sleep(2)
except Exception as e:
LOGGER.error(e)
if not Config.playlist:
await start_stream()
return
LOGGER.info(f"- START PLAYING: {Config.playlist[0][1]}")
await sleep(2)
await play()
LOGGER.info("Restarting Playout")
if len(Config.playlist) <= 1:
return
await download(Config.playlist[1])
async def restart_playout():
if not Config.playlist:
await start_stream()
return
LOGGER.info(f"RESTART PLAYING: {Config.playlist[0][1]}")
data=Config.DATA.get('FILE_DATA')
if data:
link, seek, pic, width, height = await chek_the_media(data['file'], title=f"{Config.playlist[0][1]}")
if not link:
LOGGER.warning("Unsupported Link")
return
await sleep(1)
if Config.STREAM_LINK:
Config.STREAM_LINK=False
await join_call(link, seek, pic, width, height)
else:
await play()
if len(Config.playlist) <= 1:
return
await download(Config.playlist[1])
async def set_up_startup():
regex = r"^(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?"
match = re.match(regex, Config.STREAM_URL)
if match:
Config.YSTREAM=True
LOGGER.info("YouTube Stream is set as STARTUP STREAM")
elif Config.STREAM_URL.startswith("https://t.me/DumpPlaylist"):
try:
msg_id=Config.STREAM_URL.split("/", 4)[4]
Config.STREAM_URL=int(msg_id)
Config.YPLAY=True
LOGGER.info("YouTube Playlist is set as STARTUP STREAM")
except:
Config.STREAM_URL="http://j78dp346yq5r-hls-live.5centscdn.com/safari/live.stream/playlist.m3u8"
LOGGER.error("Unable to fetch youtube playlist, starting Safari TV")
pass
else:
Config.STREAM_URL=Config.STREAM_URL
Config.STREAM_SETUP=True
async def start_stream():
if not Config.STREAM_SETUP:
await set_up_startup()
if Config.YPLAY:
await y_play(Config.STREAM_URL)
return
if Config.YSTREAM:
link=await get_link(Config.STREAM_URL)
else:
link=Config.STREAM_URL
link, seek, pic, width, height = await chek_the_media(link, title="Startup Stream")
if not link:
LOGGER.warning("Unsupported link")
return False
#if Config.playlist:
#Config.playlist.clear()
await join_call(link, seek, pic, width, height)
async def stream_from_link(link):
link, seek, pic, width, height = await chek_the_media(link)
if not link:
LOGGER.error("Unable to obtain sufficient information from the given url")
return False, "Unable to obtain sufficient information from the given url"
#if Config.playlist:
#Config.playlist.clear()
Config.STREAM_LINK=link
await join_call(link, seek, pic, width, height)
return True, None
async def get_link(file):
def_ydl_opts = {'quiet': True, 'prefer_insecure': False, "geo-bypass": True}
with YoutubeDL(def_ydl_opts) as ydl:
try:
ydl_info = ydl.extract_info(file, download=False)
except Exception as e:
LOGGER.error(f"Errors occured while getting link from youtube video {e}")
await skip()
return False
url=None
for each in ydl_info['formats']:
if each['width'] == 640 \
and each['acodec'] != 'none' \
and each['vcodec'] != 'none':
url=each['url']
break #prefer 640x360
elif each['width'] \
and each['width'] <= 1280 \
and each['acodec'] != 'none' \
and each['vcodec'] != 'none':
url=each['url']
continue # any other format less than 1280
else:
continue
if url:
return url
else:
LOGGER.error(f"Errors occured while getting link from youtube video - No Video Formats Found")
await skip()
return False
async def download(song, msg=None):
if song[3] == "telegram":
if not Config.GET_FILE.get(song[5]):
try:
original_file = await bot.download_media(song[2], progress=progress_bar, file_name=f'./tgdownloads/', progress_args=(int((song[5].split("_"))[1]), time.time(), msg))
Config.GET_FILE[song[5]]=original_file
except Exception as e:
LOGGER.error(e)
Config.playlist.remove(song)
await clear_db_playlist(song=song)
if len(Config.playlist) <= 1:
return
await download(Config.playlist[1])
async def chek_the_media(link, seek=False, pic=False, title="Music"):
if not Config.IS_VIDEO:
width, height = None, None
is_audio_=False
try:
is_audio_ = is_audio(link)
except:
is_audio_ = False
LOGGER.error("Unable to get Audio properties within time.")
if not is_audio_:
Config.STREAM_LINK=False
await skip()
return None, None, None, None, None
else:
try:
width, height = get_height_and_width(link)
except:
width, height = None, None
LOGGER.error("Unable to get video properties within time.")
if not width or \
not height:
is_audio_=False
try:
is_audio_ = is_audio(link)
except:
is_audio_ = False
LOGGER.error("Unable to get Audio properties within time.")
if is_audio_:
pic_=await bot.get_messages("DumpPlaylist", 30)
photo = "./pic/photo"
if not os.path.exists(photo):
photo = await pic_.download(file_name=photo)
try:
dur_=get_duration(link)
except:
dur_='None'
pic = get_image(title, photo, dur_)
else:
Config.STREAM_LINK=False
await skip()
return None, None, None, None, None
try:
dur=get_duration(link)
except:
dur=0
Config.DATA['FILE_DATA']={"file":link, 'dur':dur}
return link, seek, pic, width, height
async def edit_title():
if not Config.playlist:
title = "Live Stream"
else:
title = Config.playlist[0][1]
try:
chat = await USER.resolve_peer(Config.CHAT)
full_chat=await USER.send(
GetFullChannel(
channel=InputChannel(
channel_id=chat.channel_id,
access_hash=chat.access_hash,
),
),
)
edit = EditGroupCallTitle(call=full_chat.full_chat.call, title=title)
await USER.send(edit)
except Exception as e:
LOGGER.error(f"Errors Occured while editing title - {e}")
pass
async def stop_recording():
job=str(Config.CHAT)
a = await bot.send(GetFullChannel(channel=(await bot.resolve_peer(Config.CHAT))))
if a.full_chat.call is None:
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
Config.IS_RECORDING=False
await sync_to_db()
return False, "No GroupCall Found"
try:
await USER.send(
ToggleGroupCallRecord(
call=(
await USER.send(
GetFullChannel(
channel=(
await USER.resolve_peer(
Config.CHAT
)
)
)
)
).full_chat.call,
start=False,
)
)
Config.IS_RECORDING=False
Config.LISTEN=True
await sync_to_db()
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
return True, "Succesfully Stoped Recording"
except Exception as e:
if 'GROUPCALL_NOT_MODIFIED' in str(e):
LOGGER.warning("Already No recording Exist")
Config.IS_RECORDING=False
await sync_to_db()
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
return False, "No recording was started"
else:
LOGGER.error(str(e))
Config.IS_RECORDING=False
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
await sync_to_db()
return False, str(e)
async def start_record_stream():
if Config.IS_RECORDING:
await stop_recording()
if Config.WAS_RECORDING:
Config.WAS_RECORDING=False
a = await bot.send(GetFullChannel(channel=(await bot.resolve_peer(Config.CHAT))))
job=str(Config.CHAT)
if a.full_chat.call is None:
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
return False, "No GroupCall Found"
try:
if not Config.PORTRAIT:
pt = False
else:
pt = True
if not Config.RECORDING_TITLE:
tt = None
else:
tt = Config.RECORDING_TITLE
if Config.IS_VIDEO_RECORD:
await USER.send(
ToggleGroupCallRecord(
call=(
await USER.send(
GetFullChannel(
channel=(
await USER.resolve_peer(
Config.CHAT
)
)
)
)
).full_chat.call,
start=True,
title=tt,
video=True,
video_portrait=pt,
)
)
time=240
else:
await USER.send(
ToggleGroupCallRecord(
call=(
await USER.send(
GetFullChannel(
channel=(
await USER.resolve_peer(
Config.CHAT
)
)
)
)
).full_chat.call,
start=True,
title=tt,
)
)
time=86400
Config.IS_RECORDING=True
k=scheduler.get_job(job_id=job, jobstore=None)
if k:
scheduler.remove_job(job, jobstore=None)
try:
scheduler.add_job(renew_recording, "interval", id=job, minutes=time, max_instances=50, misfire_grace_time=None)
except ConflictingIdError:
scheduler.remove_job(job, jobstore=None)
scheduler.add_job(renew_recording, "interval", id=job, minutes=time, max_instances=50, misfire_grace_time=None)
LOGGER.warning("This already scheduled, rescheduling")
await sync_to_db()
LOGGER.info("Recording Started")
return True, "Succesfully Started Recording"
except Exception as e:
if 'GROUPCALL_NOT_MODIFIED' in str(e):
LOGGER.warning("Already Recording.., stoping and restarting")
Config.IS_RECORDING=True
await stop_recording()
return await start_record_stream()
else: