-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathinstall.js
executable file
·334 lines (212 loc) · 8.08 KB
/
install.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env node
const os = require("os");
const fs = require("fs");
const path = require("path");
const child_process = require("child_process");
const dotenv = require("dotenv");
const get = require("simple-get");
const tar = require("tar");
const DOWNLOAD_RETRY_ATTEMPTS = 2;
const MACOS_MINIMUM_SUPPORTED_VERSION = 23;
const MACOS_MINIMUM_SUPPORTED_RELEASE = "Sonoma";
function targetFfmpegRelease() {
return "v" + process.env.npm_package_version;
}
function ffmpegCache() {
return path.join(__dirname, ".build");
}
function makeFfmpegCacheDir() {
fs.mkdirSync(ffmpegCache(), { recursive: true });
}
function ensureFfmpegCacheDir() {
if(!fs.existsSync(ffmpegCache())) {
return makeFfmpegCacheDir();
}
}
async function getDownloadFileName() {
switch(os.platform()) {
case "darwin":
switch(process.arch) {
case "x64":
return "ffmpeg-darwin-x86_64.tar.gz";
case "arm64":
return "ffmpeg-darwin-arm64.tar.gz";
default:
return null;
}
case "linux":
let osReleaseEnv = {};
if(fs.existsSync("/etc/os-release")) {
osReleaseEnv = dotenv.parse(fs.readFileSync("/etc/os-release"));
}
switch(process.arch) {
case "x64":
return "ffmpeg-alpine-x86_64.tar.gz";
case "arm":
return "ffmpeg-alpine-arm32v7.tar.gz";
case "arm64":
return "ffmpeg-alpine-aarch64.tar.gz";
default:
return null;
}
case "freebsd":
switch(process.arch) {
case "x64":
return "ffmpeg-freebsd-x86_64.tar.gz";
default:
return null;
}
case "win32":
if(process.arch === "x64") {
return "ffmpeg.exe"
}
return null;
default:
return null;
}
}
async function downloadFfmpeg(downloadUrl, ffmpegDownloadPath, retries = DOWNLOAD_RETRY_ATTEMPTS) {
const tempFile = path.resolve(ffmpegCache(), ".download");
console.log("Downloading FFmpeg from: " + downloadUrl);
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(tempFile);
const attemptDownload = () => {
// Download the file.
get(downloadUrl, (err, res) => {
if(err || (res.statusCode !== 200)) {
console.log("Download failed. Retrying.");
// Clean up the incomplete download before proceeding.
if(retries > 0) {
file.close();
fs.unlinkSync(tempFile);
return downloadFfmpeg(downloadUrl, ffmpegDownloadPath, retries - 1)
.then(resolve)
.catch(reject);
}
return reject(err || new Error("Failed to download after " + (DOWNLOAD_RETRY_ATTEMPTS + 1).toString() + " attempts."));
}
// We ensure totalBytes is never zero so we avoid divide-by-zero errors.
const totalBytes = parseInt(res.headers["content-length"], 10) || 1;
let downloadedBytes = 0;
// Inform users of our progress.
res.on("data", (chunk) => {
downloadedBytes += chunk.length;
process.stdout.write("\r" + Math.round((downloadedBytes / totalBytes) * 100).toString() + "%.");
});
// Download complete and the file is now closed, rename it.
file.on("close", () => {
fs.renameSync(tempFile, ffmpegDownloadPath);
resolve();
});
// Error handling.
file.on("error", (error) => {
console.log(error);
reject(error);
});
// All data written - we've completed the download.
file.on("finish", () => console.log(" - download complete."));
res.pipe(file);
}).on("error", (error) => {
console.log("Request error: ", error);
// Clean up the incomplete download before proceeding.
if(retries > 0) {
console.log("Retrying download.");
fs.unlinkSync(tempFile); // Clean up on error
return downloadFfmpeg(downloadUrl, ffmpegDownloadPath, retries - 1)
.then(resolve)
.catch(reject);
}
reject(new Error("Failed after " + (DOWNLOAD_RETRY_ATTEMPTS + 1).toString() + " attempts."));
});
};
attemptDownload();
});
}
function binaryOk(ffmpegTempPath) {
try {
child_process.execSync(ffmpegTempPath + " -buildconf");
return true;
} catch (e) {
return false;
}
}
function displayErrorMessage() {
console.log("\n\x1b[36mThe homebridge plugin has been installed, however you may need to install FFmpeg separately.\x1b[0m\n");
}
// Attempt to install a working version of FFmpeg for the system we are running on.
async function install() {
// Ensure the FFmpeg npm cache directory exists.
ensureFfmpegCacheDir();
// Ensure we don't support versions of macOS that are too old.
if((os.platform().toString() === "darwin") && (parseInt(os.release().split(".")[0]) < MACOS_MINIMUM_SUPPORTED_VERSION)) {
console.error("ffmpeg-for-homebridge: macOS versions older than " + MACOS_MINIMUM_SUPPORTED_RELEASE + " are not supported, you will need to install a working version of FFmpeg manually.");
process.exit(0);
}
// Determine the download file name for the current platform.
const ffmpegDownloadFileName = await getDownloadFileName();
if(!ffmpegDownloadFileName) {
console.error("ffmpeg-for-homebridge: %s %s is not supported, you will need to install a working version of FFmpeg manually.", os.platform, process.arch);
process.exit(0);
}
// The file path where the download will be located.
const ffmpegDownloadPath = path.resolve(ffmpegCache(), targetFfmpegRelease() + "-" + ffmpegDownloadFileName);
// Construct the download url.
const downloadUrl = "https://github.com/homebridge/ffmpeg-for-homebridge/releases/download/" + targetFfmpegRelease() + "/" + ffmpegDownloadFileName;
// Download the latest release if it's not been previously cached.
if(!fs.existsSync(ffmpegDownloadPath)) {
await downloadFfmpeg(downloadUrl, ffmpegDownloadPath);
}
// Contruct the path of the temporary FFmpeg binary.
const ffmpegTempPath = path.resolve(ffmpegCache(), os.platform() === "win32" ? "ffmpeg.exe" : "ffmpeg");
const ffmpegTargetPath = path.resolve(__dirname, os.platform() === "win32" ? "ffmpeg.exe" : "ffmpeg");
// Extract the FFmpeg binary from the downloaded tar.gz bundle on non-windows platforms.
if(os.platform() !== "win32") {
try {
await tar.x({
file: ffmpegDownloadPath,
C: ffmpegCache(),
strip: 4, // tar.gz packs ffmpeg into /usr/local/bin - this strips that out.
});
} catch (e) {
console.error(e);
console.error("An error occured while extracting the downloaded FFmpeg binary.");
displayErrorMessage();
// Delete the cached download if it failed to extract for some reason.
fs.unlinkSync(ffmpegDownloadPath);
process.exit(0);
}
// Set the execute permissions for FFmpeg.
if(fs.existsSync(ffmpegTempPath)) {
fs.chmodSync(ffmpegTempPath, 0o755);
}
} else {
// There's no need to extract for Windows - we just copy the downloaded binary to the temp path.
fs.renameSync(ffmpegDownloadPath, ffmpegTempPath)
}
// check if the downloaded binary works
if(!binaryOk(ffmpegTempPath)) {
displayErrorMessage();
// delete the cached download if it failed the test
fs.unlinkSync(ffmpegDownloadPath);
process.exit(0);
};
// move the binary to the npm package directory
fs.renameSync(ffmpegTempPath, ffmpegTargetPath);
console.log("\x1b[36m\nFFmpeg has been downloaded to %s.\x1b[0m", ffmpegTargetPath);
}
// Bootstrap the installation process.
async function bootstrap() {
console.log("Retrieving FFmpeg from ffmpeg-for-homebridge release: %s.", targetFfmpegRelease());
try {
await install();
} catch (e) {
if(e && e.code && e.code === "EACCES") {
console.log("Unable to download FFmpeg.\nIf you are installing this plugin as a global module (-g) make sure you add the --unsafe-perm flag to the install command.");
}
displayErrorMessage();
setTimeout(() => {
process.exit(0);
});
}
}
bootstrap();