-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.js
205 lines (172 loc) · 6.04 KB
/
convert.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
const IMAGE_MIMES_TO_SKIP = ['image/heic'];
const VIDEO_CODECS_TO_SKIP = ['hvc1'];
const [INPUT_PATH, OUTPUT_PATH] = process.argv.slice(2);
import { exiftool } from 'exiftool-vendored';
import { readdir, stat, access, utimes, copyFile, rm, mkdir, constants } from 'node:fs/promises';
import { join, basename, format, parse } from 'node:path';
import { promisify } from "node:util";
import { exec } from "node:child_process";
const execPromise = promisify(exec);
const failedFiles = [];
const warnFiles = [];
async function getFiles(path, results = []) {
let files = await readdir(path, { withFileTypes: true });
for (let file of files) {
let fullPath = join(path, file.name);
if (file.isDirectory()) {
await getFiles(fullPath, results);
} else {
if (basename(fullPath).startsWith('.')) {
continue;
}
results.push(fullPath);
}
}
return results;
}
async function getMediaInfo(path) {
try {
const exif = await exiftool.read(path);
return exif;
} catch (e) {
console.error(' error while getting media info', e);
}
}
async function throwIfFileExists(path) {
let exists = false;
try {
await access(path);
exists = true;
} catch {}
if (exists) {
throw new Error('file already exists');
}
}
async function checkFileSizes(file, outputPath) {
const originalFileStats = await stat(file.path);
const outputFileStats = await stat(outputPath);
if (outputFileStats.size >= originalFileStats.size) {
file.warning = `converted file "${outputPath}" is larger than original, please manually check which one you want to use`;
console.warn(' ' + file.warning);
warnFiles.push(file);
}
}
function errorHandler(file, error) {
file.error = error;
console.error(' failed to process file', file.error);
failedFiles.push(file);
}
async function buildOutputPath (parsedPath) {
const dir = join(OUTPUT_PATH, parsedPath.dir);
let outputPath = format({
dir,
name: parsedPath.name,
ext: parsedPath.ext
});
await mkdir(dir, {
recursive: true,
});
return outputPath;
}
async function convertVideo(file) {
const parsedPath = parse(file.path);
// if it's .mp4, use same container format to make sure meta data is kept. For all others, use .mov
let ext = parsedPath.ext.toLowerCase();
ext = ['.mov', '.mp4'].includes(ext) ? ext : '.mov';
const outputPath = await buildOutputPath({
...parsedPath,
ext
});
console.log(` converting video to`, outputPath);
try {
await throwIfFileExists(outputPath);
await execPromise(`ffmpeg -i "${file.path}" -c:v libx265 -x265-params preset=veryslow:crf=23 -vtag hvc1 -movflags faststart -n "${outputPath}"`);
await setDateTime(outputPath, file.exif);
await checkFileSizes(file, outputPath);
} catch (e) {
errorHandler(file, e);
}
};
async function convertImage(file) {
const parsedPath = parse(file.path);
const outputPath = await buildOutputPath({
...parsedPath,
ext: '.heic'
});
console.log(` converting image to`, outputPath);
try {
await throwIfFileExists(outputPath);
await execPromise(`magick "${file.path}" "${outputPath}"`);
await setDateTime(outputPath, file.exif);
await checkFileSizes(file, outputPath);
} catch (e) {
errorHandler(file, e);
}
}
async function copyOriginalFile(file) {
const parsedPath = parse(file.path);
const outputPath = await buildOutputPath(parsedPath);
console.log(' copying original file to', outputPath);
try {
await copyFile(file.path, outputPath, constants.COPYFILE_EXCL);
await setDateTime(outputPath, file.exif);
} catch (e) {
errorHandler(file, e);
}
}
async function setDateTime(outputPath, exif) {
let date = exif.CreationDate || exif.DateTimeOriginal || exif.MediaCreateDate || exif.CreateDate || exif.FileModifyDate;
if (!date.toDate) { // in case exiftool couldn't get the date
date = exif.FileModifyDate;
}
const dateObject = date.toDate();
console.log(' writing date', dateObject);
try {
await exiftool.write(outputPath, { AllDates: date });
await utimes(outputPath, dateObject, dateObject);
// TODO exiftool keeps a backup of the original file. With -overwrite_original CLI flag it should be possible to
// prevent it but for some reason it didn't work. Therefore removing the file manually.
await rm(outputPath + '_original');
} catch (e) {
console.error(' error while setting date', e);
}
}
const files = await getFiles(INPUT_PATH);
const totalFiles = files.length;
console.log(`found ${totalFiles} files`);
for (const [index, filePath] of files.entries()) {
const file = {
path: filePath,
exif: await getMediaInfo(filePath)
};
const failedStats = failedFiles.length ? ` (${failedFiles.length} failed)` : '';
console.log(`file ${index + 1} of ${totalFiles}${failedStats}: ${file.path}`);
let useOriginalFile = false;
const { CompressorID, MIMEType } = file.exif;
if (MIMEType.startsWith('image') && !IMAGE_MIMES_TO_SKIP.includes(MIMEType)) {
console.log(' image:', MIMEType);
await convertImage(file);
} else if (MIMEType.startsWith('video') && !VIDEO_CODECS_TO_SKIP.includes(CompressorID)) {
console.log(' video:', CompressorID);
await convertVideo(file);
} else {
useOriginalFile = true;
}
if (useOriginalFile) {
await copyOriginalFile(file);
}
}
console.log(`Done! Processed ${totalFiles - failedFiles.length} of ${totalFiles} files`);
if (failedFiles.length) {
console.warn('Errors:');
failedFiles.forEach(file => {
console.warn(' ', file.path, file.error);
});
}
if (warnFiles.length) {
console.warn('Warnings:');
warnFiles.forEach(file => {
console.warn(' ', file.path, file.warning);
});
}
exiftool.end();