-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
237 lines (201 loc) · 7.27 KB
/
index.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
const fs = require("fs");
const path = require("path");
const url = require("url");
const axios = require("axios");
const CancelToken = axios.CancelToken;
let cancel;
let source = "";
let commandArgs = {};
let cache = {};
// Template Stuff
const template = {
header:
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n' +
'<!-- This is an automatically generated file.\n' +
' It will be read and overwritten.\n' +
' DO NOT EDIT! -->\n' +
'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">\n' +
'<TITLE>Bookmarks</TITLE>\n' +
'<H1>Bookmarks</H1>\n' +
'<DL><p>\n',
start: ' <DT><H3 ADD_DATE="{date}" LAST_MODIFIED="{modified}" PERSONAL_TOOLBAR_FOLDER="false">{name}</H3>\n <DL><p>\n',
end: ' </DL><p>\n',
item: ' <DT><A HREF="{url}" ADD_DATE="{date}" ICON="{icon}" LAST_MODIFIED="{modified}">{title}</A>\n',
};
// Check if an object has a key
Object.prototype.has = function (key) {
return Object.keys(this).includes(key);
};
// Process the command line arguments
const commandlineArgs = (args) => {
let command = {};
let regex = new RegExp(/(\w+)\s?(.*)?/);
let argsArr = args
.slice(2)
.join(" ")
.split(/-|--/g)
.map((t) => {
return t.trim();
})
.filter(Boolean);
for (let cmd of argsArr) {
let words = cmd.match(regex);
command[words[1]] = words[2];
}
return command;
};
// Does directory exist
const dirExists = (dir) => {
try {
fs.opendirSync(dir, (err, isDir) => {
if (err) return false;
isDir.close();
});
} catch (err) {
return false;
}
return true;
};
// Extract the thumbnail if it exists.
const extractThumbnail = (_url, data) => {
let base64Header = new RegExp(/(^data\:image\/(\w+);base64,)/);
if (base64Header.test(data)) {
let matches = data.match(base64Header);
let parser = url.parse(_url, true);
let host = (parser.host + parser.pathname).replace(/\.|\//g, "-");
let file = path.join(commandArgs.x, host + "." + matches[2]);
data = data.replace(matches[1], "");
fs.writeFileSync(file, data, { encoding: "base64" });
console.log("🖼️ Thumbnail extracted to " + file);
}
};
// Get the favicon if it exists
const getFavicon = (_url) => {
return new Promise((resolve, reject) => {
let hostname = url.parse(bookmark.url, true).host;
axios({
method: "GET",
url: `http://${hostname}/favicon.ico`,
responseType: "arraybuffer",
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
timeout: 5000,
})
.then((response) => {
console.log("💗 Got an icon for " + hostname);
const base64 = Buffer.from(response.data, "binary").toString("base64");
cache[hostname] = "data:image/ico;base64," + base64;
resolve("data:image/ico;base64," + base64);
})
.catch((error) => {
cancel();
resolve("");
});
});
};
// Get groups from FVD file
const getGroups = () => {
let groups = [];
source["db"]["groups"].forEach((group) => {
groups.push({ id: group.id, name: group.name });
});
return groups;
};
// Get dials from a group
const getDials = async (id) => {
let temp = [];
bookmarks = source["db"]["dials"].filter((d) => d.group_id == id);
for (bookmark of bookmarks) {
let builder = {};
builder["title"] = bookmark.title;
builder["url"] = bookmark.url;
builder["icon"] = "";
// get a new favicon
if (commandArgs.has("f")) {
let hostname = url.parse(bookmark.url, true).host;
if (cache.has(hostname)) {
console.log("⭐ Got an icon from the cache for " + hostname);
builder["icon"] = cache[hostname];
}
else builder["icon"] = await getFavicon(bookmark.url);
}
// extract the thumbnail
if (commandArgs.has("x")) extractThumbnail(bookmark.url, bookmark.thumb);
temp.push(builder);
}
return temp;
};
// Creates the html
const buildHTML = (fvdData) => {
let html = template.header;
for (data in fvdData) {
let key = data;
let value = fvdData[data];
// Because I prototyped the object it tries to dump that function out
// Just have to skip that
if (typeof value !== "function") {
html += template.start
.replace("{name}", key)
.replace("{date}", new Date().getTime())
.replace("{modified}", new Date().getTime());
value.forEach((bookmark) => {
html += template.item
.replace("{title}", bookmark.title)
.replace("{url}", bookmark.url)
.replace("{date}", new Date().getTime())
.replace("{modified}", new Date().getTime())
.replace("{icon}", bookmark.icon);
});
html += template.end;
}
}
return html;
};
// Start
const convertFile = async () => {
let tempJSON = [];
source = JSON.parse(fs.readFileSync(commandArgs.i, "utf-8"));
for (group of getGroups()) {
console.log(`📂 Starting import of ${group.name}`);
tempJSON[group.name] = await getDials(group.id);
console.log(`😎 Finished ${group.name} with ${tempJSON[group.name].length} bookmarks`);
console.log();
}
fs.writeFileSync(commandArgs.o, buildHTML(tempJSON), "utf-8");
console.log(`🥰 HTML bookmarks file created!`);
};
// ***********************************************************************
// Process the command line
commandArgs = commandlineArgs(process.argv);
if (commandArgs.has("i") && commandArgs.has("o")) {
if (!fs.existsSync(commandArgs.i)) {
console.log("❌ Input file does not exist");
process.exit(100);
}
if (commandArgs.has("x") == true) {
if (!dirExists(commandArgs.x)) {
console.log("❌ Extract directory does not exist");
process.exit(200);
}
}
convertFile();
} else if (commandArgs.has("help") || commandArgs.has("h") || commandArgs.has("?")) {
console.log("Usage:");
console.log("node index.js -i source.json -o import.html");
console.log("node index.js -i source.json -o import.html -x ./thumbnails -f");
console.log();
console.log("-i [input file], -o [output file]");
console.log("-x [extract thumbnails to directory, -f Update the favicon");
console.log();
console.log("* [f]: Will attempt to download the favicon from the website");
console.log(" and add it to the bookmark import file.");
console.log();
console.log("* [x]: The eXtract option only extracts thumbnails of dials with");
console.log(" thumbnails that were manually assigned. (Not automatic thumbnails)");
console.log(" the automatic thumbnails are not stored in this file!");
} else {
console.log("Usage:");
console.log("node index.js -i source.json -o import.html");
console.log("node index.js --help (for more command options)");
}