1 import json, http.cookiejar, binascii, time, datetime, pickle, urllib.error
2 from urllib import request, parse
3 from bs4 import BeautifulSoup as soup
4 from . import currency, auth, data
5 soupify = lambda cont: soup(cont, "html.parser")
7 apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
8 loginurl = "https://online.swedbank.se/app/privat/login"
9 serviceid = "B7dZHQcY78VRVz9l"
11 class fmterror(Exception):
14 class autherror(auth.autherror):
17 class jsonerror(Exception):
18 def __init__(self, code, data, headers):
21 self.headers = headers
24 def fromerr(cls, err):
25 cs = err.headers.get_content_charset()
28 data = json.loads(err.read().decode(cs))
29 return cls(err.code, data, err.headers)
31 def resolve(d, keys, default=fmterror):
33 if default is fmterror:
39 if isinstance(d, dict):
42 return rec(d[keys[0]], keys[1:])
43 elif isinstance(d, list):
44 if not 0 <= keys[0] < len(d):
46 return rec(d[keys[0]], keys[1:])
53 raise fmterror("unexpected link url: " + ln)
54 return parse.urljoin(apibase, ln[1:])
57 with request.urlopen(loginurl) as resp:
59 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
60 doc = soupify(resp.read())
61 dsel = doc.find("div", id="cust-sess-id")
62 if not dsel or not dsel.has_attr("value"):
63 raise fmterror("DSID DIV not on login page")
67 return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
69 class transaction(data.transaction):
70 def __init__(self, account, data):
71 self.account = account
77 def value(self): return currency.currency.get(resolve(self._data, ("currency",))).parse(resolve(self._data, ("amount",)))
79 def message(self): return resolve(self._data, ("description",))
82 p = time.strptime(resolve(self._data, ("accountingDate",)), self._datefmt)
83 return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
85 class txnaccount(data.txnaccount):
86 def __init__(self, sess, id, idata):
94 if self._data is None:
95 self._data = self.sess._jreq("v5/engagement/account/" + self.id)
99 def number(self): return resolve(self.data, ("accountNumber",))
101 def clearing(self): return resolve(self.data, ("clearingNumber",))
103 def fullnumber(self): return resolve(self.data, ("fullyFormattedNumber",))
105 def balance(self): return currency.currency.get(resolve(self.data, ("balance", "currencyCode"))).parse(resolve(self.data, ("balance", "amount")))
107 def name(self): return resolve(self._idata, ("name",))
109 def transactions(self):
113 data = self.sess._jreq("v5/engagement/transactions/" + self.id, transactionsPerPage=pagesz, page=page)
114 txlist = resolve(data, ("transactions",))
118 yield transaction(self, tx)
121 class cardtransaction(data.transaction):
122 def __init__(self, account, data):
123 self.account = account
126 _datefmt = "%Y-%m-%d"
130 am = resolve(self._data, ("localAmount",))
131 return currency.currency.get(resolve(am, ("currencyCode",))).parse(resolve(am, ("amount",)))
133 def message(self): return resolve(self._data, ("description",))
136 p = time.strptime(resolve(self._data, ("date",)), self._datefmt)
137 return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
139 class cardaccount(data.cardaccount):
140 def __init__(self, sess, id, idata):
148 if self._data is None:
149 self._data = self.sess._jreq("v5/engagement/cardaccount/" + self.id)
153 def number(self): return resolve(self.data, ("cardAccount", "cardNumber"))
156 cc = resolve(self.data, ("transactions", 0, "localAmount", "currencyCode"))
157 return currency.currency.get(cc).parse(resolve(self.data, ("cardAccount", "currentBalance")))
159 def name(self): return resolve(self._idata, ("name",))
161 def transactions(self):
165 data = self.sess._jreq("v5/engagement/cardaccount/" + self.id, transactionsPerPage=pagesz, page=page)
166 txlist = resolve(data, ("transactions",))
170 yield cardtransaction(self, tx)
173 class session(object):
174 def __init__(self, dsid):
176 self.auth = base64((serviceid + ":" + str(int(time.time() * 1000))).encode("ascii"))
177 self.jar = request.HTTPCookieProcessor()
178 self.jar.cookiejar.set_cookie(http.cookiejar.Cookie(
179 version=0, name="dsid", value=dsid, path="/", path_specified=True,
180 domain=".online.swedbank.se", domain_specified=True, domain_initial_dot=True,
181 port=None, port_specified=False, secure=False, expires=None,
182 discard=True, comment=None, comment_url=None,
183 rest={}, rfc2109=False))
185 self._accounts = None
187 def _req(self, url, data=None, ctype=None, headers={}, method=None, **kws):
188 if "dsid" not in kws:
189 kws["dsid"] = self.dsid
190 kws = {k: v for (k, v) in kws.items() if v is not None}
191 url = parse.urljoin(apibase, url + "?" + parse.urlencode(kws))
192 if isinstance(data, dict):
193 data = json.dumps(data).encode("utf-8")
194 ctype = "application/json;charset=UTF-8"
195 req = request.Request(url, data=data, method=method)
196 for hnam, hval in headers.items():
197 req.add_header(hnam, hval)
198 if ctype is not None:
199 req.add_header("Content-Type", ctype)
200 req.add_header("Authorization", self.auth)
201 self.jar.https_request(req)
202 with request.urlopen(req) as resp:
203 if resp.code != 200 and resp.code != 201:
204 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
205 self.jar.https_response(req, resp)
208 def _jreq(self, *args, **kwargs):
209 headers = kwargs.pop("headers", {})
210 headers["Accept"] = "application/json"
212 ret = self._req(*args, headers=headers, **kwargs)
213 except urllib.error.HTTPError as e:
214 if e.headers.get_content_type() == "application/json":
215 raise jsonerror.fromerr(e)
216 return json.loads(ret.decode("utf-8"))
218 def _postlogin(self):
219 auth = self._jreq("v5/user/authenticationinfo")
220 uid = auth.get("identifiedUser", "")
222 raise fmterror("no identified user even after successful authentication")
224 prof = self._jreq("v5/profile/")
225 if len(prof["banks"]) != 1:
226 raise fmterror("do not know the meaning of multiple banks")
227 rolesw = linkurl(resolve(prof["banks"][0], ("privateProfile", "links", "next", "uri")))
228 self._jreq(rolesw, method="POST")
230 def auth_bankid(self, user, conv=None):
232 conv = auth.default()
234 data = self._jreq("v5/identification/bankid/mobile", data = {
236 "useEasyLogin": False,
237 "generateEasyLoginId": False})
238 except jsonerror as e:
240 flds = resolve(e.data, ("errorMessages", "fields"), False)
241 if isinstance(flds, list):
243 if resolve(fld, ("field",), None) == "userId":
244 raise autherror(fld["message"])
246 if data.get("status") != "USER_SIGN":
247 raise fmterror("unexpected bankid status: " + str(data.get("status")))
248 vfy = linkurl(resolve(data, ("links", "next", "uri")))
252 vdat = self._jreq(vfy)
253 st = vdat.get("status")
254 if st in {"USER_SIGN", "CLIENT_NOT_STARTED"}:
256 conv.message("Status: %s" % (st,), auth.conv.msg_info)
259 elif st == "COMPLETE":
262 elif st == "CANCELLED":
263 raise autherror("authentication cancelled")
265 raise fmterror("unexpected bankid status: " + str(st))
268 data = self._jreq("v5/framework/clientsession")
269 return data["timeoutInMillis"] / 1000
273 if self._accounts is None:
274 data = self._jreq("v5/engagement/overview")
276 for acct in resolve(data, ("transactionAccounts",)):
277 accounts.append(txnaccount(self, resolve(acct, ("id",)), acct))
278 for acct in resolve(data, ("cardAccounts",)):
279 accounts.append(cardaccount(self, resolve(acct, ("id",)), acct))
280 self._accounts = accounts
281 return self._accounts
284 if self.userid is not None:
285 self._jreq("v5/identification/logout", method="PUT")
290 self._req("v5/framework/clientsession", method="DELETE")
295 def __exit__(self, *excinfo):
300 if self.userid is not None:
301 return "#<fsb.session %s>" % self.userid
302 return "#<fsb.session>"
306 return cls(getdsid())
308 def save(self, filename):
309 with open(filename, "wb") as fp:
310 pickle.dump(self, fp)
313 def load(cls, filename):
314 with open(filename, "rb") as fp:
315 return pickle.load(fp)