-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
65 lines (58 loc) · 2.27 KB
/
service-worker.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
const getNextEmptyRow = async (googleAuthToken, spreadsheetId) => {
const requestOptions = {
method: 'GET',
headers: {
Authorization: `Bearer ${googleAuthToken}`,
},
};
const response = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/Sheet1!A1:A1000`, requestOptions);
const responseJson = await response.json();
return responseJson.values.length + 1;
};
const postNewRowData = async (googleAuthToken, rowData) => {
const spreadsheetId = rowData.spreadsheetId;
const spreadsheetRange = `Sheet1!A${rowData.nextEmptyRow}:H${rowData.nextEmptyRow}`;
const requestOptions = {
method: 'PUT',
headers: {
Authorization: `Bearer ${googleAuthToken}`,
'Content-Type': 'application/json'
},
contentType: 'json',
body: JSON.stringify({
range: spreadsheetRange,
majorDimension: 'ROWS',
values: [ [ rowData.companyName, '', rowData.date, '', '', '', '', rowData.url ] ]
})
};
await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${spreadsheetRange}?valueInputOption=USER_ENTERED`, requestOptions);
};
const parseNameFromLinkedIn = (pageTitle) => {
return pageTitle.split(' | ')[1];
};
const sanitizeLinkedInUrl = (url) => { //
const linkedInUrlRegex = new RegExp('^https://www\.linkedin\.com/jobs/view/\\d+', 'gm');
return linkedInUrlRegex.exec(url)[0];
};
chrome.action.onClicked.addListener(async (tab) => {
const spreadsheetId = (await chrome.storage.local.get('spreadsheetId')).spreadsheetId;
if (!spreadsheetId) {
chrome.tabs.create({ url: 'index.html' });
} else {
const googleAuthToken = (await chrome.identity.getAuthToken({ interactive: true })).token;
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const activeTab = tabs[0];
const nextEmptyRow = await getNextEmptyRow(googleAuthToken, spreadsheetId);
const currentDate = new Date();
const companyName = parseNameFromLinkedIn(activeTab.title);
const postingUrl = sanitizeLinkedInUrl(activeTab.url);
const rowData = {
companyName,
date: `${currentDate.getMonth() + 1}/${currentDate.getDate()}`,
url: postingUrl,
nextEmptyRow,
spreadsheetId
};
await postNewRowData(googleAuthToken, rowData);
}
});