2018-11-20 19:45:27 +00:00
|
|
|
import sys
|
|
|
|
import asyncio
|
|
|
|
import random
|
2021-08-19 02:59:04 +00:00
|
|
|
import syndicate
|
2021-08-19 21:05:55 +00:00
|
|
|
from syndicate import patterns as P, actor, dataspace
|
2021-08-19 21:04:35 +00:00
|
|
|
from syndicate.schema import simpleChatProtocol, sturdy
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 02:59:04 +00:00
|
|
|
Present = simpleChatProtocol.Present
|
|
|
|
Says = simpleChatProtocol.Says
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 02:59:04 +00:00
|
|
|
conn_str = '<ws "ws://localhost:8001/">'
|
|
|
|
cap_str = '<ref "syndicate" [] #[pkgN9TBmEd3Q04grVG4Zdw==]>'
|
|
|
|
cap = sturdy.SturdyRef.decode(syndicate.parse(cap_str))
|
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
def main(turn):
|
|
|
|
root_facet = turn._facet
|
2021-08-19 17:26:12 +00:00
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
@syndicate.relay.connect(turn, conn_str, cap)
|
|
|
|
def on_connected(turn, ds):
|
|
|
|
me = 'user_' + str(random.randint(10, 1000))
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
turn.publish(ds, Present(me))
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
@dataspace.during(turn, ds, P.rec('Present', P.CAPTURE), inert_ok=True)
|
|
|
|
def on_presence(turn, who):
|
|
|
|
print('%s joined' % (who,))
|
|
|
|
turn.on_stop(lambda turn: print('%s left' % (who,)))
|
2021-08-19 16:59:48 +00:00
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
@dataspace.on_message(turn, ds, P.rec('Says', P.CAPTURE, P.CAPTURE))
|
|
|
|
def on_says(turn, who, what):
|
|
|
|
print('%s says %r' % (who, what))
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 21:04:35 +00:00
|
|
|
@turn.linked_task()
|
|
|
|
async def accept_input(f):
|
|
|
|
reader = asyncio.StreamReader()
|
|
|
|
await actor.find_loop().connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), sys.stdin)
|
|
|
|
while line := (await reader.readline()).decode('utf-8'):
|
|
|
|
actor.Turn.external(f, lambda turn: turn.send(ds, Says(me, line.strip())))
|
|
|
|
actor.Turn.external(f, lambda turn: turn.stop(root_facet))
|
2018-11-20 19:45:27 +00:00
|
|
|
|
2021-08-19 02:59:04 +00:00
|
|
|
actor.start_actor_system(main, name = 'chat', debug = False)
|