-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtc.py
420 lines (318 loc) · 12.2 KB
/
rtc.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
import asyncio
import os, sys
from aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.signaling import BYE, CopyAndPasteSignaling, ApprtcSignaling
from blessed import Terminal
term = Terminal()
def rands(x):
from random import choice
return ''.join([choice("1234567890QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkmjnhbgvfcdxsza") for i in range(x)])
def copy(x):
if sys.platform.startswith("linux"):
with open('.temp', 'w') as f:
f.write(x)
os.system("xclip -sel clip .temp")
os.remove('.temp')
def log(*a, **k):
return
print(*a, **k, flush=True)
def task(coro):
asyncio.get_event_loop().create_task(coro)
log("[async] created task", coro)
class Obj(dict):
def __init__(self, a=None, **kwargs):
if type(a) == str:
self.update(**eval(
'dict('+a.strip('obj{').strip('}')+')'
))
else:
super().__init__(**kwargs)
def __str__(self):
return 'obj{'+', '.join([k+'='+repr(v) for k, v in self.items()]) +'}'
__repr__ = __str__
def __getattr__(self, a):
try: return self[a]
except KeyError: return None
def __iter__(self): return iter(self.values())
def __setattr__(self, a, v): self[a] = v
import asyncio
from aiortc.contrib.signaling import object_from_string, object_to_string
import aiohttp
import random
class QSig:
def __init__(self, server=""):
self.server = server
self.id = ''.join([random.choice("1234567890qwertyuiop") for i in range(32)])
print("clientid: ", self.id)
async def connect(self):
pass
async def receive(self):
async with aiohttp.ClientSession(headers=dict(id=self.id)) as session:
while True:
async with session.get(self.server) as r:
if r.status == 200:
return object_from_string( await r.text() )
await asyncio.sleep(0.5)
async def send(self, descr):
async with aiohttp.ClientSession(headers=dict(id=self.id)) as session:
await session.post(self.server, data = object_to_string(descr))
async def close(self):
pass
import asyncio
from aiortc.contrib.signaling import object_from_string, object_to_string
import aiohttp
import random
class HTTPSignal:
def __init__(self, server=""):
self.server = server
self.id = ''.join([random.choice("1234567890qwertyuiop") for i in range(32)])
print("clientid: ", self.id)
async def connect(self):
pass
async def receive(self):
async with aiohttp.ClientSession(headers=dict(id=self.id)) as session:
while True:
async with session.get(self.server) as r:
if r.status == 200:
return object_from_string( await r.text() )
await asyncio.sleep(0.5)
async def send(self, descr):
async with aiohttp.ClientSession(headers=dict(id=self.id)) as session:
await session.post(self.server, data = object_to_string(descr))
class Channel:
def __init__(self, node, label,signal, offer = False):
self.sig = signal
self.pc = RTCPeerConnection()
self._channel = None
self.offer = offer
self.connected = False
self.node = node
self.label = label
async def sig_connect(self):
#run signaling loop
while True:
obj = await self.sig.receive()
if isinstance(obj, RTCSessionDescription):
await self.pc.setRemoteDescription(obj)
if obj.type == "offer":
await self.pc.setLocalDescription(await self.pc.createAnswer())
await self.sig.send(self.pc.localDescription)
elif isinstance(obj, RTCIceCandidate):
await self.pc.addIceCandidate(obj)
elif obj is BYE:
print(f"Channel {self.label} closed", flush=True)
self.node.remove_channel(self.label)
async def connect(self):
await self.sig.connect()
if self.offer:
self._channel = self.pc.createDataChannel("rtc-channel")
@self._channel.on("message")
def on_message(message):
self.node.on_msg( Obj(message), self.label)
@self._channel.on("open")
def on_open():
self.connected = True
await self.pc.setLocalDescription(
await self.pc.createOffer()
)
await self.sig.send(self.pc.localDescription)
else:
@self.pc.on("datachannel")
def on_datachannel(channel):
self._channel = channel
@self._channel.on("message")
def on_message(message):
self.node.on_msg( Obj(message) , self.label)
self.connected = True
loop = asyncio.get_event_loop()
loop.create_task( self.sig_connect() )
while not self.connected:
log(' waiting for connection...\r',end='')
await asyncio.sleep(0.05)
log("connected ")
def send(self, message):
if self.connected:
self.node.cache.append( message.id )
self._channel.send( str(message) )
log(f"[channel>>] {self.label}: {message}")
else:
raise RuntimeError(f"Channel {self.label} not connected")
async def flush(self):
await self._channel._RTCDataChannel__transport._data_channel_flush()
await self._channel._RTCDataChannel__transport._transmit()
async def close(self):
await self.sig.close()
await self.pc.close()
class Node:
def __init__(self, username):
self.channels = Obj()
self.cache = []
self.username = username
self.buffer = ''
def add_channel(self, label, offer=True, id=None):
c = Channel(
self,
label,
HTTPSignal( os.environ.get("RTC_SERVER") or "https://rtc.zyugyzarc.repl.co" ),
offer=offer
)
self.channels[label] = c
return c, id
def on_msg(self, data, label):
log(f"[channel<<] {label}: {data}")
if data.id in self.cache:
log("^ message already in cache")
return
self.cache.append(data.id)
ev = self.__getattribute__("on_"+data.type)
task( ev(data, label) )
async def run(self):
offer = len(sys.argv) == 3
c, id = self.add_channel(
'temp',
offer = offer
)
await c.connect()
if not offer:
await asyncio.sleep(1)
c.send(
Obj(
type='user_join',
username=self.username,
id= rands(64),
reply=True
)
)
await c.flush()
task( self.loop() )
while True:
await asyncio.sleep(1)
async def on_user_join(self, data, label):
self.channels[data.username] = self.channels.pop(label)
if data.reply:
self.channels[data.username].send( Obj(
type='user_join',
username=self.username,
id= rands(64),
reply = False
)
)
data = Obj(
type='message_raw',
sender=self.username,
message=
f"\t{term.bold}{term.cyan}{self.username}{term.normal}{term.bold} added {term.bold}{term.cyan}{data.username}{term.normal}{term.bold} to the chat{term.normal}",
id=rands(64)
)
await self.on_message(data, label)
async def on_user_leave(self, data, label):
await asyncio.sleep(0.1)
c = self.channels.pop(data.username)
await c.close()
async def on_connect_request(self, data, label):
if data.to in self.channels.keys():
self.channels[data.to].send(data)
else:
for i in self.channels:
i.send(data)
async def on_message(self, data, label):
for i in self.channels:
if i.label != data.sender:
i.send( data )
await i.flush()
await self.out(
'\r['+
term.cyan+
data.sender+
term.normal+'] '+
data.message
)
async def on_message_raw(self, data, label):
for i in self.channels:
if i.label != data.sender:
i.send( data )
await i.flush()
await self.out(
data.message
)
async def loop(self):
self.buffer = ''
while True:
with term.cbreak():
s = term.inkey(timeout=0.05)
if s:
if not s.is_sequence:
self.buffer += s
print("\r>> "+self.buffer, end='')
else:
if s.name == 'KEY_BACKSPACE':
self.buffer = self.buffer[:-1]
print('\r>> '+self.buffer+" ", end='')
elif "ENTER" in s.name:
if self.buffer.startswith('/'):
res, raw = await self.cmd(self.buffer)
if res:
data = Obj(
type=('message_raw' if raw else "message"),
sender=self.username,
message=res,
id=rands(64)
)
for i in self.channels:
if i.label != 'temp':
i.send( data )
await i.flush()
self.buffer = ''
await self.out(
'['+term.cyan+
data.sender+
term.normal+'] '+
data.message
)
else:
data = Obj(
type='message',
sender=self.username,
message=self.buffer,
id=rands(64)
)
for i in self.channels:
i.send( data )
await i.flush()
self.buffer = ''
await self.out(
'['+term.cyan+
data.sender+
term.normal+'] '+
data.message
)
await asyncio.sleep(0.05)
await asyncio.sleep(0.05)
async def cmd(self, command):
if command == '/invite':
c, id = self.add_channel(
'temp',
offer = True,
)
task( c.connect() )
print(f"{term.bold} waiting for connection... {term.normal}")
return None, None
elif command == '/leave':
for i in self.channels:
i.send( Obj(
type='user_leave',
username=self.username,
id= rands(64)
) )
async def kill():
await asyncio.sleep(1)
sys.exit()
task(kill())
return f"{term.bold}{self.username} left the chat {term.normal}", True
async def out(self, o):
print('\r' + str(o) +'\n\r>> ' + self.buffer, end='')
async def __main__():
n = Node(sys.argv[1])
await n.run()
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(__main__())