-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontent.js
382 lines (357 loc) · 17.4 KB
/
content.js
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
372
373
374
375
376
377
378
379
380
381
382
async function runAfterModalLoaded() {
const modal = document.querySelector("ul.is-modal");
if (modal) {
console.log(modal.children.length);
let total = 0;
let count = 0;
if (modal.children.length >= 10) {
for (let item of modal.children) {
const price = parseFloat(item?.children[3]?.innerText.replace("$", "")) || 0;
if (!isNaN(price)) {
total += price;
count++;
if (count === 10) {
return total / count;
}
}
}
}
return count > 10 ? total / count : 0;
}
else return 0;
}
function observeModalLoading() {
return new Promise((resolve, reject) => {
const observer = new MutationObserver((mutationsList, observer) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
const modal = document.querySelector("ul.is-modal");
if (modal) {
observer.disconnect(); // Stop observing once the modal is found
const averagePrice = runAfterModalLoaded();
resolve(averagePrice);
break;
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
// Timeout to stop observing after 30 seconds
setTimeout(() => {
observer.disconnect();
reject(new Error('Modal did not load within timeout period.'));
}, 30000);
});
}
function activateModalAndObserve() {
return new Promise((resolve, reject) => {
const modalButton = document.querySelector(".modal__activator");
if (modalButton) {
modalButton.click();
observeModalLoading().then(resolve).catch(reject);
} else {
reject(new Error('.modal__activator button not found'));
}
});
}
function scrapeOrderFromCurrentPage() {
try {
const OrderNumbers = Array.from(document.querySelectorAll('td[data-label="Order #"]'))
.map(lineElement => lineElement.children[0].children[0].children[0].innerText);
const buyerNames = Array.from(document.querySelectorAll('td[data-label="Buyer Name"]'))
.map(buyerElement => buyerElement.innerText);
const orderDates = Array.from(document.querySelectorAll('td[data-label="Order Date"]'))
.map(dateElement => dateElement.innerText);
const statuses = Array.from(document.querySelectorAll('td[data-label="Status"]'))
.map(statusElement => statusElement.innerText);
const shippingTypes = Array.from(document.querySelectorAll('td[data-label="Shipping Type"]'))
.map(typeElement => typeElement.innerText);
const ProductAmts = Array.from(document.querySelectorAll('td[data-label="Product Amt"]'))
.map(productAmtElement => productAmtElement.innerText);
const shippingAmts = Array.from(document.querySelectorAll('td[data-label="Shipping Amt"]'))
.map(shippingAmtElement => shippingAmtElement.innerText);
const totalAmts = Array.from(document.querySelectorAll('td[data-label="Total Amt"]'))
.map(totalAmtElement => totalAmtElement.innerText);
const buyerPaids = Array.from(document.querySelectorAll('td[data-label="BuyerPaid"]'))
.map(buyerPaidElement => buyerPaidElement.innerText);
const links = Array.from(document.querySelectorAll('td[data-label="Order #"]'))
.map(lineElement => lineElement.children[0].children[0].children[0].getAttribute('href'));
const data = OrderNumbers.map((OrderNumber, index) => ({
OrderNumber,
buyerName: buyerNames[index] || null,
orderDate: orderDates[index] || null,
status: statuses[index] || null,
shippingType: shippingTypes[index] || null,
productAmt: ProductAmts[index] || null,
shippingAmt: shippingAmts[index] || null,
totalAmt: totalAmts[index] || null,
buyerPaid: buyerPaids[index] || null,
link: links[index] || null
}));
chrome.runtime.sendMessage({ action: 'scrapedOrder', data: data });
} catch (error) {
console.error('Error scraping order:', error);
}
}
function GetAllOrdersByNextPage() {
const nextPageButton = document.querySelector('a.pagination-next');
const pageListItem = document.querySelector('.pagination-list>li');
console.log(pageListItem);
scrapeOrderFromCurrentPage();
if (nextPageButton) {
setTimeout(() => {
nextPageButton.click();
scrapeOrderFromCurrentPage();
GetAllOrdersByNextPage();
}, 5000);
} else {
window.close();
}
}
function scrapeInventory() {
setTimeout(() => {
// Check if there's a next button to click
const nextBtn = document.querySelector("div.pager").lastElementChild.previousElementSibling;
const disabled = document.querySelector("a.ui-state-disabled.ui-corner-tl.ui-corner-bl");
const links = Array.from(document.querySelectorAll('span[data-bind="text: ProductName"]'))
.map(nameElement => nameElement.parentElement.getAttribute("href")).filter(item => item !== null);
const inStocks = Array.from(document.querySelectorAll('span[data-bind="text: InStock"]'))
.map(stockElement => stockElement.innerText);
const data = links.map((link, index) => ({
link: links[index] || null,
inStock: inStocks[index] || null
}));
chrome.runtime.sendMessage({
action: 'MyInventory',
data: data,
message: 'success getMyInventory'
});
if (!disabled || disabled.innerText === 'First') {
nextBtn.click();
} else if (disabled.innerText === 'Last') {
chrome.runtime.sendMessage({ action: 'EndCatalog' });
window.close();
}
}, 4000)
}
window.addEventListener('load', () => {
if (window.location.href.includes("https://www.tcgplayer.com/login")) {
chrome.storage.local.get(['credential'], (result) => {
console.log(result.credential);
if (emailInput && passwordInput) {
emailInput.value = result.credential.email;
passwordInput.value = result.credential.password;
emailInput.dispatchEvent(new Event('input'));
passwordInput.dispatchEvent(new Event('input'));
const submitButton = document.querySelector('button[type="submit"]');
if (submitButton) {
submitButton.click();
} else {
console.error('Submit button not found.');
}
}
})
const emailInput = document.querySelector('input[type="email"]');
const passwordInput = document.querySelector('input[type="password"]');
}
else if (window.location.href.includes("https://www.tcgplayer.com/search")) {
setInterval(() => {
if (document.querySelector("img.blank-slate__image")) {
chrome.runtime.sendMessage({ action: 'failCard' });
window.close();
}
else {
const nextbtn = document.querySelector("a[aria-label='Next page']");
const productLines = Array.from(document.querySelectorAll('h3.product-card__category-name'))
.map(lineElement => lineElement.innerText);
const rarityElements = Array.from(document.querySelectorAll('.product-card__rarity'))
.map(viewElement => viewElement.children[0].innerText);
const sets = Array.from(document.querySelectorAll('.product-card__set-name'))
.map(setElement => setElement.innerText);
const productNames = Array.from(document.querySelectorAll('span.product-card__title.truncate'))
.map(nameElement => nameElement.innerText);
const links = Array.from(document.querySelectorAll('.product-card__content'))
.map(linkElement => linkElement.children[0].getAttribute('href'));
const data = productLines.map((productLine, index) => ({
productLine,
set: sets[index] || null,
productName: productNames[index] || null,
rarity: rarityElements[index] || null,
link: links[index] || null
}));
chrome.runtime.sendMessage({ action: 'scrapedCard', data: data });
if (!document.querySelector("a.is-disabled") || document.querySelector("a.is-disabled").getAttribute("aria-label") === "Previous page") {
nextbtn.click();
}
else if (document.querySelector("a.is-disabled").getAttribute("aria-label") === "Next page") {
chrome.runtime.sendMessage({ action: 'endCardScraping' });
window.close();
}
}
}, 10000);
}
else if (window.location.href.includes('https://store.tcgplayer.com/admin/product/manage')) {
chrome.storage.local.get(['inventoryProduct', 'bulkStatus'], function (result) {
if (result.bulkStatus === 'getAllSaveInfo') {
const lowestPrice = document.querySelector('span[data-bind="formatCurrency: lowestPrice"]')?.innerText;
const lastSoldPrice = document.querySelector('span[data-bind="formatCurrency: lowestPrice"]')?.innerText;
const lastSoldShipping = document.querySelector('span[data-bind="formatCurrency: lastSoldShipping"]')?.innerText;
const marketPrice = document.querySelector('span[data-bind="formatCurrency: marketPrice"]')?.innerText;
chrome.runtime.sendMessage({
action: 'scrapeCardSaveInfo',
data: {
link: window.location.href,
lowestPrice: lowestPrice || 0,
lastSoldPrice: lastSoldPrice || 0,
lastSoldShipping: lastSoldShipping || 0,
marketPrice: marketPrice || 0
},
message: 'success'
}, function () {
console.log("scrape carddetail");
});
} else if (result.bulkStatus === "updateCard") {
console.log(result.bulkStatus, result.inventoryProduct);
const productName = document.querySelector('span[data-bind="text: productName"]').innerText;
const inputField1 = document.querySelector('span[data-bind="validationMessage: newPrice"]').previousElementSibling;
const inputField2 = document.querySelector('span[data-bind="validationMessage: quantity"]').previousElementSibling;
Object.keys(result.inventoryProduct).forEach((item, index) => {
if (item === productName) {
inputField1.value = result.inventoryProduct[item].price;
inputField2.value = result.inventoryProduct[item].count;
inputField1.dispatchEvent(new Event('input'));
inputField2.dispatchEvent(new Event('input'));
const saveBtn = document.querySelector('input[value="Save"]');
if (saveBtn) saveBtn.click();
}
});
chrome.runtime.sendMessage({
action: 'updatecard',
link: window.location.href,
message: 'success'
}, function () {
console.log("card update");
});
} else if (result.bulkStatus === "fetchInventory") {
const inputField1 = document.querySelector('span[data-bind="validationMessage: newPrice"]').previousElementSibling;
chrome.runtime.sendMessage({
action: 'scrapeMyInventory',
data: {
link: window.location.href,
Price: inputField1.value,
},
message: 'success'
}, function () {
console.log("scrape Myinventory");
});
}
});
}
else if (window.location.href.includes("https://www.tcgplayer.com/product/")) {
setInterval(() => {
const selector = Array.from(document.querySelectorAll('strong'));
const ListPrices = Array.from(document.querySelectorAll('.listing-item__listing-data__info__price'));
let elementElem = null;
let rarityElem = null;
let cardCategoryElem = null;
let cardTypeElem = null;
let toplowestListPrice = null;
let mediumlowestListPrice = null;
let bottomlowestListPrice = null;
if (selector && ListPrices) {
selector.forEach((item) => {
if (item.innerText === 'Element:') elementElem = item.nextElementSibling.innerText;
if (item.innerText === 'Rarity:') rarityElem = item.nextElementSibling.innerText;
if (item.innerText === 'Card Category:') cardCategoryElem = item.nextElementSibling.innerText;
if (item.innerText === 'Card Type:') cardTypeElem = item.nextElementSibling.innerText;
});
toplowestListPrice = ListPrices[2]?.innerText || '0$';
mediumlowestListPrice = ListPrices[1]?.innerText || '0$';
bottomlowestListPrice = ListPrices[0]?.innerText || '0$';
activateModalAndObserve().then(averagePrice => {
chrome.runtime.sendMessage({
action: 'cardDetail',
data: {
element: elementElem,
cardCategory: cardCategoryElem,
cardType: cardTypeElem,
rarity: rarityElem,
link: window.location.href,
latestPriceAverage: averagePrice,
toplowestListPrice: parseFloat(toplowestListPrice.replace("$", "")) || 0,
mediumlowestListPrice: parseFloat(mediumlowestListPrice.replace("$", "")) || 0,
bottomlowestListPrice: parseFloat(bottomlowestListPrice.replace("$", "")) || 0
},
message: 'success getCardDetail'
});
}).catch((error) => {
console.log("error");
})
}
}, 8000);
}
else if (window.location.href === "https://store.tcgplayer.com/admin/orders/orderlist") {
chrome.storage.local.get(['inventoryStatus'], function (result) {
if (result.inventoryStatus === "order") {
GetAllOrdersByNextPage();
}
});
}
else if (window.location.href === "https://store.tcgplayer.com/admin/product/catalog") {
const interval = setInterval(() => {
const myInventoryOnly = document.querySelector("input#OnlyMyInventory");
if (myInventoryOnly) {
myInventoryOnly.click();
}
const searchBtn = document.querySelector("input#Search");
if (searchBtn) {
searchBtn.click();
}
setTimeout(() => {
const addBtn = Array.from(document.querySelectorAll('a.blue-button-sm-darker'))
.filter(btnElement => btnElement.innerText === 'Add');
if (addBtn.length === 0) {
clearInterval(interval);
const scrapeMyInventory = setInterval(() => scrapeInventory(), 3000);
}
}, 3000)
}, 10000)
}
});
window.addEventListener('message', event => {
if (event.source === window && event.data.type) {
const { type, products, credential } = event.data;
switch (type) {
case 'manageMyInventory':
chrome.runtime.sendMessage({ type: 'manageMyInventory', products });
break;
case 'fetchCard':
chrome.runtime.sendMessage({ type: 'fetchCard' });
break;
case 'fetchCardDetail':
chrome.runtime.sendMessage({ type: 'fetchCardDetail', products });
break;
case 'fetchSaveInfo':
chrome.runtime.sendMessage({ type: 'fetchSaveInfo', products });
break;
case 'fetchOrder':
chrome.runtime.sendMessage({ type: 'fetchOrder' });
break;
case 'fetchSelectCardDetail':
console.log(products);
chrome.runtime.sendMessage({ type: 'fetchSelectCardDetail', products });
break;
case 'myInventoryOnly':
chrome.runtime.sendMessage({ type: 'myInventoryOnly' });
break;
case 'InventoryFetch':
chrome.runtime.sendMessage({ type: 'InventoryFetch', products });
break;
case 'sendCredential':
chrome.storage.local.set({
credential: credential
});
break;
}
}
});