-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
171 lines (149 loc) · 5.25 KB
/
background.js
File metadata and controls
171 lines (149 loc) · 5.25 KB
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
// Background script to handle API requests
console.log("AutoTrader Background Script loaded");
// Listen for messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "fetchOwnership") {
console.log("Fetching ownership for", message.cars.length, "cars");
fetchAllOwnership(message.cars, sender.tab.id);
sendResponse({ status: "started" });
}
});
// Fetch ownership information for all cars
async function fetchAllOwnership(cars, tabId) {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (let i = 0; i < cars.length; i++) {
const car = cars[i];
console.log(
`Fetching ownership for car ${i + 1}/${cars.length}: ${car.id}`,
);
try {
const ownershipData = await fetchCarOwnership(car.id);
// Send update to content script
chrome.tabs.sendMessage(tabId, {
action: "ownershipUpdate",
carId: car.id,
ownership: ownershipData,
});
} catch (error) {
console.error(`Error fetching ownership for car ${car.id}:`, error);
// Send error to content script
chrome.tabs.sendMessage(tabId, {
action: "ownershipUpdate",
carId: car.id,
ownership: { error: error.message },
});
}
// Add delay between requests to be respectful to the server
if (i < cars.length - 1) {
await delay(500); // Reduced from 1000ms to 500ms for faster processing
}
}
// Notify completion
chrome.tabs.sendMessage(tabId, {
action: "ownershipComplete",
});
}
// Fetch ownership information for a single car
async function fetchCarOwnership(carId) {
const apiUrl = `https://www.autotrader.co.uk/product-page/v1/advert/${carId}?channel=cars&postcode=NW10%207EG`;
try {
console.log(`Fetching: ${apiUrl}`);
const response = await fetch(apiUrl, {
method: "GET",
headers: {
Accept: "application/json",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Data received for car ${carId}:`, data);
return extractOwnershipInfo(data);
} catch (error) {
console.error(`Failed to fetch ownership for car ${carId}:`, error);
throw error;
}
}
// Extract ownership information from the API response
function extractOwnershipInfo(data) {
const result = {};
try {
console.log("Extracting ownership info for car:", data.id);
// Check the history section for ownership data
if (data.history) {
// Check ownersData
if (data.history.ownersData) {
console.log("Found ownersData:", data.history.ownersData);
if (
data.history.ownersData.value &&
data.history.ownersData.value !== "Contact seller"
) {
const ownerMatch =
data.history.ownersData.value.match(/(\d+)\s*owner/i);
if (ownerMatch) {
result.owners = parseInt(ownerMatch[1]);
} else {
result.owners = data.history.ownersData.value;
}
} else {
result.ownerStatus = data.history.ownersData.value || "Unknown";
}
}
// Check historyItems for ownership info
if (data.history.historyItems) {
console.log("Found historyItems:", data.history.historyItems);
for (const item of data.history.historyItems) {
if (item.key === "OWNERS") {
if (item.value && item.value !== "Contact seller") {
const ownerMatch = item.value.match(/(\d+)\s*owner/i);
if (ownerMatch) {
result.owners = parseInt(ownerMatch[1]);
} else {
result.owners = item.value;
}
} else {
result.ownerStatus = item.value || "Unknown";
}
}
}
}
// Extract service history
if (data.history.serviceHistory) {
console.log("Found serviceHistory:", data.history.serviceHistory);
result.serviceHistory =
data.history.serviceHistory.description ||
data.history.serviceHistory.label;
}
}
// Also check ownershipAndHistory section
if (
data.ownershipAndHistory &&
data.ownershipAndHistory.sellerInformation
) {
const sellerInfo = data.ownershipAndHistory.sellerInformation;
if (sellerInfo.serviceHistory && sellerInfo.serviceHistory.title) {
if (!result.serviceHistory) {
result.serviceHistory = sellerInfo.serviceHistory.title.value;
}
}
}
// Look in description for ownership mentions
if (data.description && data.description.text) {
for (const text of data.description.text) {
const ownerMatch = text.match(/(\d+)\s*(?:previous\s*)?owner/i);
if (ownerMatch && !result.owners) {
result.owners = parseInt(ownerMatch[1]);
break;
}
}
}
console.log(`Final extracted ownership info:`, result);
return result;
} catch (error) {
console.error("Error extracting ownership info:", error);
return { error: "Failed to parse ownership data" };
}
}