-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.ts
371 lines (318 loc) · 12 KB
/
main.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import {
exportToCsv,
ListStorage,
UIContainer,
createCta,
createSpacer,
createTextSpan,
HistoryTracker,
LogCategory
} from 'browser-scraping-utils';
interface WhatsAppMember {
profileId: string
name?: string
description?: string
phoneNumber?: string
source?: string
}
function cleanName(name: string): string{
const nameClean = name.trim()
return nameClean.replace('~ ', '')
}
function cleanDescription(description: string) : string | null {
const descriptionClean = description.trim()
if(
!descriptionClean.match(/Loading About/i) &&
!descriptionClean.match(/I am using WhatsApp/i) &&
!descriptionClean.match(/Available/i)
){
return descriptionClean
}
return null;
}
class WhatsAppStorage extends ListStorage<WhatsAppMember> {
get headers() {
return [
'Phone Number',
'Name',
'Description',
'Source'
]
}
itemToRow(item: WhatsAppMember): string[]{
return [
item.phoneNumber ? item.phoneNumber : "",
item.name ? item.name : "",
item.description ? item.description : "",
item.source ? item.source : ""
]
}
}
const memberListStore = new WhatsAppStorage({
name: "whatsapp-scraper"
});
const counterId = 'scraper-number-tracker'
const exportName = 'whatsAppExport';
let logsTracker: HistoryTracker;
async function updateConter(){
// Update member tracker counter
const tracker = document.getElementById(counterId)
if(tracker){
const countValue = await memberListStore.getCount();
tracker.textContent = countValue.toString()
}
}
const uiWidget = new UIContainer();
function buildCTABtns(){
// History Tracker
logsTracker = new HistoryTracker({
onDelete: async (groupId: string) => {
// We dont have cancellable adds for now
console.log(`Delete ${groupId}`);
await memberListStore.deleteFromGroupId(groupId);
await updateConter();
},
divContainer: uiWidget.history,
maxLogs: 4
})
// Button Download
const btnDownload = createCta();
btnDownload.appendChild(createTextSpan('Download\u00A0'))
btnDownload.appendChild(createTextSpan('0', {
bold: true,
idAttribute: counterId
}))
btnDownload.appendChild(createTextSpan('\u00A0users'))
btnDownload.addEventListener('click', async function() {
const timestamp = new Date().toISOString()
const data = await memberListStore.toCsvData()
try{
exportToCsv(`${exportName}-${timestamp}.csv`, data)
}catch(err){
console.error('Error while generating export');
// @ts-ignore
console.log(err.stack)
}
});
uiWidget.addCta(btnDownload)
// Spacer
uiWidget.addCta(createSpacer())
// Button Reinit
const btnReinit = createCta();
btnReinit.appendChild(createTextSpan('Reset'))
btnReinit.addEventListener('click', async function() {
await memberListStore.clear();
logsTracker.cleanLogs();
await updateConter();
});
uiWidget.addCta(btnReinit);
// Draggable
uiWidget.makeItDraggable();
// Render
uiWidget.render()
// Initial
window.setTimeout(()=>{
updateConter()
}, 1000)
}
let modalObserver: MutationObserver;
function listenModalChanges(){
const groupNameNode = document.querySelectorAll("header span[style*='height']:not(.copyable-text)")
let source: string | null;
if(groupNameNode.length==1){
source = groupNameNode[0].textContent
}
const modalElems = document.querySelectorAll('[data-animate-modal-body="true"]');
const modalElem = modalElems[0]
const targetNode = modalElem.querySelectorAll("div[style*='height']")[1];
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = (
mutationList: MutationRecord[],
// observer: MutationObserver
) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
// console.log("A child node has been added or removed.");
if(mutation.addedNodes.length>0){
const node = mutation.addedNodes[0]
const text = node.textContent;
if(text){
const textClean = text.trim();
if(textClean.length>0){
if(
!textClean.match(/Loading About/i) &&
!textClean.match(/I am using WhatsApp/i) &&
!textClean.match(/Available/i)
){
// console.log(text)
}
}
}
}
}else if (mutation.type === "attributes") {
const target = mutation.target as HTMLElement;
const tagName = target.tagName;
// Must be a div with role="listitem"
if(
['div'].indexOf(tagName.toLowerCase())===-1 ||
target.getAttribute("role")!=="listitem"
){
continue;
}
const listItem = target;
// Use timeout to way for all data to be displayed
window.setTimeout(async ()=>{
let profileName = "";
let profileDescription = "";
let profilePhone = ""
// Name
const titleElems = listItem.querySelectorAll("span[title]:not(.copyable-text)");
if(titleElems.length>0){
const text = titleElems[0].textContent
if(text){
const name = cleanName(text);
if(name && name.length>0){
profileName = name;
}
}
}
if(profileName.length===0){
return;
}
// Description
const descriptionElems = listItem.querySelectorAll("span[title].copyable-text");
if(descriptionElems.length>0){
const text = descriptionElems[0].textContent;
if(text){
const description = cleanDescription(text);
if(description && description.length>0){
profileDescription = description;
}
}
}
// Phone
const phoneElems = listItem.querySelectorAll("span[style*='height']:not([title])");
if(phoneElems.length>0){
const text = phoneElems[0].textContent;
if(text){
const textClean = text.trim()
if(textClean && textClean.length>0){
profilePhone = textClean;
}
}
}
if(profileName){
const identifier = profilePhone ? profilePhone : profileName;
console.log(identifier)
const data: {
name?: string,
description?: string,
phoneNumber?: string,
source?: string
} = {
}
if(source){
data.source = source;
}
if(profileDescription){
data.description = profileDescription
}
if(profilePhone){
data.phoneNumber = profilePhone;
if(profileName){
data.name = profileName
}
}else{
if(profileName){
data.phoneNumber = profileName;
}
}
await memberListStore.addElem(
identifier, {
profileId: identifier,
...data
},
true // Update
)
let profileStr = profileName;
if(profilePhone){
profileStr += ` - ${profilePhone}`
}
if(profileDescription){
profileStr += ` - ${profileDescription}`
}
logsTracker.addHistoryLog({
label: `Scraping ${profileName}`,
category: LogCategory.LOG
})
updateConter()
}
}, 10)
}
}
};
// Create an observer instance linked to the callback function
modalObserver = new MutationObserver(callback);
// Start observing the target node for configured mutations
modalObserver.observe(targetNode, config);
}
function stopListeningModalChanges(){
// Later, you can stop observing
if(modalObserver){
modalObserver.disconnect();
}
}
function main(): void {
buildCTABtns();
logsTracker.addHistoryLog({
label: "Wait for modal",
category: LogCategory.LOG
})
function bodyCallback(
mutationList: MutationRecord[],
// observer: MutationObserver
){
for (const mutation of mutationList) {
// console.log(mutation)
if (mutation.type === "childList") {
if(mutation.addedNodes.length>0){
mutation.addedNodes.forEach((node)=>{
const htmlNode = node as HTMLElement
const modalElems = htmlNode.querySelectorAll('[data-animate-modal-body="true"]');
if(modalElems.length>0){
window.setTimeout(()=>{
listenModalChanges();
logsTracker.addHistoryLog({
label: "Modal found - Scroll to scrape",
category: LogCategory.LOG
})
}, 10)
}
})
}
if(mutation.removedNodes.length>0){
mutation.removedNodes.forEach((node)=>{
const htmlNode = node as HTMLElement
const modalElems = htmlNode.querySelectorAll('[data-animate-modal-body="true"]');
if(modalElems.length>0){
stopListeningModalChanges();
logsTracker.addHistoryLog({
label: "Modal Removed - Scraping Stopped",
category: LogCategory.LOG
})
}
})
}
}
}
}
const bodyConfig = { attributes: true, childList: true, subtree: true };
const bodyObserver = new MutationObserver(bodyCallback);
// Start observing the target node for configured mutations
const app = document.getElementById('app');
if(app){
bodyObserver.observe(app, bodyConfig);
}
}
main();