fsb: Work around cookie processors no longer being pickleable.
[fulbank.git] / fulbank / fsb.py
CommitLineData
f78b790d 1import json, http.cookiejar, binascii, time, datetime, pickle, urllib.error
8e60b2da
FT
2from urllib import request, parse
3from bs4 import BeautifulSoup as soup
717d54fc 4from . import currency, auth, data
8e60b2da
FT
5soupify = lambda cont: soup(cont, "html.parser")
6
7apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
8loginurl = "https://online.swedbank.se/app/privat/login"
9serviceid = "B7dZHQcY78VRVz9l"
10
11class fmterror(Exception):
12 pass
13
f99c3f74 14class autherror(auth.autherror):
8e60b2da
FT
15 pass
16
f78b790d
FT
17class jsonerror(Exception):
18 def __init__(self, code, data, headers):
19 self.code = code
20 self.data = data
21 self.headers = headers
22
23 @classmethod
24 def fromerr(cls, err):
25 cs = err.headers.get_content_charset()
26 if cs is None:
27 cs = "utf-8"
28 data = json.loads(err.read().decode(cs))
29 return cls(err.code, data, err.headers)
30
8e60b2da 31def resolve(d, keys, default=fmterror):
d791f2f2 32 def err(key):
8e60b2da 33 if default is fmterror:
d791f2f2 34 raise fmterror(key)
8e60b2da
FT
35 return default
36 def rec(d, keys):
37 if len(keys) == 0:
38 return d
39 if isinstance(d, dict):
40 if keys[0] not in d:
d791f2f2
FT
41 return err(keys[0])
42 return rec(d[keys[0]], keys[1:])
43 elif isinstance(d, list):
44 if not 0 <= keys[0] < len(d):
45 return err(keys[0])
8e60b2da
FT
46 return rec(d[keys[0]], keys[1:])
47 else:
d791f2f2 48 return err(keys[0])
8e60b2da
FT
49 return rec(d, keys)
50
51def linkurl(ln):
52 if ln[0] != '/':
53 raise fmterror("unexpected link url: " + ln)
54 return parse.urljoin(apibase, ln[1:])
55
56def getdsid():
57 with request.urlopen(loginurl) as resp:
58 if resp.code != 200:
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")
64 return dsel["value"]
65
66def base64(data):
67 return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
68
717d54fc 69class transaction(data.transaction):
61fd054f
FT
70 def __init__(self, account, data):
71 self.account = account
72 self._data = data
73
8c456209
FT
74 _datefmt = "%Y-%m-%d"
75
61fd054f 76 @property
8e415ee7 77 def value(self): return currency.currency.get(resolve(self._data, ("currency",))).parse(resolve(self._data, ("amount",)))
61fd054f 78 @property
8c456209
FT
79 def message(self): return resolve(self._data, ("description",))
80 @property
81 def date(self):
82 p = time.strptime(resolve(self._data, ("accountingDate",)), self._datefmt)
83 return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
84
717d54fc 85class txnaccount(data.txnaccount):
61fd054f
FT
86 def __init__(self, sess, id, idata):
87 self.sess = sess
88 self.id = id
89 self._data = None
90 self._idata = idata
91
92 @property
93 def data(self):
94 if self._data is None:
95 self._data = self.sess._jreq("v5/engagement/account/" + self.id)
96 return self._data
97
98 @property
99 def number(self): return resolve(self.data, ("accountNumber",))
100 @property
101 def clearing(self): return resolve(self.data, ("clearingNumber",))
102 @property
103 def fullnumber(self): return resolve(self.data, ("fullyFormattedNumber",))
104 @property
0ba154d0
FT
105 def balance(self): return currency.currency.get(resolve(self.data, ("balance", "currencyCode"))).parse(resolve(self.data, ("balance", "amount")))
106 @property
61fd054f
FT
107 def name(self): return resolve(self._idata, ("name",))
108
109 def transactions(self):
110 pagesz = 50
8c456209
FT
111 page = 1
112 while True:
113 data = self.sess._jreq("v5/engagement/transactions/" + self.id, transactionsPerPage=pagesz, page=page)
114 txlist = resolve(data, ("transactions",))
115 if len(txlist) < 1:
116 break
117 for tx in txlist:
118 yield transaction(self, tx)
119 page += 1
61fd054f 120
717d54fc 121class cardtransaction(data.transaction):
d791f2f2
FT
122 def __init__(self, account, data):
123 self.account = account
124 self._data = data
125
126 _datefmt = "%Y-%m-%d"
127
128 @property
129 def value(self):
130 am = resolve(self._data, ("localAmount",))
131 return currency.currency.get(resolve(am, ("currencyCode",))).parse(resolve(am, ("amount",)))
132 @property
133 def message(self): return resolve(self._data, ("description",))
134 @property
135 def date(self):
136 p = time.strptime(resolve(self._data, ("date",)), self._datefmt)
137 return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
138
717d54fc 139class cardaccount(data.cardaccount):
d791f2f2
FT
140 def __init__(self, sess, id, idata):
141 self.sess = sess
142 self.id = id
143 self._data = None
144 self._idata = idata
145
146 @property
147 def data(self):
148 if self._data is None:
149 self._data = self.sess._jreq("v5/engagement/cardaccount/" + self.id)
150 return self._data
151
152 @property
153 def number(self): return resolve(self.data, ("cardAccount", "cardNumber"))
154 @property
155 def balance(self):
156 cc = resolve(self.data, ("transactions", 0, "localAmount", "currencyCode"))
157 return currency.currency.get(cc).parse(resolve(self.data, ("cardAccount", "currentBalance")))
158 @property
159 def name(self): return resolve(self._idata, ("name",))
160
161 def transactions(self):
162 pagesz = 50
163 page = 1
164 while True:
165 data = self.sess._jreq("v5/engagement/cardaccount/" + self.id, transactionsPerPage=pagesz, page=page)
166 txlist = resolve(data, ("transactions",))
167 if len(txlist) < 1:
168 break
169 for tx in txlist:
170 yield cardtransaction(self, tx)
171 page += 1
172
8e60b2da
FT
173class session(object):
174 def __init__(self, dsid):
175 self.dsid = 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))
184 self.userid = None
61fd054f 185 self._accounts = None
8e60b2da
FT
186
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:
61fd054f 203 if resp.code != 200 and resp.code != 201:
8e60b2da
FT
204 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
205 self.jar.https_response(req, resp)
206 return resp.read()
207
208 def _jreq(self, *args, **kwargs):
209 headers = kwargs.pop("headers", {})
210 headers["Accept"] = "application/json"
f78b790d
FT
211 try:
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)
8e60b2da
FT
216 return json.loads(ret.decode("utf-8"))
217
61fd054f
FT
218 def _postlogin(self):
219 auth = self._jreq("v5/user/authenticationinfo")
220 uid = auth.get("identifiedUser", "")
221 if uid == "":
222 raise fmterror("no identified user even after successful authentication")
223 self.userid = uid
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")
229
f4de0bf1
FT
230 def auth_bankid(self, user, conv=None):
231 if conv is None:
232 conv = auth.default()
f78b790d
FT
233 try:
234 data = self._jreq("v5/identification/bankid/mobile", data = {
235 "userId": user,
236 "useEasyLogin": False,
237 "generateEasyLoginId": False})
238 except jsonerror as e:
239 if e.code == 400:
240 flds = resolve(e.data, ("errorMessages", "fields"), False)
241 if isinstance(flds, list):
242 for fld in flds:
243 if resolve(fld, ("field",), None) == "userId":
244 raise autherror(fld["message"])
245 raise
8cda37c5 246 st = data.get("status")
8e60b2da 247 vfy = linkurl(resolve(data, ("links", "next", "uri")))
f4de0bf1 248 fst = None
8e60b2da 249 while True:
f4de0bf1
FT
250 if st in {"USER_SIGN", "CLIENT_NOT_STARTED"}:
251 if st != fst:
252 conv.message("Status: %s" % (st,), auth.conv.msg_info)
253 fst = st
8e60b2da 254 elif st == "COMPLETE":
61fd054f 255 self._postlogin()
8e60b2da
FT
256 return
257 elif st == "CANCELLED":
258 raise autherror("authentication cancelled")
86601bc0
FT
259 elif st == "OUTSTANDING_TRANSACTION":
260 raise autherror("another bankid transaction already in progress")
8e60b2da
FT
261 else:
262 raise fmterror("unexpected bankid status: " + str(st))
8cda37c5
FT
263 time.sleep(3)
264 vdat = self._jreq(vfy)
265 st = vdat.get("status")
8e60b2da 266
61fd054f
FT
267 def keepalive(self):
268 data = self._jreq("v5/framework/clientsession")
269 return data["timeoutInMillis"] / 1000
270
271 @property
272 def accounts(self):
273 if self._accounts is None:
274 data = self._jreq("v5/engagement/overview")
275 accounts = []
276 for acct in resolve(data, ("transactionAccounts",)):
d791f2f2
FT
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))
61fd054f
FT
280 self._accounts = accounts
281 return self._accounts
282
8e60b2da
FT
283 def logout(self):
284 if self.userid is not None:
285 self._jreq("v5/identification/logout", method="PUT")
286 self.userid = None
287
288 def close(self):
289 self.logout()
290 self._req("v5/framework/clientsession", method="DELETE")
291
db4731c6
FT
292 def __getstate__(self):
293 state = dict(self.__dict__)
294 state["jar"] = list(state["jar"].cookiejar)
295 return state
296
297 def __setstate__(self, state):
298 jar = request.HTTPCookieProcessor()
299 for cookie in state["jar"]:
300 jar.cookiejar.set_cookie(cookie)
301 state["jar"] = jar
302 self.__dict__.update(state)
303
8e60b2da
FT
304 def __enter__(self):
305 return self
306
307 def __exit__(self, *excinfo):
308 self.close()
309 return False
310
61fd054f
FT
311 def __repr__(self):
312 if self.userid is not None:
313 return "#<fsb.session %s>" % self.userid
314 return "#<fsb.session>"
315
8e60b2da
FT
316 @classmethod
317 def create(cls):
318 return cls(getdsid())
61fd054f
FT
319
320 def save(self, filename):
321 with open(filename, "wb") as fp:
322 pickle.dump(self, fp)
323
324 @classmethod
325 def load(cls, filename):
326 with open(filename, "rb") as fp:
c526374d 327 return pickle.load(fp)