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":
63 sys.stderr.write("usage: login bankid USER-ID\n")
65 with auth.ttyconv() as conv:
67 sess.auth_bankid(args[1], conv)
68 except auth.autherror as err:
69 sys.stderr.write("netbank: authentication failed: %s\n" % err)
72 sys.stderr.write("netbank: %s: unknown authentication type\n" % (args[0]))
74 commands["login"] = cmd_login
77 def cmd_logout(cmd, args):
82 commands["logout"] = cmd_logout
85 def cmd_ping(cmd, args):
87 commands["ping"] = cmd_ping
90 def cmd_lsacct(cmd, args):
91 for acct in sess.accounts:
92 sys.stdout.write("%s (%s): %s\n" % (acct.number, acct.name, acct.balance))
93 commands["lsacct"] = cmd_lsacct
96 def cmd_lstxn(cmd, args):
97 opts, args = getopt.getopt(args, "n:")
103 sys.stderr.write("usage: lstxn [-n NUM] ACCOUNT\n")
106 acct = find(sess.accounts, item=args[0], key=lambda acct: acct.number, test=pfxmatch)
107 except ambiguous as exc:
108 sys.stderr.write("netbank: %s: ambiguous match between %s and %s\n" % (args[0], exc.a, exc.b))
111 sys.stderr.write("netbank: %s: no such account\n" % (args[0]))
113 for i, txn in zip(range(num), acct.transactions()):
114 sys.stdout.write("%s %s: %s\n" % (txn.date.isoformat(), txn.value, txn.message))
115 commands["lstxn"] = cmd_lstxn
118 global sess, sesstype
120 opts, args = getopt.getopt(sys.argv[1:], "h")
131 sesstype = fulbank.fsb.session
133 sys.stderr.write("netbank: %s: unknown bank id\n" % (args[0]))
135 sesspath = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, ".cache/fulbank", args[0])
139 if os.path.exists(sesspath):
140 sess = sesstype.load(sesspath)
144 commands[cmd](cmd, args)
146 sys.stderr.write("netbank: %s: unknown command\n" % (cmd))
149 sessdir = os.path.dirname(sesspath)
150 if not os.path.isdir(sessdir):
154 if os.path.exists(sesspath):
158 if __name__ == "__main__":
160 except KeyboardInterrupt: