-
Notifications
You must be signed in to change notification settings - Fork 0
/
UI.py
1497 lines (1301 loc) · 69 KB
/
UI.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
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
import csv
import os
import pickle
from tkinter import *
from tkinter import colorchooser
from tkinter.ttk import Separator
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
import PIL.ImageTk
import PIL.Image
import google_auth_oauthlib
import googleapiclient.discovery
import requests
import bs4
from functools import partial
from googleapiclient.http import MediaFileUpload
from pygame import mixer
from time import localtime, strptime, mktime, time
class ManagerWindow(Tk):
"""
Window used to control the livestream.
"""
def __init__(self):
Tk.__init__(self)
self.title("Stream Manager")
self.configure(bg='#4E4E4E')
self.MainFrame = SetupFrame(self, width=900, height=700, bg='#4E4E4E')
self.YtFrame = YoutubeFrame(self, width=900, height=200, bg='#4E4E4E')
self.StreamFrame = EditFrame(self, bg='#4E4E4E')
self.MainFrame.grid(row=0, column=0)
self.YtFrame.grid(row=1, column=0)
self.StreamFrame.grid(row=0, column=2, rowspan=2)
Separator(self, orient="vertical").grid(row=0, column=1, rowspan=2, sticky="ns", padx=4)
self.csv_links = []
self.current_csv = 0
self.afters = {"rotate": None, "free": None}
self.after_blocked = {"rotate": False, "free": False}
self.MatchWindow = None
def launch_match(self, nb_matches, url_list, empty_text=""):
"""
Method that displays the stream window if it is not already on, updates it otherwise. Also updates the EditFrame
:param nb_matches: int number of simultaneous matches to display (from 1 to 4)
:param url_list: list containing the urls to the specific matches
:param empty_text: text to display if no match is left
:return: None
"""
# if there is no MatchWindow, create one. Otherwise update the current one.
if not self.MatchWindow:
self.MatchWindow = MatchWindow(master=self, nb_matches=nb_matches, url_list=url_list, empty_text=empty_text)
self.StreamFrame.load_edit(nb_matches)
else:
self.MatchWindow.change_match_number(nb_matches, url_list, empty_text=empty_text)
self.StreamFrame.load_edit(nb_matches)
def move(self, tag, direction):
"""
Method used as a medium between EditFrame and MatchWindow for moving text parts of the stream.
:param tag: string, tag of the item in the canvas.
:param direction: tuple of 2 int indicating how to move the element on the 2D axes. Same numbers indicated font
size change
:return: None
"""
self.MatchWindow.move(tag, direction)
def define_user_comment(self, color="black", text=""):
"""
Method used as a medium between YoutubeFrame and MatchWindow to generate the Defined User Text.
:param color: string indicating the color of the text
:param text: text to dislay. Empty indicates the text has to be erased.
:return: None
"""
self.MatchWindow.define_user_comment(color, text)
def load_video(self, video_url):
"""
Method used as a medium between YoutubeFrame and MatchWindow to load the likes and views of the video.
:param video_url: url of the livestream
:return: None
"""
self.MatchWindow.load_video_stats(video_url)
def launch_playback(self, filename):
"""
Method used as a medium between YoutubeFrame and MatchWindow to play the music selected
:param filename:
:return: None
"""
self.MatchWindow.playback(filename)
def is_stream_on(self):
"""
Method to indicate if the stream window is created
:return: boolean indicating if the stream window is already created
"""
return not (self.MatchWindow is None)
def erase(self):
"""
Method to erase the reference to the MatchWindow
:return: None
"""
self.MatchWindow = None
def load_from_csv(self, launch=True):
"""
Method called to load the content of the file named schedule.csv
:param launch: boolean indicating whether one wants to call launch_match after running the method
:return: None
"""
for block in self.after_blocked.values():
if block:
self.after(500, self.load_from_csv)
return
for after in self.afters.values():
if after:
self.after_cancel(after)
error_urls = []
self.csv_links = []
with open("./ressources/schedule.csv", "r", encoding="utf8") as file:
reader = csv.reader(file, delimiter=",")
for row in reader:
match_page = requests.get(row[0])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
if soup.find("title").text != "Erreur 404":
if len(row) == 1:
row.append("2")
if not([row[0], 0, int(row[1])] in self.csv_links):
self.csv_links.append([row[0], 0, int(row[1])])
else:
error_urls.append(row[0])
if error_urls:
showerror("Erreur 404", f"Le(s) match(s) que vous cherchez, {error_urls}, " +
"n'existe(nt) pas sur matchendirect.")
if launch:
self.timer()
self.clean_list()
self.csv_match()
def load_to_csv(self, new_urls=None, empty=False):
"""
Method called to refresh the content of the csv file
:param new_urls: list of urls to add to the csv file
:param empty: boolean indicating if csv_links is intentionnally empty (False indicates that it has never been
loaded)
:return: None
"""
if not self.csv_links and not empty:
self.load_from_csv(False)
# if there are new urls, sort them in the timer and redo the schedule
if new_urls:
self.csv_links += new_urls
self.timer()
self.clean_list()
for block in self.after_blocked.values():
if block:
self.after(500, self.load_to_csv, new_urls, empty)
return
for after in self.afters.values():
if after:
self.after_cancel(after)
if self.is_stream_on():
self.waiter()
with open("ressources/schedule.csv", 'w', newline="") as f:
writer = csv.writer(f, delimiter=',')
for link in self.csv_links:
writer.writerow(link[0::2])
def csv_match(self):
"""
Method called to prepare to launch a MatchWindow following the schedule.
:return: None
"""
# print("Changement de matchs")
i = 0
url_list = []
while i < 4 and i < len(self.csv_links) and self.csv_links[i][1] == -1:
url_list.append(self.csv_links[i][0])
i += 1
self.current_csv = i
message = ""
if self.current_csv == 0 and self.csv_links:
cast_time = localtime(self.csv_links[0][1] * 60)
now = localtime()
if now.tm_mday != cast_time.tm_mday or now.tm_mon != cast_time.tm_mon or now.tm_year != cast_time.tm_year:
message = " le " + str(cast_time.tm_mday) + "/" + "{0:0=2d}".format(cast_time.tm_mon)
message += " à " + str(cast_time.tm_hour) + "h" + "{0:0=2d}".format(cast_time.tm_min) + "."
self.launch_match(i, url_list, message)
self.waiter()
def waiter(self):
"""
Method called to shedule future actions concerning the refresh of displayed matches.
:return: None
"""
now = int(time() // 60)
if self.current_csv < len(self.csv_links) and self.current_csv < 4:
if self.csv_links[self.current_csv][1] - now - 5 < 0:
self.rotate_matches()
else:
if not self.afters["rotate"]:
self.afters["rotate"] = self.after((self.csv_links[self.current_csv][1] - now - 5) * 60000,
self.rotate_matches)
if self.csv_links[self.current_csv][1] - now > 10:
self.afters["free"] = self.after(300000, self.free_matches)
else:
self.afters["free"] = self.after(300000, self.free_matches)
# only liberate the blockers when after calls to either free_matches or rotate_matches are scheduled
self.after_blocked["rotate"] = False
self.after_blocked["free"] = False
def rotate_matches(self):
"""
Method called when a new match begins.
:return: None
"""
# turn the blocker on to indicate that not cancellation can be made right away
self.after_blocked["rotate"] = True
self.afters["rotate"] = None
self.csv_links[self.current_csv][1] = -1
self.check_finished()
self.csv_links.sort(key=self.sortlinks_key)
self.clean_list()
self.csv_match()
def free_matches(self):
"""
Method called regularly to remove finished matches from the MatchWindow.
:return: None
"""
# turn the blocker on to indicate that not cancellation can be made right away
self.after_blocked["free"] = True
self.afters["free"] = None
old_list = self.csv_links.copy()
self.check_finished()
self.csv_links.sort(key=self.sortlinks_key)
self.clean_list()
if self.csv_links != old_list:
self.csv_match()
else:
self.waiter() # even if no modification is done to the stream, it is necessary to loop back for checks
def check_finished(self):
"""
Method that checks whether there are finished matches into the csv_links list.
:return: None
"""
for i in range(self.current_csv):
link = self.csv_links[i]
match_page = requests.get(link[0])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
minute_text = soup.find(class_="status").text
if minute_text in ["Match terminé", "Match annulé", "0"] or minute_text[:6] in [" (déla", "Report"]:
link[1] = -2
def timer(self):
"""
Method used to calculate when the matches of csv_links will start. Gives them the time status -1 if the match is
ongoing, -2 if it is finished/cancelled.
:return: None
"""
time_conv = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5, "juin": 6,
"juillet": 7, "août": 8, "septembre": 9, "octobre": 10, "novembre": 11, "décembre": 12}
now = int(time() // 60) # current time in minutes
for link in self.csv_links:
if not link[1]:
match_page = requests.get(link[0])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
minute_text = soup.find(class_="status").text
if minute_text.split(" ")[0] == "Coup":
start = soup.find("div", class_="info1").text.split("|")[0]
start = start.split(" ")[1:4] + [start.split(" ")[-2]]
start[1] = time_conv[start[1]]
cast_time = strptime(str(start), "['%d', %m, '%Y', '%Hh%M']")
cast_time = int(mktime(cast_time) // 60)
if cast_time - 5 < now:
link[1] = -1
else:
link[1] = cast_time
elif minute_text == " Mi-temps":
link[1] = -1 # match ongoing
elif minute_text in ["Match terminé", "Match annulé", "0"] or minute_text[:6] in [" (déla", "Report"]:
link[1] = -2
else:
link[1] = -1 # match ongoing
self.csv_links.sort(key=self.sortlinks_key)
def sortlinks_key(self, link):
"""
Method called when sorting the csv_links attribute list
:param link: element of the list to move
:return: int to use to sort (link[2] is always inferior to link[1] if link[1] is positive)
"""
if link[1] == -1:
return link[2]
else:
return link[1]
def clean_list(self):
"""
Method called to remove all finished/cancelled matches from the list of matches to display.
:return: None
"""
if self.csv_links:
while self.csv_links[0][1] == -2:
self.csv_links.pop(0)
if not self.csv_links:
self.load_to_csv(empty=True)
return
self.load_to_csv()
def destroy(self):
"""
Method handling some problems happening when destroying the Stream Manager before the MatchWindow.
:return: None
"""
if self.MatchWindow:
self.MatchWindow.destroy()
Tk.destroy(self)
class MatchWindow(Toplevel):
"""
Window used for the youtube livestream.
"""
def __init__(self, master: ManagerWindow, nb_matches: int, url_list=None, empty_text=""):
Toplevel.__init__(self, master)
self.youtube = self.authenticate()
self.master = master
self.title("Match Stream")
self.match_urls = []
self.nb_matches = -1
self.stop_gif = False
self.afters = {"scores": None, "timer": None, "commentaries": None, "gif": None}
self.after_blocked = {"scores": False, "timer": False, "commentaries": False, "gif": False}
self.videos_infos = {"video_id": None, "title": "", "description": [], "tags": [],
"thumbnail": MediaFileUpload("./ressources/images/thumbnail_empty.png")}
self.base_description = ["", "Subscribe! /Abonne-toi!",
"https://www.youtube.com/channel/UCvahkUIQv3F1eYh7BV0CmbQ?sub_confirmation=1", ""]
self.base_tags = ["foot", "match foot", "foot en direct", "Actu2Foot", "uefa", "match en direct", "direct",
"football", "buts", "goals", "actu2foot", "actu foot", "score", "score direct", "match",
"multiplex", "live", "score en direct", "stream", "communauté foot"]
self.MatchCanvas = Canvas(self, width=1536, height=864)
self.MatchCanvas.grid(row=0, column=0)
self.displayed_bg = None
self.displayed_logo = None
self.displayed_black = None
self.displayed_icons = []
self.displayed_teamlogos = []
self.displayed_championnat = None
self.load_bases()
self.load_channel_stats()
self.change_match_number(nb_matches, url_list, empty_text)
def update_videos(self):
"""
Method called to trigger the online update of all video info.
:return: None
"""
# print(self.videos_infos)
# get all the information related to the livestream
videos_list_response = self.youtube.videos().list(id=self.videos_infos["video_id"], part="snippet").execute()
videos_list_snippet = videos_list_response["items"][0]["snippet"]
# update only the relevant parts
videos_list_snippet["title"] = self.videos_infos["title"]
videos_list_snippet["description"] = "\n".join(self.videos_infos["description"])
videos_list_snippet["tags"] = list(set(self.videos_infos["tags"]))
# to avoid any bugs, push the whole modified thing
self.youtube.videos() \
.update(part="snippet", body=dict(snippet=videos_list_snippet, id=self.videos_infos["video_id"])).execute()
self.youtube.thumbnails().set(videoId=self.videos_infos["video_id"],
media_body=self.videos_infos["thumbnail"]).execute()
def update_video_info(self, titre="", description=None, tags=None):
"""
Method called to update the informations of the livestream
:param titre: new title for the livestream
:param description: description to set below the video
:param tags: tags to put into the video
:return: None
"""
self.videos_infos["title"] = titre
if description:
self.videos_infos["description"] = description
if tags:
self.videos_infos["tags"] = tags
def load_bases(self):
"""
Method to load the very bases of the Canvas (called only at initiation).
:return: None
"""
# Main background
pil_image = PIL.Image.open("./ressources/images/fond_direct.jpg")
pil_image2 = pil_image.resize((1536, 864))
pil_image.close()
self.displayed_bg = PIL.ImageTk.PhotoImage(pil_image2)
self.MatchCanvas.create_image(770, 434, image=self.displayed_bg, tag="Background")
pil_image2.close() # Close to make sure memory is free
# Logo of the channel
pil_image = PIL.Image.open("./ressources/images/logo.png")
pil_image2 = pil_image.resize((100, 100))
pil_image.close()
self.displayed_logo = PIL.ImageTk.PhotoImage(pil_image2)
self.MatchCanvas.create_image(70, 70, image=self.displayed_logo, tag="Logo")
pil_image2.close()
# load all the icons related to youtube statistics
iconlist = ["./ressources/images/youtube.png", "./ressources/images/views.png", "./ressources/images/likes.png"]
for i in range(3):
self.MatchCanvas.create_rectangle(1306, 20 + 70 * i, 1486, 70 + 70 * i, fill="white", outline="white")
pil_image2.close()
pil_image = PIL.Image.open(iconlist[i])
pil_image2 = pil_image.resize((int((pil_image.size[0] / pil_image.size[1]) * 40), 40))
pil_image.close()
self.displayed_icons.append(PIL.ImageTk.PhotoImage(pil_image2))
self.MatchCanvas.create_image(1341, 45 + 70 * i, image=self.displayed_icons[i], tag="Icon" + str(i))
pil_image2.close()
def load_black(self):
"""
Method called to draw the black background
:return: None
"""
pil_image = PIL.Image.open("./ressources/images/affiche_vierge.png")
# different sizes depending on the number of matches
if self.nb_matches == 1:
pil_image2 = pil_image.resize((1150, 234))
elif self.nb_matches == 2:
pil_image2 = pil_image.resize((875, 195))
else:
pil_image2 = pil_image.resize((700, 156))
pil_image.close()
if pil_image2:
self.displayed_black = PIL.ImageTk.PhotoImage(pil_image2)
# placement is different according to the number of matches
for i in range(self.nb_matches):
if self.nb_matches == 1:
self.MatchCanvas.create_image(770, 500, image=self.displayed_black, tag="Black" + str(i))
elif self.nb_matches == 2:
self.MatchCanvas.create_image(770, 300 * i + 320, image=self.displayed_black, tag="Black" + str(i))
elif self.nb_matches == 3:
self.MatchCanvas.create_image(770 - 375 * (i == 1) + 375 * (i == 2), 265 * (i > 0) + 300,
image=self.displayed_black, tag="Black" + str(i))
elif self.nb_matches == 4:
self.MatchCanvas.create_image(770 - 375 * (i % 2 == 0) + 375 * (i % 2 == 1), 265 * (i > 1) + 300,
image=self.displayed_black, tag="Black" + str(i))
def load_match_stats(self):
"""
Method called to set all the places where things are displayed on the stream. Used every time the number of
matches is different.
:return: None
"""
for j in range(self.nb_matches):
# sizes and coordinates depend on the number of matches, and are set through experimentation
if self.nb_matches == 1:
for i in range(2):
self.MatchCanvas.create_text(195 * (1 - i) + (1 - 2 * i) * 300 + 1347 * i, 500, font=["Ubuntu", 30],
fill="white", justify="center", tag="TeamName" + str(i))
for i in range(2):
self.MatchCanvas.create_text(195 * (1 - i) + (1 - 2 * i) * 493 + 1347 * i, 535, font=["Ubuntu", 40],
fill="white", justify="center", tag="score" + str(i))
self.MatchCanvas.create_rectangle(221, 625, 1321, 720, tag="bg" + str(j), width=0)
self.MatchCanvas.create_text(771, 672, font=["Arial", 12],
fill="black", tag="commentaire" + str(j), width=1100)
for i in range(2):
self.MatchCanvas.create_image(195 * (1 - i) + (1 - 2 * i) * 100 + 1347 * i, 500, tag="Teamlogo" +
str(2 * j + i))
self.MatchCanvas.create_text(771, 448, justify="center", tag="timer" + str(j))
self.MatchCanvas.create_oval(710, 438, 730, 458, fill="green", tag="gif" + str(j))
elif self.nb_matches == 2:
for i in range(2):
self.MatchCanvas.create_text(333 * (1 - i) + (1 - 2 * i) * 240 + 1217 * i, 300 * j + 320, # -30
font=["Ubuntu", 22],
fill="white", justify="center", tag="TeamName" + str(2 * j + i))
for i in range(2):
self.MatchCanvas.create_text(325 * (1 - i) + (1 - 2 * i) * 383 + 1217 * i, 300 * j + 350,
font=["Ubuntu", 40],
fill="white", justify="center", tag="score" + str(2 * j + i))
self.MatchCanvas.create_rectangle(360, 420 + 300 * j, 1180, 506 + 300 * j, width=0, tag="bg" + str(j))
self.MatchCanvas.create_text(771, 463 + 300 * j,
text="", font=["Arial", 10],
fill="black", tag="commentaire" + str(j), width=800)
for i in range(2):
self.MatchCanvas.create_image(333 * (1 - i) + (1 - 2 * i) * 80 + 1207 * i, 300 * j + 320,
tag="Teamlogo" + str(2 * j + i))
self.MatchCanvas.create_text(771, 277 + 300 * j, justify="center", tag="timer" + str(j))
self.MatchCanvas.create_oval(715, 267 + 300 * j, 735, 287 + 300 * j, fill="green", tag="gif" + str(j))
elif self.nb_matches == 3:
for i in range(2):
self.MatchCanvas.create_text((420 - 375 * (j == 1) + 375 * (j == 2)) * (1 - i) + (1 - 2 * i) * 200 +
(1120 - 375 * (j == 1) + 375 * (j == 2)) * i, 265 * (j >= 1) + 300,
font=["Ubuntu", 20],
fill="white", justify="center", tag="TeamName" + str(2 * j + i))
for i in range(2):
self.MatchCanvas.create_text((420 - 375 * (j == 1) + 375 * (j == 2)) * (1 - i) + (1 - 2 * i) * 300 +
(1122 - 375 * (j == 1) + 375 * (j == 2)) * i, 265 * (j >= 1) + 322,
font=["Ubuntu", 35],
fill="white", justify="center", tag="score" + str(2 * j + i))
self.MatchCanvas.create_rectangle(50 + 375 * (j == 0) + 750 * (j == 2), 387 + 265 * (j >= 1),
740 + 375 * (j == 0) + 750 * (j == 2), 469 + 265 * (j >= 1),
width=0, tag="bg" + str(j))
self.MatchCanvas.create_text((770 - 375 * (j == 1) + 375 * (j == 2)), 265 * (j >= 1) + 425,
text="", font=["Arial", 8],
fill="black", tag="commentaire" + str(j), width=680)
for i in range(2):
self.MatchCanvas.create_image((420 - 375 * (j == 1) + 375 * (j == 2)) * (1 - i) + (1 - 2 * i) * 70 +
(1120 - 375 * (j == 1) + 375 * (j == 2)) * i, 265 * (j >= 1) + 300,
tag="Teamlogo" + str(2 * j + i))
self.MatchCanvas.create_text(771 - 375 * (j == 1) + 375 * (j == 2), 263 + 265 * (j >= 1),
justify="center", tag="timer" + str(j))
self.MatchCanvas.create_oval(710 - 375 * (j == 1) + 375 * (j == 2), 253 + 265 * (j >= 1),
730 - 375 * (j == 1) + 375 * (j == 2), 273 + 265 * (j >= 1),
fill="green", tag="gif" + str(j))
elif self.nb_matches == 4:
for i in range(2):
self.MatchCanvas.create_text(
(420 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * (1 - i) + (1 - 2 * i) *
195 + (1120 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * i, 265 * (j >= 2) + 300,
font=["Ubuntu", 20],
fill="white", justify="center", tag="TeamName" + str(2 * j + i))
for i in range(2):
self.MatchCanvas.create_text(
(420 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * (1 - i) + (1 - 2 * i) *
300 + (1122 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * i, 265 * (j >= 2) + 322, # -50, +50
font=["Ubuntu", 35],
fill="white", justify="center", tag="score" + str(2 * j + i))
self.MatchCanvas.create_rectangle(50 + 750 * (j % 2 == 1), 385 + 265 * (j >= 2), # -45
740 + 750 * (j % 2 == 1), 469 + 265 * (j >= 2), # -10
width=0, tag="bg" + str(j))
self.MatchCanvas.create_text((770 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)),
265 * (j >= 2) + 425, # -30
text="", font=["Arial", 8],
fill="black", tag="commentaire" + str(j), width=680)
for i in range(2):
self.MatchCanvas.create_image(
(420 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * (1 - i) + (1 - 2 * i) *
70 + (1120 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1)) * i, 265 * (j >= 2) + 300,
tag="Teamlogo" + str(2 * j + i))
self.MatchCanvas.create_text(771 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1), 263 + 265 * (j >= 2),
justify="center", tag="timer" + str(j))
self.MatchCanvas.create_oval(720 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1), 253 + 265 * (j >= 2),
740 - 375 * (j % 2 == 0) + 375 * (j % 2 == 1), 273 + 265 * (j >= 2),
fill="green", tag="gif" + str(j))
# once places are set, load the actual data
self.load_match_teams()
self.reload_match_score()
self.reload_match_commentaries()
self.reload_match_timer()
def change_matches(self, new_urls: list):
"""
Method called when matches rotate without changing their numbers
:param new_urls: list of urls with the new matches to display
:return: None
"""
self.match_urls = new_urls
self.load_match_teams()
self.reload_match_score()
self.reload_match_commentaries()
self.reload_match_timer()
def change_match_number(self, new_number: int, new_urls: list, empty_text=""):
"""
Method called when rotating matches
:param new_number: new number of matches to be displayed
:param new_urls: list of urls of the new matches to display
:param empty_text: text to display
:return: None
"""
# tell the gif process to stop
self.stop_gif = True
# make sure all after methods are currently waiting
for value in self.after_blocked.values():
if value:
self.after(500, self.change_match_number, new_number, new_urls)
return
self.stop_gif = False
# cancel all sheduled methods
for after_id in self.afters.values():
if after_id:
self.after_cancel(after_id)
# erase the championship logo and the message for empty screen
self.MatchCanvas.delete("Empty")
self.MatchCanvas.delete("champ")
# if there is a different number of matches to be displayed, erase all elements not related to the video itself
if new_number != self.nb_matches:
for j in range(self.nb_matches):
self.MatchCanvas.delete("bg" + str(j))
self.MatchCanvas.delete("commentaire" + str(j))
self.MatchCanvas.delete("timer" + str(j))
self.MatchCanvas.delete("Black" + str(j))
self.MatchCanvas.delete("gif" + str(j))
for i in range(2):
self.MatchCanvas.delete("Teamlogo" + str(2 * j + i))
self.MatchCanvas.delete("TeamName" + str(2 * j + i))
self.MatchCanvas.delete("score" + str(2 * j + i))
self.nb_matches = new_number
self.match_urls = new_urls
# if there is at least a match to display, call the regular setting functions
if self.nb_matches:
self.load_black()
self.load_match_stats()
self.play_gif()
# if there is no match to display anymore, use the specific method
else:
self.load_empty(empty_text)
# if only the urls are different, the process is lighter
elif self.match_urls != new_urls:
self.change_matches(new_urls)
self.play_gif()
# if there was no match, and there is still none, recreate an empty text with possibly new content
elif new_number == 0:
self.load_empty(empty_text)
def load_empty(self, empty_text=""):
"""
Method called when there is no match to display. Displays a specific text instead.
:param empty_text: sentence to display
:return: None
"""
# if there is no text, it means there is no match scheduled anymore, display the specific message
if not empty_text:
self.MatchCanvas.create_rectangle(350, 400, 1190, 560, fill="white", tag="Empty", width=0)
self.MatchCanvas.create_text(770, 480, width=800, text="C'est fini pour aujourd'hui.\n" +
"Il n'y a plus de match prévus pour ce stream.\n" +
"A plus la team!",
justify="center", tag="Empty", font=["Ubuntu", 30])
self.update_video_info("Actu2Foot revient bientôt", self.base_description, self.base_tags)
# change the thumbnail to empty stream thumbnail
self.videos_infos["thumbnail"] = MediaFileUpload("./ressources/images/thumbnail_empty.png")
# if the livestream was linked to the window, update its information
if self.videos_infos["video_id"]:
self.update_videos()
else:
self.MatchCanvas.create_rectangle(350, 450, 1190, 510, fill="white", tag="Empty", width=0)
self.MatchCanvas.create_text(770, 480, text="Prochain match prévu" + empty_text, tag="Empty",
font=["Ubuntu", 30])
self.update_video_info("[Score en direct] Prochain match prévu" + empty_text, self.base_description,
self.base_tags)
# if the livestream was linked to the window, update its information
if self.videos_infos["video_id"]:
self.update_videos()
def load_match_teams(self):
"""
Method called to load all the information about the teams playing the match.
:return: None
"""
self.displayed_teamlogos = []
self.videos_infos["title"] = "[Score en direct]"
self.displayed_championnat = None
first_url_logo_champ = ""
dict_head_description = {}
hashtag_description = []
list_tags = []
for j in range(self.nb_matches):
# if the number of matches does not fit the number of urls, return (should not happen anyway)
if j >= len(self.match_urls):
return
# initialise match title, description and hashtags
match_title = " "
match_head_description = ""
match_page = requests.get(self.match_urls[j])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
# add championship hashtags
championnat = soup.find("div", class_="info1").text.split("|")[1][1:-1]
if championnat not in dict_head_description:
dict_head_description[championnat] = [""]
hashtag = "#" + championnat.lower().replace(" ", "").replace("-", "").replace(",", "")
# add team hashtags
if not (hashtag in hashtag_description):
hashtag_description.append(hashtag)
tag = championnat.lower()
if not (tag in list_tags):
list_tags.append(tag)
# display team names on the MatchWindow
i = 0
for div in soup.find_all("div", class_="col-xs-4 text-center team"):
self.MatchCanvas.itemconfigure("TeamName" + str(2 * j + i), text=div.text[1:-1].replace(" ", "\n"))
match_title += div.text[1:-1]
match_head_description += div.text[1:-1]
hashtag = "#" + div.text[1:-1].lower().replace(" ", "").replace("-", "")
hashtag_description.append(hashtag)
tag = div.text[1:-1].lower()
list_tags.append(tag)
if i == 0:
match_title += " - "
match_head_description += " - "
i += 1
# configure video description
match_head_description += " | [Score en direct]"
dict_head_description[championnat].append(match_head_description)
# configure match title
if j != (self.nb_matches - 1):
match_title += " |"
if len(self.videos_infos["title"] + match_title) <= 100:
self.videos_infos["title"] += match_title
elif self.videos_infos["title"][0:18] == "[Score en direct]" and \
len(self.videos_infos["title"][18:] + match_title) <= 100:
self.videos_infos["title"] = self.videos_infos["title"][18:] + match_title
# display team logos on the MatchWindow
i = 0
for div in soup.find_all("div", class_="col-xs-4 text-center"):
full_url = "https://www.matchendirect.fr" + div.find("img")["src"].replace("/96/", "/128/")
pil_image = PIL.Image.open(requests.get(full_url, stream=True).raw)
self.displayed_teamlogos.append(PIL.ImageTk.PhotoImage(pil_image))
self.MatchCanvas.itemconfigure("Teamlogo" + str(2 * j + i), image=self.displayed_teamlogos[2 * j + i])
i += 1
# check if all the matchs are from the same championship
url_logo_champ = "https://www.matchendirect.fr" + \
soup.find("div", class_="col-xs-4 text-center imgfootball").find("img")["src"]
if j == 0:
first_url_logo_champ = url_logo_champ
pil_image = PIL.Image.open(requests.get(url_logo_champ, stream=True).raw)
logo = PIL.ImageTk.PhotoImage(pil_image)
self.displayed_championnat = logo
else:
if first_url_logo_champ != url_logo_champ:
self.displayed_championnat = None
self.autoadjust_fontsize()
self.display_championnat()
# finish to configure video title, description and hashtags
if self.videos_infos["title"][-1] == "|":
self.videos_infos["title"] = self.videos_infos["title"][:-1]
head_description = []
for key in dict_head_description:
head_description.append(key)
for match in dict_head_description[key]:
head_description.append(match)
head_description.append("")
self.videos_infos["description"] = head_description + self.base_description + hashtag_description
self.videos_infos["tags"] = self.base_tags + list_tags
# generate the thumbnail with the new teams and set it in video_infos
self.create_thumbnail()
self.videos_infos["thumbnail"] = MediaFileUpload("./ressources/images/thumbnail.png")
# update video infos
if self.videos_infos["video_id"]:
self.update_videos()
def create_thumbnail(self):
"""
Method that creates the new thumbnail to set for the livestream.
:return: None
"""
image = PIL.Image.new(mode='RGBA', size=(700, 350), color=(0, 0, 0, 0))
background = PIL.Image.open("./ressources/images/fond_thumbnail.jpg").resize((700, 350), PIL.Image.ANTIALIAS)
image.paste(background, (0, 0))
background.close()
score = PIL.Image.open("./ressources/images/score_en_direct.png").resize((494, 118), PIL.Image.ANTIALIAS)
image.paste(score, (103, 10), score)
score.close()
if self.nb_matches >= 2:
separator = PIL.Image.open("./ressources/images/horizontal_separator.png").resize((500, 5),
PIL.Image.ANTIALIAS)
image.paste(separator, (100, 230))
separator.close()
if self.nb_matches == 4:
separator = PIL.Image.open("./ressources/images/vertical_separator.png").resize((5, 200),
PIL.Image.ANTIALIAS)
image.paste(separator, (343, 140))
separator.close()
if self.nb_matches == 1:
vs = PIL.Image.open("./ressources/images/vs.png").resize((120, 118), PIL.Image.ANTIALIAS)
else:
vs = PIL.Image.open("./ressources/images/vs.png").resize((80, 78), PIL.Image.ANTIALIAS)
for j in range(self.nb_matches):
for i in range(2):
if self.nb_matches == 1:
logo_image = PIL.ImageTk.getimage(self.displayed_teamlogos[2*j+i])
else:
logo_image = PIL.ImageTk.getimage(self.displayed_teamlogos[2 * j + i]).resize((80, 80),
PIL.Image.ANTIALIAS)
if self.nb_matches == 1:
x = -64+164*(1-2*i)+700*i
y = 180
elif self.nb_matches == 2:
x = -40 + 200 * (1 - 2 * i) + 700 * i
y = 130 + j*120
elif self.nb_matches == 3:
x = -40 + 250 * (1 - 2 * i) + 700 * i - 175*(j == 1) + 175*(j == 2)
y = 130 + (j >= 1) * 120
else:
x = -40 + 250 * (1 - 2 * i) + 700 * i - 175*(j % 2 == 0) + 175*(j % 2 == 1)
y = 130 + (j >= 2) * 120
image.paste(logo_image, (x, y), logo_image)
logo_image.close()
if self.nb_matches == 1:
x = 290
y = 184
elif self.nb_matches == 2:
x = 310
y = 131 + j*120
elif self.nb_matches == 3:
x = 310 - 175*(j == 1) + 175*(j == 2)
y = 131 + (j >= 1)*120
else:
x = 310 - 175*(j % 2 == 0) + 175*(j % 2 == 1)
y = 131 + (j >= 2) * 120
image.paste(vs, (x, y), vs)
image.save("./ressources/images/thumbnail.png", "PNG")
vs.close()
image.close()
def autoadjust_fontsize(self):
"""
Method called to adjust the font size of the names of the teams.
:return: None
"""
size_limits = [(13, 18), (12, 18), (9, 15), (9, 15)]
adjust_sizes = [[-2, -5, -8, -11, -12, -14], [-1, -3, -5, -7, -8, -9, -9],
[-1, -2, -4, -5, -7, -8, -10], [-1, -2, -4, -5, -7, -8, -10]]
for j in range(self.nb_matches):
for i in range(2):
# find the longest part of the name of the team and keep its length
team_name = self.MatchCanvas.itemcget("TeamName"+str(2*j+i), "text")
team_name = team_name.split("\n")
maxsize = len(max(team_name, key=lambda x: len(x)))
# if the maximum size is in the range, associate the right reduction
if size_limits[self.nb_matches-1][1] >= maxsize >= size_limits[self.nb_matches-1][0]:
current_font = self.MatchCanvas.itemcget("TeamName"+str(2*j+i), "font").split(" ")
current_font[1] = int(current_font[1]) + \
adjust_sizes[self.nb_matches-1][maxsize-size_limits[self.nb_matches-1][0]]
self.MatchCanvas.itemconfigure("TeamName"+str(2*j+i), font=current_font)
# if the maximum size is too important for the tests, stick to the maximal reduction
elif size_limits[self.nb_matches-1][1] < maxsize:
current_font = self.MatchCanvas.itemcget("TeamName" + str(2 * j + i), "font").split(" ")
current_font[1] = int(current_font[1]) + \
adjust_sizes[self.nb_matches - 1][-1]
self.MatchCanvas.itemconfigure("TeamName" + str(2 * j + i), font=current_font)
def display_championnat(self):
"""
Method to display the championship of the matches, if all matches belong to the same championship
:return: None
"""
if self.displayed_championnat:
self.MatchCanvas.create_image(770, 120, image=self.displayed_championnat, tag="champ")
def define_user_comment(self, color="black", text=""):
"""
Method called when it is needed to write a specific message on the stream
:param color: string of a color
:param text: string containing hte message to display. Empty means message will be erased
:return: None
"""
if text:
self.MatchCanvas.create_rectangle(370, 820, 1170, 860, fill="white", width=0, tag="white_defined_bg")
self.MatchCanvas.create_text(770, 840, text=text, fill=color, font=["Ubuntu", 18], tag="defined_text")
else:
self.MatchCanvas.delete("white_defined_bg")
self.MatchCanvas.delete("defined_text")
def reload_match_score(self):
"""
Method called every ten seconds to reload the scores of the matches
:return: None
"""
self.after_blocked["scores"] = True
for j in range(self.nb_matches):
match_page = requests.get(self.match_urls[j])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
i = 0
for score in soup.find_all(class_="score"):
self.MatchCanvas.itemconfigure("score" + str(2 * j + i), text=score.text)
i += 1
# print("Scores mis à jour")
self.afters["scores"] = self.after(10000, self.reload_match_score)
self.after_blocked["scores"] = False
def reload_match_commentaries(self):
"""
Method called every minute to reload the commentaries below the matches
:return: None
"""
self.after_blocked["commentaries"] = True
for j in range(self.nb_matches):
match_page = requests.get(self.match_urls[j])
soup = bs4.BeautifulSoup(match_page.text, "html.parser")
a = soup.find(class_="bg-primary")
if a is not None:
if not a.text:
a = "0'"
else:
a = a.text + "'"
b = soup.find(id="commentaire").find_all("td")[2].text
self.MatchCanvas.itemconfigure("bg" + str(j), fill="#E5E4E1")
self.MatchCanvas.itemconfigure("commentaire" + str(j), text=a + " : " + b)
# print("Commentaires mis à jour")
self.afters["commentaries"] = self.after(60000, self.reload_match_commentaries)
self.after_blocked["commentaries"] = False
def reload_match_timer(self):
"""
Method called every minute to actualize the timer.
:return: None