-
Notifications
You must be signed in to change notification settings - Fork 4
/
payback.lua
329 lines (258 loc) · 12.5 KB
/
payback.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
-- ---------------------------------------------------------------------------------------------------------------------
--
-- MoneyMoney Web Banking Extension
-- http://moneymoney-app.com/api/webbanking
--
--
-- The MIT License (MIT)
--
-- Copyright (c) 2012-2016 MRH applications GmbH
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- ---------------------------------------------------------------------------------------------------------------------
-- ---------------------------------------------------------------------------------------------------------------------
--
-- Get portfolio of Payback online account.
--
-- ATTENTION: This extension requires MoneyMoney version 2.2.2 or higher
--
-- ---------------------------------------------------------------------------------------------------------------------
-- ---------------------------------------------------------------------------------------------------------------------
-- Common MoneyMoney extension informations
-- ---------------------------------------------------------------------------------------------------------------------
WebBanking {
version = 2.11,
country = "de",
url = "https://www.payback.de/login#loginSecureTab",
services = {"Payback-Punkte"},
description = string.format(MM.localizeText("Get points of %s"), "Payback account")
}
-- ---------------------------------------------------------------------------------------------------------------------
-- Helper functions
-- ---------------------------------------------------------------------------------------------------------------------
local function strToAmount(str)
-- Helper function for converting localized amount strings to Lua numbers.
print("raw value: ".. str)
local convertedValue = string.gsub(string.gsub(string.gsub(str, " .+", ""), "%.", ""), ",", ".")
print("converted value " .. convertedValue)
return convertedValue
end
--Helper for priniting nested table
local function deep_print(tbl)
for i, v in pairs(tbl) do
if type(v) == "table" then
deep_print(v)
else
print(i, v)
end
end
end
-- ---------------------------------------------------------------------------------------------------------------------
local function strToAmountWithDefault(str, defaultValue)
-- Helper function for converting localized amount strings to Lua numbers with a default value.
local value = strToAmount(str)
if value == nil or value == "" then
value = defaultValue
end
return value
end
-- ---------------------------------------------------------------------------------------------------------------------
local function strToDate(str)
-- Helper function for converting localized date strings to timestamps.
local d, m, y = string.match(str, "(%d%d)%.(%d%d)%.(%d%d%d%d)")
if d and m and y then
return os.time { year = y, month = m, day = d, hour = 0, min = 0, sec = 0 }
end
end
-- ---------------------------------------------------------------------------------------------------------------------
local function printElementWithPrefix(prefix, element)
-- Helper function for debugging HTML elements with a prtinable prefix
if element:children():length() >= 1 then
element:children():each(function(index, element2)
local newPrefix = prefix .. "-" .. index
print(newPrefix .. "=" .. element2:text())
printElementWithPrefix(newPrefix, element2)
end)
end
end
-- ---------------------------------------------------------------------------------------------------------------------
local function strToFullDate (str)
-- Helper function for converting localized date strings to timestamps.
local d, m, y = string.match(str, "(%d%d).(%d%d).(%d%d%d%d)")
return os.time{year=y, month=m, day=d}
end
local function printElement(element)
-- Helper function for debugging HTML elements
printElementWithPrefix('0', element)
end
-- ---------------------------------------------------------------------------------------------------------------------
-- The following variables are used to save state.
-- ---------------------------------------------------------------------------------------------------------------------
local connection
local overview_html
-- ---------------------------------------------------------------------------------------------------------------------
--
-- MoneyMoney API Extension
--
-- @see: http://moneymoney-app.com/api/webbanking/
--
-- ---------------------------------------------------------------------------------------------------------------------
function SupportsBank(protocol, bankCode)
-- Using artificial bankcode to identify the DWS Investments group.
return bankCode == "Payback-Punkte" and protocol == ProtocolWebBanking
end
-- ---------------------------------------------------------------------------------------------------------------------
function InitializeSession(protocol, bankCode, username, customer, password)
print("InitializeSession with " .. protocol .. " connecting " .. url .. " with ".. username)
MM.printStatus("Start to login for user ".. username)
-- Create HTTPS connection object.
connection = Connection()
connection.language = "de-de"
-- just ask the mpm to get a userId--
--local request = connection:get("https://mpm.payback.de/js?wp_id=3125530");
-- Fetch login page.
local loginPage = HTML(connection:get(url))
-- Fill in login credentials.
loginPage:xpath("//*[@id='aliasInputSecure']"):attr("value", username)
loginPage:xpath("//*[@id='passwordInput']"):attr("value", password)
MM.printStatus("parameters for login filled in - username = " .. username);
local loginForm = loginPage:xpath("//form[@name='loginForm']");
tprint(loginForm, 2);
-- Submit login form.
local response, code, headers, status = connection:request(loginForm:submit())
-- local response, code, headers, status = connection:request(loginPage:xpath("//input[@id='loginSubmitButtonSecure']"):click())
MM.printStatus("status code " ..code)
MM.printStatus("headers " ..headers)
MM.printStatus("status " ..status)
MM.printStatus("login response " ..response)
overview_html = HTML(response)
-- Submit login form.
-- MM.printStatus("request " ..request)
-- overview_html = HTML(request)
-- Check for failed login.
local failure = overview_html:xpath("//*[@id='errorNotification']")
if failure:length() > 0 then
print("Login failed. Reason: " .. failure:xpath("//*p[@class='MsoNormal']"))
MM.printStatus("Login failed...");
return LoginFailed
end
MM.printStatus("Login success- go to correct paypack page ");
-- hard coded point url ...
overview_html = HTML(connection:get("https://www.payback.de/pb/punktekonto/id/13598/"))
print("Session initialization completed successfully.")
MM.printStatus("Login successfull...")
return nil
end
-- ---------------------------------------------------------------------------------------------------------------------
function ListAccounts(knownAccounts)
local accountNumber = overview_html:xpath("//p[text()='Kundennummer:']/span"):text();
-- Supports only one account
local account = {
owner = overview_html:xpath("//*/p[@class='welcome-msg']/strong"):text(),
name = "Paypack Punkte Konto (" .. accountNumber .. ")",
accountNumber = accountNumber,
portfolio = false,
currency = "EUR",
type = AccountTypeUnknown
}
return { account }
end
-- ---------------------------------------------------------------------------------------------------------------------
function RefreshAccount(account, since)
local transactions = {}
-- the datefields can be filled directly
overview_html:xpath("//input[@id='date1']"):attr("value", os.date("%d.%m.%Y", since))
overview_html:xpath("//input[@id='date2']"):attr("value", os.date("%d.%m.%Y"))
MM.printStatus("Fill in date ranges" )
print("Submitting transaction search form for " .. account.accountNumber)
-- local form = overview_html:xpath("//form[@id='pointRangeForm']")
--overview_html = HTML(form):submit()
-- MM.printStatus("Form for pointRangeForm: " .. deep_print(form))
-- local response = connection:request(overview_html:xpath("//input[@title='Anzeigen']"):click())
overview_html = HTML(connection:request(overview_html:xpath("//input[@title='Anzeigen']"):click()))
-- Get paypack points from text next to select box
local balance = overview_html:xpath("//span[@id='serverPoints']"):text()
-- eleminate the dot in the point number and divide it with 100 to get the euro equivalent
balance = string.gsub(balance,"%.","")/100
MM.printStatus("balance " .. balance)
local firstPage =true;
repeat
local noMorePages = true;
-- Check if the HTML table with transactions exists.
if overview_html:xpath("//table[@class='mypoints']/tbody/tr[1]/td[1]"):length() > 0 then
-- Extract transactions.
overview_html:xpath("//table[@class='mypoints']/tbody/tr[position()>0]"):each(function (index, row)
local columns = row:children()
local transaction = {
valueDate = strToFullDate(columns:get(1):text()),
bookingDate = strToFullDate(columns:get(1):text()),
name = columns:get(2):text(),
purpose = columns:get(3):text() .. " : " .. columns:get(4):text(), true,
currency = "EUR",
amount = strToAmount(columns:get(4):text(), true)/100
}
table.insert(transactions, transaction)
end)
local linkCounter
if firstPage then
linkCounter = 1
else
linkCounter = 2
end
local nextPageLink = overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]");
-- check website for more pages to extract transactions for
if nextPageLink:length()> 0 then
local link = overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]")
overview_html = HTML(connection:request(overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]"):click()))
noMorePages = false;
firstPage=false;
MM.printStatus("Getting more transactions...")
end
end
until (noMorePages);
-- Return balance and array of transactions.
return {balance=balance, transactions=transactions, securities=nil}
end
-- ---------------------------------------------------------------------------------------------------------------------
function EndSession()
-- Submit logout form.
local logout_html = HTML(connection:request(overview_html:xpath("//a[@id='pbLogin']"):click()))
print("Logged out successfully!")
end
-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tprint(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
elseif type(v) == 'function' then
print(formatting .. tostring(v))
elseif type(v) == 'userdata' then
print(formatting .. tostring(v))
else
print(formatting .. v)
end
end
end