/
content.js
265 lines (227 loc) · 7.39 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
const TOOLS_PANEL_ID = 'kt-tools-panel';
const CLONE_BUTTON_ID = 'kt-clone-button';
const TICKET_PAGE_PATTERN = /^\/main\/ticket\/\d+/;
const SUBMITTED_STORAGE_KEY = 'kt-submited-tickets'
const SUCCESS_BUTTON_TEXT = 'Скопіювано'
const BACKEND_SERVER = 'https://1551-back.kyivcity.gov.ua';
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function sendMessagePromise(item) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(item, response => {
if (response.ok) {
resolve(response.data);
} else {
reject('Something wrong');
}
});
});
}
function fromBase64String(value) {
return Uint8Array.from(atob(value), c => c.charCodeAt(0))
}
async function waitTicketContainer() {
while (true) {
console.log('Wait for ticket container...');
const containers = document.getElementsByClassName('main-content');
if (containers.length !== 0) {
console.log('Ticket cotainer found');
return containers[0];
}
await sleep(100);
}
}
async function watchToolsPanel() {
console.log('Watch tools panel');
while (true) {
const tool = document.getElementById(TOOLS_PANEL_ID);
if (!tool) {
console.log('Tools panel not exists');
return;
}
await sleep(100);
}
}
async function waitTicketURL() {
console.log('Wait ticket URL');
while (true) {
if (location.pathname.match(TICKET_PAGE_PATTERN)) {
console.log('Ticket URL detected')
return;
}
await sleep(100);
}
}
function getTicketNumber() {
return location.pathname.match(/\d+/)[0];
}
function getClonedTickets() {
const item = localStorage.getItem(SUBMITTED_STORAGE_KEY);
if (!item) {
return [];
}
try {
return JSON.parse(item);
} catch (e) {
return [];
}
}
function getToken() {
return localStorage.getItem('token');
}
function isTicketCloned(number) {
const numbers = getClonedTickets();
return numbers.includes(number);
}
function createButtonPanel() {
const panel = document.createElement('div');
panel.className = 'kt-panel';
panel.id = TOOLS_PANEL_ID;
return panel;
}
function getAuthRequestOptions() {
const token = getToken();
return {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
'Referer': 'https://1551.gov.ua/main/create',
'DNT': 1,
},
redirect: 'error',
}
}
async function fetchTicket(number) {
const response = await fetch(`${BACKEND_SERVER}/api/tickets/${number}?include[]=files`);
return await response.json();
}
async function fetchStreetId(street) {
const url = new URL(`${BACKEND_SERVER}/api/addresses/street`);
url.search = new URLSearchParams({ name: street }).toString();
const response = await fetch(url, { ...getAuthRequestOptions() });
if (!response.ok) {
throw await response.json();
}
const { streets } = await response.json();
if (streets.length === 0) {
throw { 'street': street, 'message': 'Street not found' };
}
return streets[0].id;
}
async function fetchBuilding(streetId, number) {
const url = new URL(`${BACKEND_SERVER}/api/addresses/building`);
url.search = new URLSearchParams({ street_id: streetId, number: number }).toString();
const response = await fetch(url, { ...getAuthRequestOptions() });
if (!response.ok) {
throw await response.json();
}
const { buildings } = await response.json();
if (buildings.length === 0) {
throw { 'streetId': streetId, 'number': number, 'message': 'Building not found' };
}
return [buildings[0].district_id, buildings[0].object_id];
}
function splitTicketAddress(address) {
const parts = address.split(/,(?=(?:[^\)]*\)[^\)]*\))*[^\)]*$)/);
return [parts[0].trim(), parts.slice(1).join(',').trim()];
}
async function createTicket(number) {
const { ticket } = await fetchTicket(number);
const formData = new FormData();
if (ticket.files) {
for (const file of ticket.files) {
const filename = file.url.match(/\w+\.\w+$/)[0];
const content = await sendMessagePromise({ query: "fetchFile", url: file.url });
const arrayBuffer = fromBase64String(content.content);
const blob = new Blob([arrayBuffer], { type: content.type });
formData.append('images[]', blob, filename);
}
}
chrome.runtime.sendMessage({ content: "message from the content script" });
formData.append('subject_id', ticket.subject.id);
formData.append('description', ticket.description);
if (ticket.address) {
const [street, building] = splitTicketAddress(ticket.address);
const streetId = await fetchStreetId(street);
const [districtId, objectId] = await fetchBuilding(streetId, building);
formData.append('street', street);
formData.append('building', building);
formData.append('district_id', districtId);
formData.append('object_id', objectId);
}
if (ticket.location_lat) {
formData.append('location_lat', ticket.location_lat);
formData.append('location_lng', ticket.location_lng);
}
formData.append('private', '0');
const response = await fetch(`${BACKEND_SERVER}/api/tickets`, {
method: 'POST',
body: formData,
...getAuthRequestOptions(),
});
if (!response.ok) {
throw response.status;
}
return await response.json();
}
async function handleCloneButtonClick(evt) {
const button = evt.target;
button.setLoadingState();
try {
const number = getTicketNumber();
await createTicket(number);
const tickets = getClonedTickets();
const storageItem = JSON.stringify([...tickets, number]);
localStorage.setItem(SUBMITTED_STORAGE_KEY, storageItem);
button.setCopiedState();
} catch (e) {
alert(e);
button.setCopyState();
}
}
function createCloneButton(ticketNumber) {
const button = document.createElement('button');
button.id = CLONE_BUTTON_ID;
button.setCopyState = function() {
button.innerText = 'Скопіювати'
button.className = 'kt-button';
button.onclick = handleCloneButtonClick;
}
button.setLoadingState = function() {
button.innerText = 'Копіювання...'
button.className = 'kt-button kt-button-loading';
button.onclick = undefined;
}
button.setCopiedState = function() {
button.innerText = SUCCESS_BUTTON_TEXT
button.className = 'kt-button kt-button-success';
button.onclick = undefined;
}
if (isTicketCloned(ticketNumber)) {
button.setCopiedState();
} else {
button.setCopyState();
}
return button;
}
async function demo() {
const container = await waitTicketContainer();
const panel = createButtonPanel();
container.prepend(panel);
const ticketNumber = getTicketNumber();
const cloneButton = createCloneButton(ticketNumber)
panel.appendChild(cloneButton);
}
async function init() {
if (!getToken()) {
console.log('Token not found');
return
};
while (true) {
await waitTicketURL();
await demo();
await watchToolsPanel();
}
}
init()