This repository has been archived by the owner on Feb 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhelpers.js
211 lines (180 loc) · 4.94 KB
/
helpers.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
const axios = require('axios');
const fsBase = require('fs');
const fs = fsBase.promises;
const path = require('path');
const filenamify = require('filenamify');
const jsdom = require('jsdom').JSDOM;
const ProgressBar = require('progress');
const signale = require('signale');
let client = new axios.create();
async function formatDate(date) {
let month = date.getMonth() + 1;
let day = date.getDate();
/**
* Totally and definitely the best way to zero-prefix dates.
*/
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
return `${date.getFullYear()}-${month}-${day}`;
}
/**
* Normalize path names and avoid 'special' characters.
*
* @param {String} dir
*/
async function normalizePath(dir) {
return (
dir
.replace(/[^a-z0-9-]/gi, '_')
// Avoid double (or more) underscores
.replace(/_{2,}/g, '_')
);
}
/**
* Checks input path and makes sure it exists.
* If it exists, it checks if it's a directory and errors if it doesn't.
* If it doesn't exist, it will attempt to create it.
*
* @param {String} dir
*/
async function checkAndCreateDir(dir) {
dir = path.normalize(dir);
const exists = fsBase.existsSync(dir);
if (!exists) {
await fs.mkdir(dir, {
recursive: true,
});
signale.success(`Resolved & created directory: ${dir}`);
return dir;
}
const stat = await fs.stat(dir);
if (!stat.isDirectory()) {
signale.error(
`Path ${dir} exists, but is not a directory (most likely a file).`
);
return null;
}
return dir;
}
/**
* Downloads a file as a blob from the specified URL, to the specified directory with the specified filename.
*
* @param {String} url
* @param {String} path
* @param {String} filename
*/
async function downloadFile(url, dir, filename) {
filename = filenamify(filename);
const output = `${dir}/${filename}`;
if (fsBase.existsSync(output)) {
signale.info(`File already exists: ${output} -- Skipping`);
return null;
}
// Lazily catch errors
try {
const response = await client({
url: url,
responseType: 'stream',
});
const fileLength = parseInt(response.headers['content-length'], 10);
const bar = new ProgressBar(
`Downloading file: ${filename} - [:bar] :percent`,
{
complete: '=',
incomplete: ' ',
width: 20,
total: fileLength,
}
);
response.data.pipe(fsBase.createWriteStream(output));
signale.time(filename);
return new Promise((resolve, reject) => {
response.data.on('end', () => {
resolve();
signale.timeEnd(filename);
});
response.data.on('data', data => {
bar.tick(data.length);
});
response.data.on('error', err => {
signale.timeEnd(filename);
signale.error(`An error occurred downloading URL: ${url}`);
signale.error(`Could not save file: ${output}`);
signale.error(err);
reject(err);
});
});
} catch (err) {
signale.error(`An error occurred downloading URL: ${url} -- Skipping`);
signale.error(err);
return null;
}
}
/**
* Saves a text file with UTF-8 encoding.
*
* @param {String} dir
* @param {String} filename
* @param {String} text
*/
async function saveTextFile(dir, filename, text) {
filename = filenamify(filename);
const output = `${dir}/${filename}`;
try {
await fs.writeFile(output, text, {
encoding: 'utf8',
});
return output;
} catch (err) {
signale.error(`Error writing file: ${output}`);
signale.error(err);
return null;
}
}
/**
* Parses post the post body and extracts the inline images.
*
* @param {String} body
*/
async function parseInline(body) {
const dom = new jsdom(body);
const inlineImages = Array.from(
dom.window.document.querySelectorAll('img')
);
const imageLinks = inlineImages.map(img => {
const src = img.src;
let prefix = 'https://yiff.party';
// Only add a forward slash at the end of the prefix
// if src doesn't already include it.
// In most cases it should...
if (src[0] !== '/') {
prefix += '/';
}
return prefix + src;
});
return imageLinks;
}
/**
* @param {Object} cli cli object from `meow`
*/
module.exports = (cli) => {
client = axios.create({
method: 'GET',
headers: {
'User-Agent': cli.flags.userAgent,
},
});
return {
checkAndCreateDir,
client,
downloadFile,
formatDate,
normalizePath,
parseInline,
saveTextFile,
};
};