forked from eshaham/israeli-bank-scrapers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-scraper.ts
222 lines (184 loc) · 5.84 KB
/
base-scraper.ts
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
import { EventEmitter } from 'events';
import { Browser, Page } from 'puppeteer';
import moment from 'moment-timezone';
import { TimeoutError } from '../helpers/waiting';
import { TransactionsAccount } from '../transactions';
import { CompanyTypes } from '../definitions';
const SCRAPE_PROGRESS = 'SCRAPE_PROGRESS';
export enum ScraperErrorTypes {
InvalidPassword ='INVALID_PASSWORD',
ChangePassword = 'CHANGE_PASSWORD',
Timeout = 'TIMEOUT',
AccountBlocked = 'ACCOUNT_BLOCKED',
Generic = 'GENERIC',
General = 'GENERAL_ERROR'
}
export interface ScaperLoginResult {
success: boolean;
errorType?: ScraperErrorTypes;
errorMessage?: string; // only on success=false
}
export interface FutureDebit {
amount: number;
amountCurrency: string;
chargeDate?: string;
bankAccountNumber?: string;
}
export interface ScaperScrapingResult {
success: boolean;
accounts?: TransactionsAccount[];
futureDebits?: FutureDebit[];
errorType?: ScraperErrorTypes;
errorMessage?: string; // only on success=false
}
export type ScraperCredentials = Record<string, string>;
export interface ScraperOptions {
/**
* The company you want to scrape
*/
companyId: CompanyTypes;
/**
* include more debug info about in the output
*/
verbose?: boolean;
/**
* the date to fetch transactions from (can't be before the minimum allowed time difference for the scraper)
*/
startDate: Date;
/**
* shows the browser while scraping, good for debugging (default false)
*/
showBrowser?: boolean;
/**
* scrape transactions to be processed X months in the future
*/
futureMonthsToScrape?: number;
/**
* option from init puppeteer browser instance outside the libary scope. you can get
* browser diretly from puppeteer via `puppeteer.launch()`
*/
browser?: any;
/**
* provide a patch to local chromium to be used by puppeteer. Relevant when using
* `israeli-bank-scrapers-core` library
*/
executablePath?: string;
/**
* if set to true, all installment transactions will be combine into the first one
*/
combineInstallments?: boolean;
/**
* additional arguments to pass to the browser instance. The list of flags can be found in
*
* https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options
* https://peter.sh/experiments/chromium-command-line-switches/
*/
args?: string[];
/**
* adjust the browser instance before it is being used
*
* @param browser
*/
prepareBrowser?: (browser: Browser) => Promise<void>;
/**
* adjust the page instance before it is being used.
*
* @param page
*/
preparePage?: (page: Page) => Promise<void>;
/**
* if set, store a screenshot if failed to scrape. Used for debug purposes
*/
storeFailureScreenShotPath?: string;
/**
* if set, will set the timeout in milliseconds of puppeteer's `page.setDefaultTimeout`.
*/
defaultTimeout?: number;
}
export enum ScaperProgressTypes {
Initializing = 'INITIALIZING',
StartScraping = 'START_SCRAPING',
LoggingIn = 'LOGGING_IN',
LoginSuccess = 'LOGIN_SUCCESS',
LoginFailed = 'LOGIN_FAILED',
ChangePassword = 'CHANGE_PASSWORD',
EndScraping = 'END_SCRAPING',
Terminating = 'TERMINATING',
}
function createErrorResult(errorType: ScraperErrorTypes, errorMessage: string) {
return {
success: false,
errorType,
errorMessage,
};
}
function createTimeoutError(errorMessage: string) {
return createErrorResult(ScraperErrorTypes.Timeout, errorMessage);
}
function createGenericError(errorMessage: string) {
return createErrorResult(ScraperErrorTypes.Generic, errorMessage);
}
export class BaseScraper {
private eventEmitter = new EventEmitter();
constructor(public options: ScraperOptions) {
}
// eslint-disable-next-line @typescript-eslint/require-await
async initialize() {
this.emitProgress(ScaperProgressTypes.Initializing);
moment.tz.setDefault('Asia/Jerusalem');
}
async scrape(credentials: ScraperCredentials): Promise<ScaperScrapingResult> {
this.emitProgress(ScaperProgressTypes.StartScraping);
await this.initialize();
let loginResult;
try {
loginResult = await this.login(credentials);
} catch (e) {
loginResult = e instanceof TimeoutError ?
createTimeoutError(e.message) :
createGenericError(e.message);
}
let scrapeResult;
if (loginResult.success) {
try {
scrapeResult = await this.fetchData();
} catch (e) {
scrapeResult =
e instanceof TimeoutError ?
createTimeoutError(e.message) :
createGenericError(e.message);
}
} else {
scrapeResult = loginResult;
}
try {
const success = scrapeResult && scrapeResult.success === true;
await this.terminate(success);
} catch (e) {
scrapeResult = createGenericError(e.message);
}
this.emitProgress(ScaperProgressTypes.EndScraping);
return scrapeResult;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
async login(_credentials: Record<string, string>): Promise<ScaperLoginResult> {
throw new Error(`login() is not created in ${this.options.companyId}`);
}
// eslint-disable-next-line @typescript-eslint/require-await
async fetchData(): Promise<ScaperScrapingResult> {
throw new Error(`fetchData() is not created in ${this.options.companyId}`);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
async terminate(_success: boolean) {
this.emitProgress(ScaperProgressTypes.Terminating);
}
emitProgress(type: ScaperProgressTypes) {
this.emit(SCRAPE_PROGRESS, { type });
}
emit(eventName: string, payload: Record<string, any>) {
this.eventEmitter.emit(eventName, this.options.companyId, payload);
}
onProgress(func: (...args: any[]) => void) {
this.eventEmitter.on(SCRAPE_PROGRESS, func);
}
}