3 import sys, os, getopt, pwd, operator
4 from fulbank import auth
9 def pfxmatch(pfx, item):
10 return str(item)[:len(pfx)] == pfx
12 class ambiguous(LookupError):
13 def __init__(self, a, b):
14 super().__init__("ambigous match: %s and %s" % (a, b))
18 def find(seq, *, item=None, test=None, match=None, key=None, default=LookupError):
21 if match is None and item is not None:
22 match = lambda o: test(item, o)
31 if default is LookupError:
32 raise ambiguous(key(found), key(thing))
37 if default is LookupError:
43 out.write("usage: netbank [-h] BANK-ID COMMAND [ARGS...]\n")
48 sys.stderr.write("netbank: %s: no current session\n" % (cmd))
55 def cmd_login(cmd, args):
58 sys.stderr.write("usage: login TYPE\n")
60 sess = sesstype.create()
61 if args[0] == "bankid":
62 authfun = sess.auth_bankid
63 elif args[0] == "token":
64 authfun = sess.auth_token
66 sys.stderr.write("netbank: %s: unknown authentication type\n" % (args[0]))
69 sys.stderr.write("usage: login bankid USER-ID\n")
71 with auth.ttyconv() as conv:
73 authfun(args[1], conv)
74 except auth.autherror as err:
75 sys.stderr.write("netbank: authentication failed: %s\n" % err)
77 commands["login"] = cmd_login
80 def cmd_logout(cmd, args):
85 commands["logout"] = cmd_logout
88 def cmd_ping(cmd, args):
90 commands["ping"] = cmd_ping
93 def cmd_lsacct(cmd, args):
94 for acct in sess.accounts:
95 sys.stdout.write("%s (%s): %s\n" % (acct.number, acct.name, acct.balance))
96 commands["lsacct"] = cmd_lsacct
99 def cmd_lstxn(cmd, args):
100 opts, args = getopt.getopt(args, "n:")
106 sys.stderr.write("usage: lstxn [-n NUM] ACCOUNT\n")
109 acct = find(sess.accounts, item=args[0], key=lambda acct: acct.number, test=pfxmatch)
110 except ambiguous as exc:
111 sys.stderr.write("netbank: %s: ambiguous match between %s and %s\n" % (args[0], exc.a, exc.b))
114 sys.stderr.write("netbank: %s: no such account\n" % (args[0]))
116 for i, txn in zip(range(num), acct.transactions()):
117 sys.stdout.write("%s %s: %s\n" % (txn.date.isoformat(), txn.value, txn.message))
118 commands["lstxn"] = cmd_lstxn
121 global sess, sesstype
123 opts, args = getopt.getopt(sys.argv[1:], "h")
134 sesstype = fulbank.fsb.session
136 sys.stderr.write("netbank: %s: unknown bank id\n" % (args[0]))
138 sesspath = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, ".cache/fulbank", args[0])
142 if os.path.exists(sesspath):
143 sess = sesstype.load(sesspath)
147 commands[cmd](cmd, args)
149 sys.stderr.write("netbank: %s: unknown command\n" % (cmd))
152 sessdir = os.path.dirname(sesspath)
153 if not os.path.isdir(sessdir):
157 if os.path.exists(sesspath):
161 if __name__ == "__main__":
163 except KeyboardInterrupt: