/
WriteTask.ts
191 lines (165 loc) · 5.77 KB
/
WriteTask.ts
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
import { encode } from "he"
import * as _path from "node:path"
import { isDateOrTime, toExifString } from "./DateTime"
import { DefaultExifToolOptions } from "./DefaultExifToolOptions"
import { errorsAndWarnings } from "./ErrorsAndWarnings"
import { ExifToolTask, ExifToolTaskOptions } from "./ExifToolTask"
import { Utf8FilenameCharsetArgs } from "./FilenameCharsetArgs"
import { Maybe } from "./Maybe"
import { isNumber, toInt } from "./Number"
import { keys } from "./Object"
import { pick } from "./Pick"
import { isString, splitLines } from "./String"
import { isStruct } from "./Struct"
import { WriteTags } from "./WriteTags"
const sep = String.fromCharCode(31) // < unit separator
// this is private because it's very special-purpose for just encoding ExifTool
// WriteTask args:
export function htmlEncode(s: string): string {
return (
// allowUnsafeSymbols is true because ExifTool doesn't care about &, <, >, ", ', * and `
encode(s, { decimal: true, allowUnsafeSymbols: true })
// `he` doesn't encode whitespaces (like newlines), but we need that:
.replace(/\s/g, (m) => (m === " " ? " " : `&#${m.charCodeAt(0)};`))
)
}
function enc(o: any, structValue = false): Maybe<string> {
if (o == null) {
return ""
} else if (isNumber(o)) {
return String(o)
} else if (isString(o)) {
// Structs need their own escaping here.
// See https://exiftool.org/struct.html#Serialize
return htmlEncode(
structValue ? o.replace(/[,[\]{}|]/g, (ea) => "|" + ea) : o
)
// const s = htmlEncode(String(o))
} else if (isDateOrTime(o)) {
return toExifString(o)
} else if (Array.isArray(o)) {
const primitiveArray = o.every((ea) => isString(ea) || isNumber(ea))
return primitiveArray
? `${o.map((ea) => enc(ea)).join(sep)}`
: `[${o.map((ea) => enc(ea)).join(",")}]`
} else if (isStruct(o)) {
// See https://exiftool.org/struct.html#Serialize
return `{${keys(o)
.map((k) => enc(k, true) + "=" + enc(o[k], true))
.join(",")}}`
} else {
throw new Error("cannot encode " + JSON.stringify(o))
}
}
export const DefaultWriteTaskOptions = {
...pick(DefaultExifToolOptions, "useMWG", "ignoreMinorErrors"),
} as const
export type WriteTaskOptions = Partial<typeof DefaultWriteTaskOptions>
export interface WriteTaskResult {
/**
* Number of files created by ExifTool
*/
created: number
/**
* Number of files updated by ExifTool. Note that this does not mean any
* field values were _changed_ from prior values.
*/
updated: number
/**
* Number of files that ExifTool knew it did not need change. Note that
* ExifTool (at least as of v12.70) only realizes it doesn't need to change
* a file if you are clearing an already empty value.
*/
unchanged: number
/**
* Non-exceptional warnings from ExifTool, like "Error: Nothing to write",
* or "Nothing to do."
*
* Any invalid tag names or values will cause {@link Error}s to be thrown.
*/
warnings?: string[]
}
export class WriteTask extends ExifToolTask<WriteTaskResult> {
private constructor(
readonly sourceFile: string,
override readonly args: string[],
override readonly options: ExifToolTaskOptions
) {
super(args, options)
}
static for(
filename: string,
tags: WriteTags,
extraArgs: string[] = [],
options: Partial<WriteTaskOptions> & Required<ExifToolTaskOptions>
): WriteTask {
const sourceFile = _path.resolve(filename)
const args: string[] = [
...Utf8FilenameCharsetArgs,
`-sep`,
`${sep}`,
"-E", // < html encoding https://exiftool.org/faq.html#Q10
]
if (options?.useMWG ?? DefaultWriteTaskOptions.useMWG) {
args.push("-use", "MWG")
}
// Special handling for GPSLatitude and GPSLongitude (due to differences
// in EXIF, XMP, and MIE encodings). See
// https://exiftool.org/forum/index.php?topic=14488.0 and
// https://github.com/photostructure/exiftool-vendored.js/issues/131
if (isNumber(tags.GPSLatitude)) {
tags.GPSLatitudeRef ??= tags.GPSLatitude >= 0 ? "N" : "S"
}
if (isNumber(tags.GPSLongitude)) {
tags.GPSLongitudeRef ??= tags.GPSLongitude >= 0 ? "E" : "W"
}
for (const key of keys(tags)) {
const val = tags[key]
args.push(`-${key}=${enc(val)}`)
}
args.push(...extraArgs)
args.push(sourceFile)
return new WriteTask(sourceFile, args, options)
}
override toString(): string {
return "WriteTask(" + this.sourceFile + ")"
}
// we're handling the stderr output ourselves, so we tell ExifToolTask that all stderr output is not ignorable so we can capture the warnings
protected parse(data: string, error?: Error): WriteTaskResult {
if (error != null) throw error
let created = 0
let updated = 0
let unchanged = 0
for (const line of splitLines(data)) {
const m_created = CreatedRE.exec(line)
if (m_created != null) {
created += toInt(m_created[1]) ?? 0
continue
}
// careful! we need to apply UnchangedRE before UpdateRE, as both match
// "updated"
const m_unchanged = UnchangedRE.exec(line)
if (m_unchanged != null) {
unchanged += toInt(m_unchanged[1]) ?? 0
continue
}
const m_updated = UpdatedRE.exec(line)
if (m_updated != null) {
updated += toInt(m_updated[1]) ?? 0
continue
}
// if we get here, we didn't match any of the expected patterns.
this.warnings.push("Unexpected output from ExifTool: " + line)
}
const w = errorsAndWarnings(this).warnings ?? []
return {
created,
updated,
unchanged,
...(w.length === 0 ? {} : { warnings: w }),
}
}
}
const CreatedRE = /(\d+) .*?\bcreated\b/i
const UnchangedRE = /(\d+) .*?(?:\bweren't updated|unchanged\b)/i
const UpdatedRE = /(\d+) .*?\bupdated\b/i