Skip to content

Commit 2320a71

Browse files
committed
make tn-cli compatible with python3 and better error reporting for {acc}
1 parent eb9099c commit 2320a71

File tree

2 files changed

+38
-37
lines changed

2 files changed

+38
-37
lines changed

server/session.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -459,12 +459,8 @@ func (s *Session) acc(msg *ClientComMessage) {
459459

460460
// Check if login is unique.
461461
if ok, err := authhdl.IsUnique(msg.Acc.Secret); !ok {
462-
log.Println("Check unique: ", err)
463-
if err == types.ErrDuplicate {
464-
s.queueOut(ErrDuplicateCredential(msg.Acc.Id, "", msg.timestamp))
465-
} else {
466-
s.queueOut(ErrUnknown(msg.Acc.Id, "", msg.timestamp))
467-
}
462+
log.Println("Check unique:", err)
463+
s.queueOut(decodeStoreError(err, msg.Acc.Id, msg.timestamp, nil))
468464
return
469465
}
470466

@@ -630,6 +626,7 @@ func (s *Session) acc(msg *ClientComMessage) {
630626

631627
} else {
632628
// session is not authenticated and this is not an attempt to create a new account
629+
log.Println("acc failed: not a new account and no valid UID")
633630
s.queueOut(ErrPermissionDenied(msg.Acc.Id, "", msg.timestamp))
634631
return
635632
}

tn-cli/tn-cli.py

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
# Saved topic: default topic name to make keyboard input easier
2525
SavedTopic = None
2626

27+
# In python 3 has input(), python 2 has raw_input. Make input() work in python 2.x.
28+
try: input = raw_input
29+
except NameError: pass
30+
2731
# Pack user's name and avatar into a vcard represented as json.
2832
def make_vcard(fn, photofile):
2933
card = None
@@ -43,7 +47,7 @@ def make_vcard(fn, photofile):
4347
# TODO: use mimetype.guess_type(ext) instead
4448
card.photo.type = os.path.splitext(photofile)[1]
4549
except IOError as err:
46-
print "Error opening '" + photofile + "'", err
50+
print("Error opening '" + photofile + "'", err)
4751

4852
card = json.dumps(card)
4953

@@ -95,7 +99,7 @@ def delMsg(id, topic, what, param, hard):
9599
topic = param
96100
param = None
97101

98-
print id, topic, what, param, hard
102+
print(id, topic, what, param, hard)
99103
enum_what = None
100104
before = None
101105
seq_list = None
@@ -106,7 +110,7 @@ def delMsg(id, topic, what, param, hard):
106110
seq_list = [pb.DelQuery(range=pb.SeqRange(low=1, hi=0x8FFFFFF))]
107111
elif param != None:
108112
seq_list = [pb.DelQuery(seq_id=int(x.strip())) for x in param.split(',')]
109-
print seq_list
113+
print(seq_list)
110114

111115
elif what == 'sub':
112116
enum_what = pb.ClientDel.SUB
@@ -151,8 +155,8 @@ def parse_cmd(cmd):
151155
parser = None
152156
if parts[0] == "acc":
153157
parser = argparse.ArgumentParser(prog=parts[0], description='Create or alter an account')
154-
parser.add_argument('--user', default=None, help='ID of the account to update')
155-
parser.add_argument('--scheme', default="basic", help='authentication scheme, default=basic')
158+
parser.add_argument('--user', default='new', help='ID of the account to update')
159+
parser.add_argument('--scheme', default='basic', help='authentication scheme, default=basic')
156160
parser.add_argument('--secret', default=None, help='secret for authentication')
157161
parser.add_argument('--uname', default=None, help='user name for basic authentication')
158162
parser.add_argument('--password', default=None, help='password for basic authentication')
@@ -165,7 +169,7 @@ def parse_cmd(cmd):
165169
parser.add_argument('--anon', default=None, help='default access mode for anonymous users')
166170
elif parts[0] == "login":
167171
parser = argparse.ArgumentParser(prog=parts[0], description='Authenticate current session')
168-
parser.add_argument('--scheme', default="basic")
172+
parser.add_argument('--scheme', default='basic')
169173
parser.add_argument('secret', nargs='?', default=argparse.SUPPRESS)
170174
parser.add_argument('--secret', dest='secret', default=None)
171175
parser.add_argument('--uname', default=None)
@@ -225,18 +229,18 @@ def parse_cmd(cmd):
225229
help='notification type')
226230
parser.add_argument('--seq', help='value being reported')
227231
else:
228-
print "Unrecognized:", parts[0]
229-
print "Possible commands:"
230-
print "\tacc\t- create account"
231-
print "\tlogin\t- authenticate"
232-
print "\tsub\t- subscribe to topic"
233-
print "\tleave\t- detach or unsubscribe from topic"
234-
print "\tpub\t- post message to topic"
235-
print "\tget\t- query topic for metadata or messages"
236-
print "\tset\t- update topic metadata"
237-
print "\tdel\t- delete message(s), topic or subscription"
238-
print "\tnote\t- send notification"
239-
print "\n\tType <command> -h for help"
232+
print("Unrecognized:", parts[0])
233+
print("Possible commands:")
234+
print("\tacc\t- create account")
235+
print("\tlogin\t- authenticate")
236+
print("\tsub\t- subscribe to topic")
237+
print("\tleave\t- detach or unsubscribe from topic")
238+
print("\tpub\t- post message to topic")
239+
print("\tget\t- query topic for metadata or messages")
240+
print("\tset\t- update topic metadata")
241+
print("\tdel\t- delete message(s), topic or subscription")
242+
print("\tnote\t- send notification")
243+
print("\n\tType <command> -h for help")
240244
return None
241245

242246
try:
@@ -294,7 +298,7 @@ def gen_message(schema, secret):
294298

295299
while True:
296300
id += 1
297-
inp = raw_input("tn> ")
301+
inp = input("tn> ")
298302
if inp == "":
299303
continue
300304
if inp == "exit" or inp == "quit":
@@ -319,17 +323,17 @@ def run(addr, schema, secret):
319323
del onCompletion[msg.ctrl.id]
320324
if msg.ctrl.code >= 200 and msg.ctrl.code < 400:
321325
func(msg.ctrl.params)
322-
print str(msg.ctrl.code) + " " + msg.ctrl.text
326+
print(str(msg.ctrl.code) + " " + msg.ctrl.text)
323327
elif msg.HasField("data"):
324-
print "\nFrom: " + msg.data.from_user_id + ":\n"
325-
print json.loads(msg.data.content) + "\n"
328+
print("\nFrom: " + msg.data.from_user_id + ":\n")
329+
print(json.loads(msg.data.content) + "\n")
326330
elif msg.HasField("pres"):
327331
pass
328332
else:
329-
print "Message type not handled", msg
333+
print("Message type not handled", msg)
330334

331335
except grpc._channel._Rendezvous as err:
332-
print err
336+
print(err)
333337

334338
def read_cookie():
335339
try:
@@ -341,7 +345,7 @@ def read_cookie():
341345
return params
342346

343347
except Exception as err:
344-
print "Missing or invalid cookie file '.tn-cli-cookie'", err
348+
print("Missing or invalid cookie file '.tn-cli-cookie'", err)
345349
return None
346350

347351
def save_cookie(params):
@@ -353,32 +357,32 @@ def save_cookie(params):
353357
for p in params:
354358
nice[p] = json.loads(params[p])
355359

356-
print "Authenticated as", nice.get('user')
360+
print("Authenticated as", nice.get('user'))
357361

358362
try:
359363
cookie = open('.tn-cookie', 'w')
360364
json.dump(nice, cookie)
361365
cookie.close()
362366
except Exception as err:
363-
print "Failed to save authentication cookie", err
367+
print("Failed to save authentication cookie", err)
364368

365369
def print_server_params(params):
366-
print "Connected to server:"
370+
print("Connected to server:")
367371
for p in params:
368-
print "\t" + p + ": " + json.loads(params[p])
372+
print("\t" + p + ": " + json.loads(params[p]))
369373

370374
if __name__ == '__main__':
371375
"""Parse command-line arguments. Extract host name and authentication scheme, if one is provided"""
372376
purpose = "Tinode command line client. Version " + VERSION + "."
373-
print purpose
377+
print(purpose)
374378
parser = argparse.ArgumentParser(description=purpose)
375379
parser.add_argument('--host', default='localhost:6061', help='address of Tinode server')
376380
parser.add_argument('--login-basic', help='login using basic authentication username:password')
377381
parser.add_argument('--login-token', help='login using token authentication')
378382
parser.add_argument('--login-cookie', action='store_true', help='read token from cookie file and use it for authentication')
379383
args = parser.parse_args()
380384

381-
print "Server '" + args.host + "'"
385+
print("Server '" + args.host + "'")
382386

383387
schema = None
384388
secret = None

0 commit comments

Comments
 (0)