Improved transactions.
[fulbank.git] / fulbank / fsb.py
1 import json, http.cookiejar, binascii, time, datetime, pickle, hashlib
2 from urllib import request, parse
3 from bs4 import BeautifulSoup as soup
4 from . import currency
5 soupify = lambda cont: soup(cont, "html.parser")
6
7 apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
8 loginurl = "https://online.swedbank.se/app/privat/login"
9 serviceid = "B7dZHQcY78VRVz9l"
10
11 class fmterror(Exception):
12     pass
13
14 class autherror(Exception):
15     pass
16
17 def resolve(d, keys, default=fmterror):
18     def err():
19         if default is fmterror:
20             raise fmterror()
21         return default
22     def rec(d, keys):
23         if len(keys) == 0:
24             return d
25         if isinstance(d, dict):
26             if keys[0] not in d:
27                 return err()
28             return rec(d[keys[0]], keys[1:])
29         else:
30             return err()
31     return rec(d, keys)
32
33 def linkurl(ln):
34     if ln[0] != '/':
35         raise fmterror("unexpected link url: " + ln)
36     return parse.urljoin(apibase, ln[1:])
37
38 def getdsid():
39     with request.urlopen(loginurl) as resp:
40         if resp.code != 200:
41             raise fmterror("Unexpected HTTP status code: " + str(resp.code))
42         doc = soupify(resp.read())
43     dsel = doc.find("div", id="cust-sess-id")
44     if not dsel or not dsel.has_attr("value"):
45         raise fmterror("DSID DIV not on login page")
46     return dsel["value"]
47
48 def base64(data):
49     return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
50
51 class transaction(object):
52     def __init__(self, account, data):
53         self.account = account
54         self._data = data
55
56     _datefmt = "%Y-%m-%d"
57
58     @property
59     def value(self): return currency.currency.get(resolve(self._data, ("currency",))).parse(resolve(self._data, ("amount",)))
60     @property
61     def message(self): return resolve(self._data, ("description",))
62     @property
63     def date(self):
64         p = time.strptime(resolve(self._data, ("accountingDate",)), self._datefmt)
65         return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
66
67     @property
68     def hash(self):
69         dig = hashlib.sha256()
70         dig.update(str(self.date.toordinal()).encode("ascii") + b"\0")
71         dig.update(self.message.encode("utf-8") + b"\0")
72         dig.update(str(self.value.amount).encode("ascii") + b"\0")
73         dig.update(self.value.currency.symbol.encode("ascii") + b"\0")
74         return dig.hexdigest()
75
76     def __repr__(self):
77         return "#<fsb.transaction %s: %r>" % (self.value, self.message)
78
79 class account(object):
80     def __init__(self, sess, id, idata):
81         self.sess = sess
82         self.id = id
83         self._data = None
84         self._idata = idata
85
86     @property
87     def data(self):
88         if self._data is None:
89             self._data = self.sess._jreq("v5/engagement/account/" + self.id)
90         return self._data
91
92     @property
93     def number(self): return resolve(self.data, ("accountNumber",))
94     @property
95     def clearing(self): return resolve(self.data, ("clearingNumber",))
96     @property
97     def fullnumber(self): return resolve(self.data, ("fullyFormattedNumber",))
98     @property
99     def name(self): return resolve(self._idata, ("name",))
100
101     def transactions(self):
102         pagesz = 50
103         page = 1
104         while True:
105             data = self.sess._jreq("v5/engagement/transactions/" + self.id, transactionsPerPage=pagesz, page=page)
106             txlist = resolve(data, ("transactions",))
107             if len(txlist) < 1:
108                 break
109             for tx in txlist:
110                 yield transaction(self, tx)
111             page += 1
112
113     def __repr__(self):
114         return "#<fsb.account %s: %r>" % (self.fullnumber, self.name)
115
116 class session(object):
117     def __init__(self, dsid):
118         self.dsid = dsid
119         self.auth = base64((serviceid + ":" + str(int(time.time() * 1000))).encode("ascii"))
120         self.jar = request.HTTPCookieProcessor()
121         self.jar.cookiejar.set_cookie(http.cookiejar.Cookie(
122             version=0, name="dsid", value=dsid, path="/", path_specified=True,
123             domain=".online.swedbank.se", domain_specified=True, domain_initial_dot=True,
124             port=None, port_specified=False, secure=False, expires=None,
125             discard=True, comment=None, comment_url=None,
126             rest={}, rfc2109=False))
127         self.userid = None
128         self._accounts = None
129
130     def _req(self, url, data=None, ctype=None, headers={}, method=None, **kws):
131         if "dsid" not in kws:
132             kws["dsid"] = self.dsid
133         kws = {k: v for (k, v) in kws.items() if v is not None}
134         url = parse.urljoin(apibase, url + "?" + parse.urlencode(kws))
135         if isinstance(data, dict):
136             data = json.dumps(data).encode("utf-8")
137             ctype = "application/json;charset=UTF-8"
138         req = request.Request(url, data=data, method=method)
139         for hnam, hval in headers.items():
140             req.add_header(hnam, hval)
141         if ctype is not None:
142             req.add_header("Content-Type", ctype)
143         req.add_header("Authorization", self.auth)
144         self.jar.https_request(req)
145         with request.urlopen(req) as resp:
146             if resp.code != 200 and resp.code != 201:
147                 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
148             self.jar.https_response(req, resp)
149             return resp.read()
150
151     def _jreq(self, *args, **kwargs):
152         headers = kwargs.pop("headers", {})
153         headers["Accept"] = "application/json"
154         ret = self._req(*args, headers=headers, **kwargs)
155         return json.loads(ret.decode("utf-8"))
156
157     def _postlogin(self):
158         auth = self._jreq("v5/user/authenticationinfo")
159         uid = auth.get("identifiedUser", "")
160         if uid == "":
161             raise fmterror("no identified user even after successful authentication")
162         self.userid = uid
163         prof = self._jreq("v5/profile/")
164         if len(prof["banks"]) != 1:
165             raise fmterror("do not know the meaning of multiple banks")
166         rolesw = linkurl(resolve(prof["banks"][0], ("privateProfile", "links", "next", "uri")))
167         self._jreq(rolesw, method="POST")
168
169     def auth_bankid(self, user):
170         data = self._jreq("v5/identification/bankid/mobile", data = {
171             "userId": user,
172             "useEasyLogin": False,
173             "generateEasyLoginId": False})
174         if data.get("status") != "USER_SIGN":
175             raise fmterror("unexpected bankid status: " + str(data.get("status")))
176         vfy = linkurl(resolve(data, ("links", "next", "uri")))
177         while True:
178             time.sleep(3)
179             vdat = self._jreq(vfy)
180             st = vdat.get("status")
181             if st == "USER_SIGN":
182                 continue
183             elif st == "CLIENT_NOT_STARTED":
184                 continue
185             elif st == "COMPLETE":
186                 self._postlogin()
187                 return
188             elif st == "CANCELLED":
189                 raise autherror("authentication cancelled")
190             else:
191                 raise fmterror("unexpected bankid status: " + str(st))
192
193     def keepalive(self):
194         data = self._jreq("v5/framework/clientsession")
195         return data["timeoutInMillis"] / 1000
196
197     @property
198     def accounts(self):
199         if self._accounts is None:
200             data = self._jreq("v5/engagement/overview")
201             accounts = []
202             for acct in resolve(data, ("transactionAccounts",)):
203                 accounts.append(account(self, resolve(acct, ("id",)), acct))
204             self._accounts = accounts
205         return self._accounts
206
207     def logout(self):
208         if self.userid is not None:
209             self._jreq("v5/identification/logout", method="PUT")
210             self.userid = None
211
212     def close(self):
213         self.logout()
214         self._req("v5/framework/clientsession", method="DELETE")
215
216     def __enter__(self):
217         return self
218
219     def __exit__(self, *excinfo):
220         self.close()
221         return False
222
223     def __repr__(self):
224         if self.userid is not None:
225             return "#<fsb.session %s>" % self.userid
226         return "#<fsb.session>"
227
228     @classmethod
229     def create(cls):
230         return cls(getdsid())
231
232     def save(self, filename):
233         with open(filename, "wb") as fp:
234             pickle.dump(self, fp)
235
236     @classmethod
237     def load(cls, filename):
238         with open(filename, "rb") as fp:
239             return picke.load(fp)