-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat.py
358 lines (299 loc) · 11.8 KB
/
chat.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
"""
@project: PJSIP-Lab
@author: sam
@file chat.py
@ide: Visual Studio Code
@time: 2019-12-03 17:42:37
@blog: https://jiahaoplus.com
"""
import time
import random
import pjsua2 as pj
import tkinter as tk
from utils import *
from config import *
from call import Call
from tkinter import ttk
from buddy import Buddy
from account import Account
from endpoint import Endpoint
class Chat(tk.Toplevel):
def __init__(self, acc, bud, app):
tk.Toplevel.__init__(self)
self.acc = acc
self.bud = bud
self.app = app
self.call = None
self.vid_win = None
self.vid_pre = None
self.state = AudioState.DISCONNECT
"""
Initialize UI
"""
self.photo = tk.PhotoImage(file='image/user.png')
self.title(bud.cfg.uri)
self.resizable(width=False, height=False)
self.geometry('+{}+{}'.format(int(self.winfo_screenwidth() / 2),
int(self.winfo_screenheight() / 2)))
self.canvas = tk.Canvas(
self, width=400, height=400, bg=COLOR_BACKGROUND)
self.canvas.grid(row=0, column=0, rowspan=10, columnspan=2,
padx=10, pady=10, sticky='nsew')
self.chat = tk.Frame(self.canvas)
self.canvas.create_window(
(0, 0), window=self.chat, anchor='nw', tags='chat')
self.canvas.bind('<Configure>', self._canvas_resize)
self.chat.bind('<Configure>', self._chat_resize)
self.scrl = ttk.Scrollbar(self, orient=tk.VERTICAL,
command=self.canvas.yview)
self.canvas.config(yscrollcommand=self.scrl.set)
self.scrl.grid(row=0, column=2, rowspan=10, sticky='nsw')
# Message Entry
self.message = tk.Entry(self, font=FONT_CONTENT, width=30)
self.message.bind('<Return>', self._send_message)
self.message.grid(row=10, column=0, padx=10, pady=10)
# Call Button
tk.Button(self, text='Call', font=FONT_CONTENT, width=10,
command=self._make_call).grid(row=10, column=1, padx=2, pady=2)
# State Label
self.state_label = tk.Label(self, font=FONT_TITLE, text='No connect')
self.state_label.grid(row=5, column=3, columnspan=3, padx=10, pady=10)
# Timer Label
self.timer = StopWatch(self)
self.timer.grid(row=6, column=3, columnspan=3, padx=10, pady=10)
# RX Volume Scale
tk.Label(self, text='Micphone', font=FONT_CONTENT).grid(
row=7, column=3, padx=10, pady=10)
self.rx_scale = tk.Scale(
self, from_=0.0, to=10.0, orient=tk.HORIZONTAL, showvalue=0)
self.rx_scale.set(5.0)
self.rx_scale.bind('<ButtonRelease-1>', self._rx_volume)
self.rx_scale.grid(row=7, column=4, columnspan=2, padx=5, pady=5)
# TX Volume Scale
tk.Label(self, text='Speaker', font=FONT_CONTENT).grid(
row=8, column=3, padx=10, pady=10)
self.tx_scale = tk.Scale(
self, from_=0.0, to=10.0, orient=tk.HORIZONTAL, showvalue=0)
self.tx_scale.set(5.0)
self.tx_scale.bind('<ButtonRelease-1>', self._tx_volume)
self.tx_scale.grid(row=8, column=4, columnspan=2, padx=5, pady=5)
# Hold Button
self.hold_button = tk.Button(
self, text='Hold', font=FONT_CONTENT, width=10, command=self._set_hold)
self.hold_button.grid(row=9, column=3, padx=10, pady=10)
# Hangup Button
tk.Button(self, text='Hangup', font=FONT_CONTENT, width=10,
command=self._hang_up).grid(row=9, column=5, padx=10, pady=10)
self.protocol('WM_DELETE_WINDOW', self._exit)
self.bind('<Configure>', self._resize)
def add_message(self, msg, flag):
msg = msg.replace('\n', '')
tk.Label(self.chat, text=time.strftime(
'%H:%M:%S', time.localtime()), fg=COLOR_TIME).pack(anchor='center')
if flag == MessageState.RECEIVE:
content = tk.Frame(self.chat)
tk.Label(content, image=self.photo).pack(side=tk.LEFT, anchor='n')
tk.Label(content, font=FONT_MESSAGE, text=msg, wraplength=200, justify='left',
bg=COLOR_RECEIVE_BUBBLE).pack(side=tk.LEFT, ipadx=5, ipady=5)
content.pack(anchor='w')
else:
content = tk.Frame(self.chat)
tk.Label(content, image=self.photo).pack(side=tk.RIGHT, anchor='n')
tk.Label(content, font=FONT_MESSAGE, text=msg, wraplength=200,
justify='left', bg=COLOR_SEND_BUBBLE).pack(side=tk.RIGHT, ipadx=5, ipady=5)
content.pack(anchor='e')
# Important!!! Can't remove!!!
self.chat.update_idletasks()
self.canvas.yview_moveto(1)
def show_video(self, vid_win, vid_pre):
self.vid_win = vid_win
self.vid_pre = vid_pre
# Set video position
pos = pj.MediaCoordinate()
pos.x = self.winfo_rootx() + self.winfo_width()
pos.y = self.winfo_rooty()
self.vid_win.setPos(pos)
# Set video size
size = pj.MediaSize()
size.w = int(self.winfo_height() * 0.8)
size.h = int(self.winfo_height() * 0.8)
self.vid_win.setSize(size)
# Show video
self.vid_win.Show(True)
# Show preview
pre_prm = pj.VideoPreviewOpParam()
self.vid_pre.start(pre_prm)
# Set preview position
pos = pj.MediaCoordinate()
pos.x = self.winfo_rootx() + self.winfo_width()
pos.y = self.winfo_rooty() + int(self.winfo_height() * 0.8)
self.vid_pre.getVideoWindow().setPos(pos)
# Set preview size
size = pj.MediaSize()
size.w = int(self.winfo_height() * 0.2)
size.h = int(self.winfo_height() * 0.2)
self.vid_pre.getVideoWindow().setSize(size)
def is_calling(self):
self.state = AudioState.CALLING
self.state_label['text'] = self.state.value
def is_connect(self):
self.state = AudioState.CONNECT
self.state_label['text'] = self.state.value
self.timer.reset()
self.timer.start()
def is_disconnect(self):
if self.vid_win:
self.vid_win = None
if self.vid_pre:
self.vid_pre.stop()
self.vid_pre = None
self.state = AudioState.DISCONNECT
self.state_label['text'] = self.state.value
self.timer.stop()
self.add_message('Call Ended\nLast ' +
self.timer.get(), MessageState.INFO)
def is_hold(self):
self.hold_button['text'] = 'UnHold'
self.state = AudioState.HOLD
self.state_label['text'] = self.state.value
self.timer.stop()
def is_unhold(self):
self.hold_button['text'] = 'Hold'
self.state = AudioState.CONNECT
self.state_label['text'] = self.state.value
self.timer.start()
def _send_message(self, event):
msg = self.message.get()
if msg != '':
msg_prm = pj.SendInstantMessageParam()
msg_prm.content = msg
self.bud.sendInstantMessage(msg_prm)
self.add_message(msg, MessageState.SEND)
self.message.delete(0, 'end')
def receive_message(self, msg):
self.add_message(msg, MessageState.RECEIVE)
def _make_call(self):
if self.state == AudioState.DISCONNECT:
# Initialize Call
self.call = Call(self.acc, self.bud.cfg.uri, self)
# Create paramter
call_prm = pj.CallOpParam()
# Enable audio
call_prm.opt.audioCount = 1
# Enable video
call_prm.opt.videoCount = 1
# Make call
self.call.makeCall(self.bud.cfg.uri, call_prm)
def receive_call(self, call):
# Update call and set chat
self.call = call
self.call.chat = self
# Receive call
call_prm = pj.CallOpParam()
call_prm.statusCode = pj.PJSIP_SC_OK
self.call.answer(call_prm)
def _set_hold(self):
if self.call:
call_prm = pj.CallOpParam()
if self.state == AudioState.CONNECT:
self.call.setHold(call_prm)
self.is_hold()
elif self.state == AudioState.HOLD:
# Important!!! Can't remove!!!
call_prm.opt.audioCount = 1
call_prm.opt.flag = pj.PJSUA_CALL_UNHOLD
self.call.reinvite(call_prm)
self.is_unhold()
else:
print('Call isn\'t initialized')
def _hang_up(self):
if self.call:
call_prm = pj.CallOpParam()
if self.state != AudioState.DISCONNECT:
self.call.hangup(call_prm)
def _rx_volume(self, event):
am = self.call.getAudioMedia(-1)
am.adjustRxLevel(self.rx_scale.get() / 10.0)
def _tx_volume(self, event):
am = self.call.getAudioMedia(-1)
am.adjustTxLevel(self.tx_scale.get() / 10.0)
def _canvas_resize(self, event):
# Important!!! Can't remove!!!
self.canvas.itemconfig('chat', width=event.width)
def _chat_resize(self, event):
# Important!!! Can't remove!!!
self.canvas.config(scrollregion=self.canvas.bbox('all'))
def _resize(self, event):
if self.vid_win and self.vid_pre:
# Set video position
pos = pj.MediaCoordinate()
pos.x = self.winfo_rootx() + self.winfo_width()
pos.y = self.winfo_rooty()
self.vid_win.setPos(pos)
# Set preview position
pos = pj.MediaCoordinate()
pos.x = self.winfo_rootx() + self.winfo_width()
pos.y = self.winfo_rooty() + int(self.winfo_height() * 0.8)
self.vid_pre.getVideoWindow().setPos(pos)
def _exit(self):
try:
self.app.delete_chat(self.bud.iid)
self._hang_up()
self.destroy()
except:
self.destroy()
class StopWatch(tk.Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
tk.Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = tk.StringVar()
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
l = tk.Label(self, textvariable=self.timestr, font=FONT_TITLE)
self._setTime(self._elapsedtime)
l.pack(fill=tk.X, expand=tk.NO, pady=2, padx=2)
def _update(self):
""" Update the label with elapsed time. """
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._timer = self.after(50, self._update)
def _setTime(self, elap):
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap / 60)
seconds = int(elap - minutes * 60.0)
hseconds = int((elap - minutes * 60.0 - seconds) * 100)
self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))
def start(self):
""" Start the stopwatch, ignore if running. """
if not self._running:
self._start = time.time() - self._elapsedtime
self._update()
self._running = 1
def stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._running = 0
def reset(self):
""" Reset the stopwatch. """
self._start = time.time()
self._elapsedtime = 0.0
self._setTime(self._elapsedtime)
def get(self):
return self.timestr.get()
def test():
root = tk.Tk()
acc = Account(None)
bud = Buddy(None, '1002')
bud_cfg = pj.BuddyConfig()
bud_cfg.uri = 'sip:1002@27.102.107.237'
Chat(acc, bud, root)
root.mainloop()
if __name__ == '__main__':
test()