-
Notifications
You must be signed in to change notification settings - Fork 2
/
unlighthouse-sites.js
210 lines (187 loc) · 7.42 KB
/
unlighthouse-sites.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
/*
* URL Processor and Google Sheets Manager Script
*
* Description:
* This Node.js script processes URLs, either provided as a single URL or from a CSV file, and interacts with Google Sheets.
* It authenticates with Google Sheets API, creates a new Google Sheet from a template, and stores the relevant URL information
* into a YAML file. The script is designed to check URLs, normalize them, handle redirections, and append new entries to a YAML configuration file.
*
* Features:
* - Processes a single URL or multiple URLs from a CSV file.
* - Authenticates and interacts with Google Sheets API to create new sheets from a template.
* - Stores URL data such as the normalized URL, sheet ID, and start date into a YAML file.
* - Handles URL normalization, redirections, and title extraction from the webpage.
* - Generates a random day of the week for scheduling purposes.
*
* This script can be used for automating URL tracking and data storage in Google Sheets, as well as maintaining an updated YAML configuration.
*
* License:
* This script is licensed under the GNU General Public License v3.0.
* You can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <https://www.gnu.org/licenses/>.
*/
const axios = require('axios');
const { google } = require('googleapis');
const fs = require('fs');
const yaml = require('js-yaml');
const { parse } = require('csv-parse/sync');
const { Command } = require('commander');
const SCOPES = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
];
const TOKEN_PATH = 'token.json';
const CREDENTIALS_PATH = 'credentials.json';
const program = new Command();
program
.version('0.1.1')
.description('Script to process URLs and manage Google Sheets.')
.option('-u, --url <type>', 'Add a single URL')
.option('-f, --file <type>', 'Add URLs from a CSV file')
.on('--help', () => {
console.log('\nExample calls:');
console.log(' $ node unlighthouse-sites.js --url https://www.example.com');
console.log(' $ node unlighthouse-sites.js --file urls.csv');
})
.parse(process.argv);
const options = program.opts();
if (!options.url && !options.file) {
console.log('Error: No URL or file provided.');
program.help(); // Display help and exit if no valid option provided
}
const weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const authenticateGoogleSheets = async () => {
const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, 'utf8'));
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
try {
const token = JSON.parse(fs.readFileSync(TOKEN_PATH, 'utf8'));
oAuth2Client.setCredentials(token);
return oAuth2Client;
} catch (error) {
console.log('Error loading the token from file:', error);
return null;
}
};
// Normalize URL by removing trailing slashes, www, and ensuring https protocol
const normalizeUrl = (url) => {
try {
// Ensure the URL starts with 'http://' or 'https://'
if (!/^https?:\/\//i.test(url)) {
url = 'https://' + url;
}
const urlObj = new URL(url);
urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
return urlObj.toString().replace(/\/+$/, '');
} catch (error) {
console.error('Invalid URL:', url, error);
return url;
}
};
// Check and extract final URL and title after redirections
const checkUrl = async (url) => {
const normalizedUrl = normalizeUrl(url);
try {
const response = await axios.get(normalizedUrl, { maxRedirects: 5 });
const finalUrl = normalizeUrl(response.request.res.responseUrl);
const titleMatch = response.data.match(/<title>(.*?)<\/title>/i);
return { url: finalUrl, title: titleMatch ? titleMatch[1] : 'No Title' };
} catch (error) {
console.error('Failed to retrieve URL:', normalizedUrl, error);
return null;
}
};
const createFromTemplate = async (auth, templateId, newTitle) => {
const drive = google.drive({ version: 'v3', auth });
try {
const copy = await drive.files.copy({
fileId: templateId,
requestBody: {
name: newTitle,
parents: ['1-8FGgtrPBH7aZrMxVlAkxooHXSzDv-w_'] // Replace 'actual-folder-id' with your actual folder ID
}
});
console.log('Spreadsheet ID:', copy.data.id);
console.log('Spreadsheet URL:', `https://docs.google.com/spreadsheets/d/${copy.data.id}/edit`);
return copy.data;
} catch (err) {
console.error('Failed to create spreadsheet from template:', err);
return null;
}
};
// Update YAML file with new data
const updateYAML = (filePath, data) => {
let doc = yaml.load(fs.readFileSync(filePath, 'utf8')) || {};
const normalizedUrl = normalizeUrl(data.url);
const shortUrl = normalizedUrl.replace(/^https?:\/\/(www\.)?/, '');
if (!doc[shortUrl]) { // Check if URL already exists
doc[shortUrl] = [{ ...data }];
fs.writeFileSync(filePath, yaml.dump(doc));
console.log('Added new entry:', data);
} else {
console.log('Entry already exists for URL:', data.url);
}
};
// Generate a random day of the week
const getRandomDay = () => {
return weekdays[Math.floor(Math.random() * weekdays.length)];
};
const processUrl = async (url) => {
const yamlPath = 'unlighthouse-sites.yml';
const normalizedUrl = normalizeUrl(url);
const shortUrl = normalizedUrl.replace(/^https?:\/\/(www\.)?/, '');
const existingEntries = yaml.load(fs.readFileSync(yamlPath, 'utf8')) || {};
console.log('Existing entries in YAML:', existingEntries);
if (existingEntries[shortUrl]) {
console.log('Entry already exists for URL:', shortUrl);
console.log('A new spreadsheet was not created.');
console.log('A new YAML entry was not created.');
return;
}
const urlData = await checkUrl(url);
console.log('URL data:', urlData);
if (!urlData) return;
const auth = await authenticateGoogleSheets();
if (!auth) {
console.error('Failed to authenticate with Google Sheets.');
return;
}
const templateId = '1UVyn_LPLCFqrXORqNqwSUvrkZtrmXUYUErbVZtxc5Tw'; // Your template ID
const copyData = await createFromTemplate(auth, templateId, urlData.title);
if (!copyData) {
console.error('Failed to create a new sheet from template.');
return;
}
const newData = {
url: urlData.url,
name: urlData.title,
sheet_id: copyData.id,
sheet_url: `https://docs.google.com/spreadsheets/d/${copyData.id}/edit`,
start_date: getRandomDay(), // Set a random day
max: 500
};
updateYAML(yamlPath, newData);
};
// Main function to parse arguments and process URLs or files
const main = () => {
program.parse(process.argv);
const options = program.opts();
if (options.url) {
processUrl(options.url);
} else if (options.file) {
const content = fs.readFileSync(options.file, 'utf8');
const records = parse(content, { columns: false });
records.forEach(record => {
const url = record[0].trim();
processUrl(url);
});
}
};
main();