2
0
mirror of https://github.com/ComradCollective/Comrad synced 2024-11-16 00:12:48 +00:00
This commit is contained in:
quadrismegistus 2020-09-16 11:23:18 +01:00
parent f05ff0a5a1
commit 7ce4885892
6 changed files with 142 additions and 61 deletions

View File

@ -602,7 +602,7 @@ class KomradeX(Caller):
msg_to_op, msg_to_op,
route='introduce_komrades' route='introduce_komrades'
) )
# print('res from op',res) print('res from op',res)
return res return res

View File

@ -265,7 +265,12 @@ class Operator(Keymaker):
resp_msg_obj.decrypt() resp_msg_obj.decrypt()
# route back? # route back?
return self.route_msg(resp_msg_obj,reencrypt=False).msg new_msg_obj=self.route_msg(resp_msg_obj,reencrypt=False)
new_msg = new_msg_obj.msg
# print('new_msg_obj',new_msg_obj)
# print('new_msg',new_msg)
return new_msg

View File

@ -431,7 +431,8 @@ from_komrade = {from_komrade}
return { return {
'status':'Message delivered.', 'status':'Message delivered.',
'success':True, 'success':True,
'post_id':post_id 'post_id':post_id,
'msg':msg_from_op
} }
def check_msgs(self, def check_msgs(self,

View File

@ -10,12 +10,12 @@ import textwrap as tw
class CLI(Logger): class CLI(Logger):
ROUTES = { ROUTES = {
'help':'seek help', 'help':'seek help',
'register':'join the komrades', 'signup':'join the komrades',
'login':'log back in', 'login':'log back in',
'meet':'meet a komrade', 'meet':'meet a komrade',
'who':'show contacts or info', 'who':'show contacts or info',
'msg':'write people', 'msg':'write people',
'refresh':'refresh mail', 'check':'check mail',
'read':'read mail', 'read':'read mail',
'verbose':'show/hide log output' 'verbose':'show/hide log output'
} }
@ -43,51 +43,87 @@ class CLI(Logger):
while True: while True:
try: try:
inp=input(f'@{self.name if self.name else "?"}: ') inp=input(f'@{self.name if self.name else "?"}: ')
# print(inp,'??') # self.print(inp,'??')
self.route(inp) self.route(inp)
except (KeyboardInterrupt,EOFError) as e: except (KeyboardInterrupt,EOFError) as e:
exit('\nGoodbye.') exit('\n\n@Operator: Goodbye.\n')
except KomradeException as e: except KomradeException as e:
print(f'@Operator: I could not handle your request. {e}\n') self.print(f'@Operator: I could not handle your request. {e}\n')
#await asyncio.sleep(0.5) #await asyncio.sleep(0.5)
def route(self,inp): def route(self,inp):
inp=inp.strip() inp=inp.strip()
# print('route got:',[inp]) # self.print('route got:',[inp])
if not inp.startswith('/'): return if not inp.startswith('/'): return
cmd=inp.split()[0] cmd=inp.split()[0]
dat=inp[len(cmd):].strip() dat=inp[len(cmd):].strip()
cmd=cmd[1:] cmd=cmd[1:]
# print([cmd,dat]) # self.print([cmd,dat])
if cmd in self.ROUTES and hasattr(self,cmd): if cmd in self.ROUTES and hasattr(self,cmd):
f=getattr(self,cmd) f=getattr(self,cmd)
return f(dat) try:
res=f(dat)
except KomradeException as e:
self.print('@Operator: Message not sent.',e,'\n')
def boot(self,indent=13): def stat(self,*msgs):
logo=art.text2art(CLI_TITLE,font=CLI_FONT) prefix='@Operator: '
blank=' '*len(prefix)
msg = '\n'.join([
(f'{prefix}{x}' if not i else f'{blank}{x}')
for i,x in enumerate(msgs)
])+'\n'
self.print(msg)
def print(self,*x):
x=' '.join(str(xx) for xx in x)
x=str(x).replace('\r\n','\n').replace('\r','\n')
for ln in x.split('\n'):
#scan_print(ln+'\n\n')
print(ln)
def boot(self,indent=None):
if indent is None:
indent=int(round(CLI_WIDTH*.18333333))
logo=art.text2art(CLI_TITLE,font=CLI_FONT).replace('\r\n','\n')
border = '-' * CLI_WIDTH # (len(logo.strip().split('\n')[0]))
# logo=make_key_discreet_str(logo,chance_redacted=0.1) #.decode() # logo=make_key_discreet_str(logo,chance_redacted=0.1) #.decode()
logo=tw.indent(logo, ' '*indent) logo=tw.indent(logo, ' '*indent)
scan_print(logo,max_pause=0.005) border=tw.indent(border, ' '*2)
print('\n'+logo)#),max_pause=0.005)
def help(self,*x,**y): def help(self,*x,**y):
clear_screen() clear_screen()
self.boot() self.boot()
HELPSTR = """ border = '-'*(40)
/login [name] --> log back in if not self.logged_in:
/register [name] --> new komrade""" + ((""" HELPSTR=f"""
/login [name] --> log back in
/signup [name] --> new komrade
"""
else:
HELPSTR=f"""
/check [inbox] --> check messages
/read [inbox] --> read messages
/msg [name] --> send messages
/meet [name] --> exchange info /meet [name] --> exchange info
/msg [name] [msg] --> write to person or group /who [name] --> show contacts
/who [name] --> show contact info
/refresh [inbox] --> refresh messages
/read [inbox] --> read messages""")
if self.with_required_login(quiet=True) else "") + """
/help --> seek help
""" """
print(HELPSTR) HELPSTR+=f"""
/help --> seek help
"""
helpstr = tw.indent(HELPSTR.strip()+'\n\n',' '*13)
self.print(helpstr)
# self.print(border+helpstr+'\n'+self.border)
@property
def border(self):
border = '-' * CLI_WIDTH # (len(logo.strip().split('\n')[0]))
border=tw.indent(border, ' '*2)
return border
def intro(self): def intro(self):
self.status(None) self.status(None)
@ -95,10 +131,10 @@ class CLI(Logger):
def who(self,whom): def who(self,whom):
if self.with_required_login(): if self.with_required_login():
contacts = self.komrade.contacts() contacts = self.komrade.contacts()
print(' ' + '\n '.join(contacts)) self.print(' ' + '\n '.join(contacts))
def register(self,name=None): def signup(self,name=None):
if not name: name=input('name: ') if not name: name=input('name: ')
if not name: return if not name: return
self.komrade = Komrade(name) self.komrade = Komrade(name)
@ -106,17 +142,18 @@ class CLI(Logger):
if res and type(res)==dict and 'success' in res and res['success']: if res and type(res)==dict and 'success' in res and res['success']:
self.name=self.komrade.name self.name=self.komrade.name
self.loggedin=True self.loggedin=True
self.stat(f'Welcome, Komrade @{self.name}.')
else: else:
self.name=None self.name=None
self.loggedin=False self.loggedin=False
self.komrade=None self.komrade=None
if res and 'status' in res: if res and 'status' in res:
# self.boot() # self.boot()
print('\n@Operator: '+res.get('status','?')+'\n') self.stat(res.get('status','?'))
def login(self,name): def login(self,name):
# print(self,name,self.name,self.komrade,self.loggedin) # self.print(self,name,self.name,self.komrade,self.loggedin)
if not name: name=input('name: ') if not name: name=input('name: ')
if not name: return if not name: return
self.komrade=Komrade(name) self.komrade=Komrade(name)
@ -132,7 +169,7 @@ class CLI(Logger):
self.komrade=None self.komrade=None
if res and 'status' in res: if res and 'status' in res:
self.help() self.help()
print('@Operator: '+res.get('status','?')+'\n') self.stat(res.get('status','?'))
@property @property
def logged_in(self): def logged_in(self):
@ -142,7 +179,7 @@ class CLI(Logger):
def with_required_login(self,quiet=False): def with_required_login(self,quiet=False):
if not self.logged_in: if not self.logged_in:
if not quiet: if not quiet:
print('@Operator: You must be logged in first.\n') self.stat('You must be logged in first.')
return False return False
return True return True
@ -159,33 +196,51 @@ class CLI(Logger):
if self.with_required_login(): if self.with_required_login():
name_or_pubkey = dat.strip().split()[0] name_or_pubkey = dat.strip().split()[0]
res = self.komrade.meet(name_or_pubkey,returning=returning) res = self.komrade.meet(name_or_pubkey,returning=returning)
print('@Operator:',res) status=res.get('status')
msg = status if not res.get('success') else status+str(res)
self.stat(status)
def msg(self,dat): def msg(self,dat):
if self.with_required_login(): if self.with_required_login():
name_or_pubkey,msg = dat.split(' ',1) dat=dat.strip()
self.log(f'Composed msg to {name_or_pubkey}: {msg}') if not dat:
self.status('Message whom? Usage: /msg [name]')
return
datl=dat.split(' ',1)
name_or_pubkey = datl[0]
if len(datl)==1:
self.stat(f'Compose your message to @{name_or_pubkey} below.', 'Press Ctrl+D to complete, or Ctrl+C to cancel.')
msg_s = multiline_input().strip()
if not msg_s:
print('\n')
self.stat('Not sending. No message found.')
return
else:
msg_s = datl[1]
self.log(f'Composed msg to {name_or_pubkey}: {msg_s}')
msg_obj = self.komrade.msg( msg_obj = self.komrade.msg(
name_or_pubkey, name_or_pubkey,
msg msg_s
) )
self.log(f'Sent msg obj to {name_or_pubkey}: {msg_obj}') self.log(f'Sent msg obj to {name_or_pubkey}: {msg_obj}')
print(f'@Operator: Message successfully sent to @{name_or_pubkey}.\n') self.stat(f'Message successfully sent to @{name_or_pubkey}.\n{msg_obj}')
def refresh(self,dat): def check(self,dat):
if self.with_required_login(): if self.with_required_login():
res = self.komrade.refresh() res = self.komrade.refresh()
if not res['success']: if not res['success']:
print(f"@Operator: {res['status']}\n") self.stat(res['status'])
else: else:
unr = res.get('unread',[]) unr = res.get('unread',[])
inb = res.get('inbox',[]) inb = res.get('inbox',[])
print(f'@Operator: You have {len(unr)} unread messages, with {len(inb)} total in your inbox.\n') self.stat(f'You have {len(unr)} unread messages, with {len(inb)} total in your inbox.')
def prompt_adduser(self,msg): def prompt_adduser(self,msg):
# print('prompt got:',msg) # self.print('prompt got:',msg)
# print(msg.data) # self.print(msg.data)
do_pause() do_pause()
# clear_screen() # clear_screen()
meet_name = msg.data.get('meet_name') meet_name = msg.data.get('meet_name')
@ -200,42 +255,42 @@ class CLI(Logger):
meet_name meet_name
) )
clear_screen() clear_screen()
print(f'@Operator: The public key of @{meet_name} has been saved as a QRcode to {fnfn}:\n{qrstr}') self.stat(f'The public key of @{meet_name} has been saved as a QRcode to {fnfn}:\n{qrstr}')
if do_senduser.strip().lower()=='y': if do_senduser.strip().lower()=='y':
print('returning the invitation ...') self.print('returning the invitation ...')
res = self.komrade.meet(meet_name,returning=True) res = self.komrade.meet(meet_name,returning=True)
# print('got from meeting:',res) # self.print('got from meeting:',res)
def prompt_msg(self,msg): def prompt_msg(self,msg):
do = input(f'\n\n@Operator: Type "r" to reply, "d" to delete, or hit Enter to continue.\n{self.komrade}: ') do = input(f'\n\n@Operator: Type "r" to reply, "d" to delete, or hit Enter to continue.\n{self.komrade}: ')
do=do.strip().lower() do=do.strip().lower()
if do=='d': if do=='d':
# print('del',msg.post_id) # self.print('del',msg.post_id)
self.komrade.delete_msg(msg.post_id) self.komrade.delete_msg(msg.post_id)
elif do=='r': elif do=='r':
print('@todo: replying...') self.print('@todo: replying...')
else: else:
pass pass
def read(self,dat): def read(self,dat):
if self.with_required_login(): if self.with_required_login():
res = self.komrade.inbox() res = self.komrade.inbox()
# print('got from read res:',res) # self.print('got from read res:',res)
if not res.get('success'): if not res.get('success'):
print('@Operator:',res['status']) self.print('@Operator:',res['status'])
return return
# print('ummmmm msgs?') # self.print('ummmmm msgs?')
msgs=res.get('msgs') msgs=res.get('msgs')
if not msgs: if not msgs:
print('@Operator: No messages.') self.print('@Operator: No messages.')
else: else:
clear_screen() clear_screen()
for i,msg in enumerate(msgs): for i,msg in enumerate(msgs):
print(f'@Operator: Showing most recent messages first.\n\n\n Message {i+1} of {len(msgs)}') self.stat(f'Showing most recent messages first.\n\n\n Message {i+1} of {len(msgs)}')
print(msg) self.print(msg)
# print('DATA',msg.msg_d) # self.print('DATA',msg.msg_d)
if msg.data.get('prompt_id')=='addcontact': if msg.data.get('prompt_id')=='addcontact':
self.prompt_adduser(msg) self.prompt_adduser(msg)
@ -277,7 +332,7 @@ class CLI(Logger):
while not name: while not name:
name=self.status(('name','@TheTelephone: Of course, Komrade...?\n@')).get('vals').get('name').strip() name=self.status(('name','@TheTelephone: Of course, Komrade...?\n@')).get('vals').get('name').strip()
print() self.print()
self.status( self.status(
f'@TheTelephone: Of course, Komrade @{name}. A fine name.', f'@TheTelephone: Of course, Komrade @{name}. A fine name.',
@ -564,7 +619,7 @@ class CLI(Logger):
def run_cli(inp): def run_cli(inp):
cli = CLI() cli = CLI()
cli.run(inp) #'/register elon') #'/register',name='elon') cli.run(inp) #'/signup elon') #'/signup',name='elon')
if __name__=='__main__': if __name__=='__main__':
inp = ' '.join(sys.argv[1:]) inp = ' '.join(sys.argv[1:])

View File

@ -166,5 +166,5 @@ SAVE_LOGS = 1
CLI_TITLE = 'KOMRADE' CLI_TITLE = 'KOMRADE'
CLI_FONT = 'clr5x6'#'colossal' CLI_FONT = 'clr5x6'#'colossal'
CLI_WIDTH = STATUS_LINE_WIDTH = 70 CLI_WIDTH = STATUS_LINE_WIDTH = 60

View File

@ -354,7 +354,7 @@ def capture_stdout(func):
def scan_print(xstr,min_pause=0,max_pause=.01,speed=1): def scan_print(xstr,min_pause=0,max_pause=.01,speed=2):
import random,time import random,time
for c in xstr: for c in xstr:
print(c,end='',flush=True) print(c,end='',flush=True)
@ -383,3 +383,23 @@ def date_today():
import datetime import datetime
dt = datetime.datetime.today() dt = datetime.datetime.today()
return f'{dt.year}-{str(dt.month).zfill(2)}-{dt.day}' return f'{dt.year}-{str(dt.month).zfill(2)}-{dt.day}'
def multiline_input(msg=None):
# if msg:
# print(msg,end=' ')
contents = []
i=-1
while True:
i+=1
try:
line = input(msg if msg and not i else "") #.decode('utf-8',errors='ignore')
contents.append(line)
except EOFError:
break
except KeyboardInterrupt:
contents=''
break
txt="\n".join(contents) if contents else contents
return txt