-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
984 lines (745 loc) · 29.4 KB
/
app.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
"""Main app file (GUI component).
"""
# Imports
import FileDialog
import json
import threading
import socket
import re
import time
import datetime
import base64
import numpy as np
import cv2
from kivy.app import App
from kivy.clock import Clock, mainthread
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.uix.camera import Camera
from kivy.uix.image import Image
from kivy.graphics.texture import Texture
from kivy.utils import rgba
import design
from peer import PypePeer
from configparser import get_option
class ErrorLabel(Label):
"""Red label for displaying error messages (see .kv file for structure).
"""
pass
class EntryScreen(Screen):
"""Entry screen class (see .kv file for structure).
Attributes:
bottom_lbl (Label): Bottom label to be added
(when username is invalid or taken).
USERNAME_REGEX (str): Regex of valid username format: Non-empty, doesn't
start with spaces and is no longer than 14 characters.
"""
USERNAME_REGEX = r'[^\s].{0,13}$'
def __init__(self):
"""Constructor method,
"""
Screen.__init__(self, name='entry_screen')
def on_join_btn_press(self):
"""Sends join request to server.
"""
app = App.get_running_app()
username = self.ids.username_input.text
# Checking is username is valid
try:
username.decode('ascii')
if not re.match(EntryScreen.USERNAME_REGEX, username):
err_msg = 'Invalid username'
self.add_bottom_lbl(err_msg)
else:
# Notifying communication component
app.send_gui_evt({
'type': 'join',
'subtype': 'request',
'name': username,
})
except UnicodeEncodeError:
err_msg = 'Invalid username'
self.add_bottom_lbl(err_msg)
@mainthread
def add_bottom_lbl(self, msg):
"""Adds bottom label to entry screen.
Args:
msg (str): The message to be shown in the label.
"""
# Checking if there already exists a bottom label
if hasattr(self, 'bottom_lbl'):
self.bottom_lbl.text = msg
else:
self.bottom_lbl = ErrorLabel(text=msg, size_hint_y=0.4)
self.ids.main_layout.add_widget(self.bottom_lbl)
class MainScreen(Screen):
"""Main screen class (see .kv file for structure).
Attributes:
call_layout (CallLayout): Layout of all active calls.
footer_widget (Widget): Widget that's added to the bottom of the screen
when necessary.
remove_widget_evt (ClockEvent): Event used for removing widgets.
session_footer (SessionFooter): Footer widget displayed during called.
session_layout (SessionLayout): Layout used for active call.
user_layout (UserLayout): Layout of all online users.
username (str): Username.
"""
def __init__(self, **kwargs):
"""Constructor method
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.username = kwargs['name']
self.user_layout = UserLayout(kwargs['user_info_lst'])
self.call_layout = CallLayout(kwargs['call_info_lst'])
Screen.__init__(self, name='main_screen')
for layout in [self.user_layout, self.call_layout]:
self.ids.interface_layout.add_widget(layout)
@mainthread
def add_footer_widget(self, **kwargs):
"""Adds footer widget to main screen.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# Checking if there already exists a footer widget
if hasattr(self, 'footer_widget'):
self.ids.footer_layout.remove_widget(self.footer_widget)
if hasattr(self, 'remove_widget_evt'):
self.remove_widget_evt.cancel()
del self.remove_widget_evt
# Pending call
if kwargs['mode'] == 'pending_call':
self.footer_widget = PendingCallFooter(kwargs['callee'])
# User not available
elif kwargs['mode'] == 'user_not_available':
self.footer_widget = ErrorLabel(text='User is in call')
# Call
elif kwargs['mode'] == 'call':
self.footer_widget = CallFooter(kwargs['caller'])
# Rejected call
elif kwargs['mode'] == 'rejected_call':
self.footer_widget = ErrorLabel(
text='Call has been rejected by user')
# Invalid text
elif kwargs['mode'] == 'invalid_text':
self.footer_widget = ErrorLabel(text='Invalid text')
# Scheduling widget removal if necessary
if kwargs['mode'] in ['user_not_available', 'rejected_call', 'invalid_text']:
self.remove_widget_evt = Clock.schedule_once(
lambda dt: self.remove_footer_widget(), 3)
self.ids.footer_layout.add_widget(self.footer_widget)
@mainthread
def remove_footer_widget(self):
"""Removes footer widget.
"""
# Deleting event attribute if widget removal was scheduled
if hasattr(self, 'remove_widget_evt'):
del self.remove_widget_evt
self.ids.footer_layout.remove_widget(self.footer_widget)
del self.footer_widget
@mainthread
def switch_to_session_layout(self, **kwargs):
"""Removes call layout and shows session layout during active call.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# Removing footer widget if necessary
if hasattr(self, 'footer_widget'):
self.remove_footer_widget()
self.ids.interface_layout.remove_widget(self.call_layout)
self.session_layout = SessionLayout(**kwargs)
self.ids.interface_layout.add_widget(self.session_layout)
self.session_footer = SessionFooter()
self.ids.footer_layout.add_widget(self.session_footer)
@mainthread
def switch_to_call_layout(self, **kwargs):
"""Removes session layout and shows call layout after call end.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.ids.interface_layout.remove_widget(self.session_layout)
del self.session_layout
self.ids.footer_layout.remove_widget(self.session_footer)
del self.session_footer
self.ids.interface_layout.add_widget(self.call_layout)
class UserSlot(BoxLayout):
"""Slot representing an online user (see .kv file for structure).
Attributes:
color (str): Slot color (for design purposes only.)
status (str): Whether the user is in call (available/in call).
username (str): Username.
"""
def __init__(self, **kwargs):
"""Constructor method.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.username = kwargs['name']
self.status = kwargs['status']
self.color = design.get_random_color()
BoxLayout.__init__(self)
def on_call_btn_press(self):
"""Sends call request with the following user to server.
"""
app = App.get_running_app()
app.send_gui_evt({
'type': 'call',
'subtype': 'request',
'callee': self.username,
'group': False
})
def switch_status(self):
"""Switches user status.
"""
if self.status == 'available':
self.status = 'in call'
self.ids.status_lbl.text = 'in call'
else:
self.status = 'available'
self.ids.status_lbl.text = 'available'
class CallSlot(BoxLayout):
"""Slot representing an active call (see .kv file for structure).
Attributes:
color (str): Slot color (for design purposes only).
master (str): Username of call master.
user_lst (list): List of all users in call.
"""
def __init__(self, **kwargs):
"""Constructor method.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.user_lst = kwargs['user_lst']
self.master = kwargs['master']
self.color = design.get_random_color()
BoxLayout.__init__(self)
self.ids.user_lbl.text = ', '.join(kwargs['user_lst'])
def update(self, **kwargs):
"""Updates call slot on user join/leave.
Args:
**kwargs: Keyword arguments supplied in dictioanry form.
"""
if kwargs['mode'] == 'join':
self.user_lst.append(kwargs['name'])
else:
self.user_lst.remove(kwargs['name'])
if 'new_master' in kwargs:
self.master = kwargs['new_master']
self.ids.user_lbl.text = ', '.join(self.user_lst)
def on_join_btn_press(self):
"""Sends call request with call master to server.
"""
app = App.get_running_app()
app.send_gui_evt({
'type': 'call',
'subtype': 'request',
'callee': self.master,
'group': True
})
class UserLayout(BoxLayout):
"""Class representing the user layout (see .kv file for structure).
Attributes:
user_slot_dct (dict): Dictionary mapping online users to their slots.
"""
def __init__(self, user_info_lst):
"""Constructor method.
Args:
user_info_lst (list): List of online users and their status.
"""
self.user_slot_dct = {}
BoxLayout.__init__(self)
for user in user_info_lst:
self.user_slot_dct[user['name']] = UserSlot(**user)
# Adding all slots to layout
self.ids.user_slot_layout.add_widget(
self.user_slot_dct[user['name']])
self.ids.user_slot_layout.height += self.user_slot_dct[
user['name']].height
self.ids.user_num_lbl.text = 'Online users ({})'.format(
len(self.user_slot_dct))
@mainthread
def update(self, **kwargs):
"""Updates layout on user join, leave or status change.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# User join
if kwargs['subtype'] == 'join':
self.user_slot_dct[kwargs['name']
] = UserSlot(**kwargs)
self.ids.user_slot_layout.add_widget(
self.user_slot_dct[kwargs['name']])
self.ids.user_slot_layout.height += self.user_slot_dct[
kwargs['name']].height
# User leave
elif kwargs['subtype'] == 'leave':
self.ids.user_slot_layout.remove_widget(
self.user_slot_dct[kwargs['name']])
self.ids.user_slot_layout.height -= self.user_slot_dct[
kwargs['name']].height
del self.user_slot_dct[kwargs['name']]
# User status change
else:
self.user_slot_dct[kwargs['name']].switch_status()
# Updating online user number
self.ids.user_num_lbl.text = 'Online users ({})'.format(
len(self.user_slot_dct))
class CallLayout(BoxLayout):
"""Class representing the call layout (see .kv file for structure).
Attributes:
call_slot_dct (dict): Dictionary mapping call masters to their respective calls.
"""
def __init__(self, call_info_lst):
"""Constructor method.
Args:
call_info_lst (list): List of users in each call and their masters.
"""
self.call_slot_dct = {}
BoxLayout.__init__(self)
for call in call_info_lst:
self.call_slot_dct[call['master']] = CallSlot(**call)
# Adding all slots to layout
self.ids.call_slot_layout.add_widget(
self.call_slot_dct[call['master']])
self.ids.call_slot_layout.height += self.call_slot_dct[
call['master']].height
self.ids.call_num_lbl.text = 'Active calls ({})'.format(
len(self.call_slot_dct))
@mainthread
def update(self, **kwargs):
"""Updates layout on call or user add or remove.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# Adding call
if kwargs['subtype'] == 'call_add':
self.call_slot_dct[kwargs['master']] = CallSlot(**kwargs)
self.ids.call_slot_layout.add_widget(
self.call_slot_dct[kwargs['master']])
self.ids.call_slot_layout.height += self.call_slot_dct[
kwargs['master']].height
# Removing call
elif kwargs['subtype'] == 'call_remove':
self.ids.call_slot_layout.remove_widget(
self.call_slot_dct[kwargs['master']])
self.ids.call_slot_layout.height -= self.call_slot_dct[
kwargs['master']].height
del self.call_slot_dct[kwargs['master']]
# Adding user to call
elif kwargs['subtype'] == 'user_join':
self.call_slot_dct[kwargs['master']].update(
mode='join', **kwargs)
# Removing user from call
else:
self.call_slot_dct[kwargs['master']].update(
mode='leave', **kwargs)
if 'new_master' in kwargs:
call = self.call_slot_dct[kwargs['master']]
del self.call_slot_dct[kwargs['master']]
self.call_slot_dct[kwargs['new_master']] = call
# Updating active call number
self.ids.call_num_lbl.text = 'Active calls ({})'.format(
len(self.call_slot_dct))
class PendingCallFooter(BoxLayout):
"""Footer widget to be shown when a call is pending (see .kv file for structure).
Attributes:
counter_update_evt (ClockEvent): Event scheduled by Kivy clock for
updating counter every second.
elapsed_time (int): Time elapsed since widget appearance.
username (str): The user to call.
"""
def __init__(self, username):
"""Constructor method.
Args:
username (str): The user to call.
"""
self.username = username
self.elapsed_time = 0
BoxLayout.__init__(self)
self.counter_update_evt = Clock.schedule_interval(
lambda dt: self.update_counter(), 1)
def update_counter(self):
"""Updates pending call counter every second.
"""
self.elapsed_time += 1
self.ids.counter.text = '{:0=2d}:{:0=2d}'.format(
self.elapsed_time / 60, self.elapsed_time % 60)
class CallFooter(BoxLayout):
"""Footer widget to be shown when a user is calling (see .kv file for structure).
Attributes:
accept_btn_pressed (bool): Whether the accept button has already been pressed.
username (str): Name of calling user.
"""
def __init__(self, username):
"""Constructor method.
Args:
username (str): Name of calling user.
"""
self.username = username
self.accept_btn_pressed = False
BoxLayout.__init__(self)
def on_call_btn_press(self, status):
"""Notifies server that the call was accepted/rejected by user.
Args:
status (str): Call status (accept/reject)
"""
if not self.accept_btn_pressed:
app = App.get_running_app()
app.send_gui_evt({
'type': 'call',
'subtype': 'response',
'caller': self.username,
'status': status
})
# Preventing sending of multiple accept responses
if status == 'accept':
self.accept_btn_pressed = True
class SessionLayout(BoxLayout):
"""Layout user sees during a call (see .kv file for structure).
Attributes:
chat_layout (ChatLayout): Chat message display layout.
master (str): Current call master.
video_layout (VideoLayout): Video capture display layout.
"""
def __init__(self, **kwargs):
"""Constructor method.
Args:
**kwargs: Keyword arguments supplied in dictioanry form.
"""
BoxLayout.__init__(self)
self.master = kwargs['master']
self.video_layout = VideoLayout(kwargs['user_lst'])
self.add_widget(self.video_layout)
self.chat_layout = ChatLayout()
self.add_widget(self.chat_layout)
def update(self, **kwargs):
"""Updates session layout when changes in call occur.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.video_layout.update(**kwargs)
# User join
if kwargs['subtype'] == 'user_join':
kwargs['msg'] = '{} joined.'.format(kwargs['name'])
# User leave
elif kwargs['subtype'] == 'user_leave':
if 'new_master' in kwargs:
self.master = kwargs['new_master']
kwargs['msg'] = '{} left.'.format(kwargs['name'])
self.chat_layout.add_msg(**kwargs)
class VideoLayout(FloatLayout):
"""Layout of all active video transmissions (see .kv file for structure).
Attributes:
show_stats (bool): Whether to display statistics on screen.
video_display_dct (dict): Dictionary mapping username to video display.
"""
def __init__(self, user_lst):
"""Constructor method.
Args:
user_lst (list): List of users in call.
"""
FloatLayout.__init__(self)
self.video_display_dct = {}
self.show_stats = False
username = App.get_running_app().root_sm.current_screen.username
for user in user_lst:
if user != username:
self.video_display_dct[
user] = PeerVideoDisplay(user, self.show_stats)
self.ids.video_display_layout.add_widget(
self.video_display_dct[user])
def update(self, **kwargs):
"""Updates video layout on user join or leave.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# User join
if kwargs['subtype'] == 'user_join':
video_display = PeerVideoDisplay(kwargs['name'], self.show_stats)
self.video_display_dct[kwargs['name']] = video_display
self.ids.video_display_layout.add_widget(video_display)
# User leave
elif kwargs['subtype'] == 'user_leave':
self.ids.video_display_layout.remove_widget(
self.video_display_dct[kwargs['name']])
del self.video_display_dct[kwargs['name']]
@mainthread
def update_frame(self, **kwargs):
"""Updates video frame corresponding to user.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
if kwargs['src'] in self.video_display_dct:
# Decoding JPEG frame
frame = base64.b64decode(kwargs['frame'])
frame = np.fromstring(frame, dtype='uint8')
decoded_frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
decoded_frame = cv2.flip(decoded_frame, 0)
frame_texture = Texture.create(
size=(decoded_frame.shape[1], decoded_frame.shape[0]),
colorfmt='bgr')
frame_texture.blit_buffer(
decoded_frame.tostring(), colorfmt='bgr', bufferfmt='ubyte')
# Displaying the new video frame on the correct display
if kwargs['src'] in self.video_display_dct:
self.video_display_dct[kwargs['src']
].ids.frame.texture = frame_texture
# Updating video statistics
peer = App.get_running_app().peer
if peer.session and kwargs['src'] in peer.session.user_lst:
tracker = peer.session.video_stat_dct[kwargs['src']]
tracker.update(**kwargs)
def reset_frame(self, user):
"""Resets a user's video display to the blank picture.
Args:
user (str): Username of user to reset its display.
"""
self.video_display_dct[user].ids.frame.reload()
class SelfVideoDisplay(Camera):
"""Display of self video capture (see .kv file for structure).
"""
def __init__(self, **kwargs):
"""Constructor method.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
Camera.__init__(self, index=get_option('cam_index'), **kwargs)
class PeerVideoDisplay(FloatLayout):
"""Display of other peers' video capture (see .kv file for structure).
Attributes:
show_stats (bool): Whether to display statistics on display.
stat_lbl (Label): Label for showing call statistics.
user (str): Name of user in video.
"""
def __init__(self, user, show_stats):
"""Constructor method
Args:
user (str): Name of user in video.
show_stats (bool): Whether to display statistics on display.
"""
self.user = user
self.show_stats = show_stats
FloatLayout.__init__(self)
self.stat_lbl = StatisticsLabel(latency=0)
if self.show_stats:
self.add_widget(self.stat_lbl)
def flip_stats(self):
"""Showing/hiding statistics label.
"""
if not self.show_stats:
self.add_widget(self.stat_lbl)
else:
self.remove_widget(self.stat_lbl)
self.show_stats = not self.show_stats
class StatisticsLabel(Label):
"""Label used for displaying call statistics (see .kv file for structure).
Attributes:
FORMAT_DCT (dict): Dictionary mapping each data type to its format.
text (TYPE): Description
"""
FORMAT_DCT = {
'framerate': lambda val: '{} fps'.format(round(val, 2)),
'bitrate': lambda val: '{} Mbps'.format(round(val / 1000000, 2)),
'latency': lambda val: '{} ms'.format(round(val * 1000, 2)),
'framedrop': lambda val: '{}%'.format(round(val * 100, 2))
}
def __init__(self, **kwargs):
"""Constructor method.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
Label.__init__(self)
self.update(**kwargs)
@mainthread
def update(self, **kwargs):
"""Updates statistics with new data.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
self.text = '\n'.join(['{}: {}'.format(key, StatisticsLabel.FORMAT_DCT[
key](val)) for key, val in kwargs.items()])
class ChatLayout(BoxLayout):
"""Chat messages display layout (see .kv file for structure).
Attributes:
MSG_REGEX (str): Regex of valid chat message format: Non-empty and
doesn't contains ']' or '[' (to prevent markup injection).
"""
MSG_REGEX = r'[^\[\]]+$'
def __init__(self):
"""Constructor method.
"""
BoxLayout.__init__(self)
@mainthread
def add_msg(self, **kwargs):
"""Adds message to chat layout.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
# Building message to be added
msg = kwargs['msg']
if 'src' in kwargs:
msg = '[b]{}[/b]: {}'.format(kwargs['src'], msg)
time = datetime.datetime.fromtimestamp(
kwargs['timestamp']).strftime('%H:%M')
msg = '[{}] {}'.format(time, msg)
# Adding message to chat layout
msg_lbl = MessageLabel(msg)
self.ids.chat_msg_layout.add_widget(msg_lbl)
self.ids.chat_msg_layout.height += msg_lbl.height
self.ids.scroll_layout.scroll_to(msg_lbl)
def on_send_btn_press(self):
"""Sends chat message to group.
"""
# Sending chat GUI event
try:
msg = self.ids.chat_input.text
msg.decode('ascii')
if not re.match(ChatLayout.MSG_REGEX, msg):
raise ValueError
self.ids.chat_input.text = ''
app = App.get_running_app()
chat_msg = {
'type': 'session',
'subtype': 'self_chat',
'src': app.root_sm.current_screen.username,
'msg': msg
}
app.send_gui_evt(chat_msg)
chat_msg['src'] = 'You'
chat_msg['timestamp'] = time.time()
self.add_msg(**chat_msg)
except (UnicodeEncodeError, ValueError):
main_screen = App.get_running_app().root_sm.current_screen
main_screen.add_footer_widget(mode='invalid_text')
class MessageLabel(Label):
"""Label for displaying chat message (see .kv file do structure).
Attributes:
msg (str): Chat message
"""
def __init__(self, msg):
"""Constructor method.
Args:
msg (str): Chat message
"""
self.msg = msg
Label.__init__(self)
class SessionFooter(BoxLayout):
"""Footer displayed during a call (see .kv file for structure).
Attributes:
counter_update_evt (ClockEvent): Event scheduled by Kivy clock for
updating counter every second.
elapsed_time (int): Time elapsed since widget appearance.
end_call_btn_pressed (bool): Whether the end call button has already been pressed.
"""
def __init__(self):
"""Constructor method.
"""
self.elapsed_time = 0
self.end_call_btn_pressed = False
BoxLayout.__init__(self)
self.counter_update_evt = Clock.schedule_interval(
lambda dt: self.update_counter(), 1)
def update_counter(self):
"""Updates pending call counter every second.
"""
self.elapsed_time += 1
self.ids.counter.text = '{:0=2d}:{:0=2d}'.format(
self.elapsed_time / 60, self.elapsed_time % 60)
def on_medium_toggle_btn_press(self, medium):
"""Signals communication component to start/stop transmitting the given medium.
Args:
medium (str): Medium to start/stop transmitting (audio/video).
"""
app = App.get_running_app()
username = app.root_sm.current_screen.username
state = self.ids[medium].state
app.send_gui_evt({
'type': 'session',
'subtype': 'control',
'mode': 'self_state',
'src': username,
'medium': medium,
'state': state
})
# Changing button color accordingly
if state == 'down':
self.ids[medium].background_color = rgba(design.GRAY)
else:
if medium == 'audio':
self.ids[medium].background_color = design.get_color(
'dark', 'orange')
else:
self.ids[medium].background_color = design.get_color(
'dark', 'purple')
def on_stat_btn_press(self):
"""Shows/hides call statistics from display.
"""
root = App.get_running_app().root_sm.current_screen
video_layout = root.session_layout.video_layout
video_display_dct = video_layout.video_display_dct
video_layout.show_stats = not video_layout.show_stats
for user in video_display_dct:
video_display_dct[user].flip_stats()
def on_end_call_btn_press(self):
"""Leaves current call and notifies server.
"""
if not self.end_call_btn_pressed:
app = App.get_running_app()
app.send_gui_evt({
'type': 'session',
'subtype': 'leave'
})
self.end_call_btn_pressed = True
class PypeApp(App):
"""Main app class.
Attributes:
gui_evt_port (int): Port of GUI event listener.
gui_evt_sender (socket.socket): UDP socket that sends GUI events to
the communication component of app.
peer (PypePeer): App's communication component.
root_sm (ScreenManager): Root screen manager.
"""
def send_gui_evt(self, data):
"""Sends GUI event to communication component of app.
Args:
data (dict): Event data (in JSON format).
"""
self.gui_evt_sender.sendto(json.dumps(
data, separators=(',', ':')), ('localhost', self.gui_evt_port))
def on_stop(self):
"""Application close event callback.
"""
self.send_gui_evt({
'type': 'terminate'
})
def build(self):
"""App builder.
Returns:
ScreenManager: Root screen manager.
"""
# Creating root object with all app screens
self.root_sm = ScreenManager()
self.root_sm.switch_to(EntryScreen())
# Creating communication thread
self.peer = PypePeer()
self.gui_evt_port = self.peer.get_gui_evt_port()
self.peer.run()
# Creating user event sender
self.gui_evt_sender = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM)
return self.root_sm
@mainthread
def switch_to_main_screen(self, **kwargs):
"""Switches current screen to main screen.
Args:
**kwargs: Keyword arguments supplied in dictionary form.
"""
main_screen = MainScreen(**kwargs)
self.root_sm.switch_to(main_screen)
# Running app
if __name__ == '__main__':
PypeApp().run()