-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
executable file
·291 lines (250 loc) · 11.2 KB
/
Copy pathcli.ts
File metadata and controls
executable file
·291 lines (250 loc) · 11.2 KB
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
#!/usr/bin/env bun
import { readFileSync, writeFileSync, statSync, existsSync } from 'fs';
import { setDefaultResultOrder } from 'node:dns';
import { lookup } from 'node:dns/promises';
import { isIP } from 'node:net';
import { loadImage, createCanvas, Image } from 'canvas';
import { getConfig, Config } from './src/config';
import { adjustContrast, ditherImage, processImageData } from './src/image-processor';
import { generateQrCode, drawQrCodeOnCanvas } from './src/qr-generator';
import { applyScaling } from './src/scaling';
import { generateQrContent } from './src/qr-content-generator';
function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
function enableIpv4FirstDns() {
try {
setDefaultResultOrder('ipv4first');
} catch (error) {
console.warn('Unable to set IPv4-first DNS result ordering:', errorMessage(error));
}
}
async function resolveHttpUrlIpv4First(url: string, headers?: HeadersInit) {
const parsedUrl = new URL(url);
if (parsedUrl.protocol !== 'http:' || isIP(parsedUrl.hostname)) {
return null;
}
try {
const address = await lookup(parsedUrl.hostname, { family: 4 });
const hostHeader = parsedUrl.host;
parsedUrl.hostname = address.address;
const resolvedHeaders = new Headers(headers);
if (!resolvedHeaders.has('Host')) {
resolvedHeaders.set('Host', hostHeader);
}
return { url: parsedUrl.toString(), headers: resolvedHeaders };
} catch (error) {
console.warn(`Could not resolve ${parsedUrl.hostname} to an IPv4 address, using original URL:`, errorMessage(error));
return null;
}
}
async function fetchImageUrl(url: string, options: RequestInit, resolveUrlIpv4First: boolean) {
if (!resolveUrlIpv4First) {
return fetch(url, options);
}
const resolved = await resolveHttpUrlIpv4First(url, options.headers);
if (!resolved) {
return fetch(url, options);
}
try {
return await fetch(resolved.url, { ...options, headers: resolved.headers });
} catch (error) {
console.warn(`IPv4 fetch failed for ${url}, retrying original URL:`, errorMessage(error));
return fetch(url, options);
}
}
async function waitForDevice(ip: string, timeout: number) {
console.log(`Waiting for device at ${ip} to come online...`);
const end = Date.now() + timeout * 1000;
while (Date.now() < end) {
try {
const response = await fetch(`http://${ip}/`, { method: 'GET', signal: AbortSignal.timeout(1000) });
if (response.status === 500) {
console.log('Device is online.');
return true;
}
} catch (error) {
// Ignore errors until timeout
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.error(`Device at ${ip} did not come online within ${timeout} seconds.`);
return false;
}
async function main() {
const args = process.argv.slice(2);
const imagePathOrUrlIndex = args.findIndex(arg => !arg.startsWith('--'));
const imagePathOrUrl = args[imagePathOrUrlIndex];
const configStrOrPathIndex = args.findIndex(arg => arg.endsWith('.json') || arg.startsWith('{'));
const configStrOrPath = args[configStrOrPathIndex];
const waitForOnlineIndex = args.indexOf('--wait-for-online');
let waitForOnlineTimeout = 0;
if (waitForOnlineIndex !== -1 && args[waitForOnlineIndex + 1]) {
waitForOnlineTimeout = parseInt(args[waitForOnlineIndex + 1], 10);
}
const ifModifiedSinceIndex = args.indexOf('--if-modified-since');
let ifModifiedSince = 0;
if (ifModifiedSinceIndex !== -1 && args[ifModifiedSinceIndex + 1]) {
ifModifiedSince = parseInt(args[ifModifiedSinceIndex + 1], 10);
}
if (!imagePathOrUrl || !configStrOrPath) {
console.error('Usage: ./dist/cli.js <path_to_image_or_url> <json_config_string_or_path_to_json> [--wait-for-online <seconds>] [--if-modified-since <timestamp>] [--resolve-url-ipv4-first]');
process.exit(1);
}
let config: Partial<Config>;
try {
config = JSON.parse(configStrOrPath);
} catch (e) {
try {
config = JSON.parse(readFileSync(configStrOrPath, 'utf-8'));
} catch (fileError) {
console.error('Error: Invalid configuration. Please provide a valid JSON string or a path to a valid JSON file.');
process.exit(1);
}
}
const settings = getConfig(config);
const resolveUrlIpv4First = settings.resolveUrlIpv4First || args.includes('--resolve-url-ipv4-first');
if (resolveUrlIpv4First) {
enableIpv4FirstDns();
}
// Check for duplicate local image file
let shouldUpdateLastFile = false;
if (!imagePathOrUrl.startsWith('http')) {
const fileStats = statSync(imagePathOrUrl);
const currentSize = fileStats.size;
const lastFilePath = '/tmp/neoframe.last';
if (existsSync(lastFilePath)) {
const lastSizeStr = readFileSync(lastFilePath, 'utf-8');
const lastSize = parseInt(lastSizeStr, 10);
if (lastSize === currentSize) {
console.log(`Error: ${imagePathOrUrl} is the same size as the last image sent to the frame (remove /tmp/neoframe.last to resend or provide an image file with a different size)`);
process.exit(100);
}
}
shouldUpdateLastFile = true;
}
try {
console.log('Loading image...');
let image;
if (imagePathOrUrl.startsWith('http')) {
const fetchOptions: any = {};
if (ifModifiedSince > 0) {
const date = new Date(ifModifiedSince * 1000);
fetchOptions.headers = {
'If-Modified-Since': date.toUTCString()
};
}
const response = await fetchImageUrl(imagePathOrUrl, fetchOptions, resolveUrlIpv4First);
if (response.status === 304) {
const isoDate = new Date(ifModifiedSince * 1000).toISOString().replace('T', ' ').slice(0, 19);
console.log(`Web server reports image as unchanged since ${ifModifiedSince} (${isoDate})`);
process.exit(100);
}
if (!response.ok) {
throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`);
}
const buffer = await response.arrayBuffer();
image = await loadImage(Buffer.from(buffer));
} else {
image = await loadImage(imagePathOrUrl);
}
const frameWidth = 1200;
const frameHeight = 1600;
const canvas = createCanvas(frameWidth, frameHeight);
const ctx = canvas.getContext('2d');
console.log('Processing image...');
const rotatedCanvas = createCanvas(image.width, image.height);
const rotatedCtx = rotatedCanvas.getContext('2d');
const rotation = parseInt(settings.rotation, 10);
if (rotation === 90 || rotation === 270) {
rotatedCanvas.width = image.height;
rotatedCanvas.height = image.width;
}
rotatedCtx.translate(rotatedCanvas.width / 2, rotatedCanvas.height / 2);
rotatedCtx.rotate(rotation * Math.PI / 180);
rotatedCtx.drawImage(image, -image.width / 2, -image.height / 2);
const sourceImage = rotatedCanvas;
const scalingMode = settings.scaling;
const offscreenCanvas = createCanvas(frameWidth, frameHeight);
const offscreenCtx = offscreenCanvas.getContext('2d');
offscreenCtx.fillStyle = 'white';
offscreenCtx.fillRect(0, 0, frameWidth, frameHeight);
const { imageBoundingBox } = applyScaling(sourceImage, offscreenCtx, settings, frameWidth, frameHeight);
const imageData = offscreenCtx.getImageData(0, 0, frameWidth, frameHeight);
adjustContrast(imageData, parseFloat(settings.contrast));
ditherImage(imageData, settings);
offscreenCtx.putImageData(imageData, 0, 0);
ctx.drawImage(offscreenCanvas, 0, 0);
if (settings.qrCodeEnabled) {
console.log('Generating QR code...');
const qrContent = await generateQrContent({
qrContentType: settings.qrContentType,
qrCustomText: settings.qrCustomText,
qrExifLabels: settings.qrExifLabels,
qrExifGps: settings.qrExifGps,
qrExifMaps: settings.qrExifMaps,
imagePathOrBuffer: imagePathOrUrl,
isBrowser: false
});
if (qrContent && qrContent.trim()) {
console.log('Generating QR code for content:', JSON.stringify(qrContent));
const qrCanvas = await generateQrCode(qrContent, settings);
console.log('QR canvas created, size:', qrCanvas.width, 'x', qrCanvas.height);
drawQrCodeOnCanvas(ctx, qrCanvas, settings, rotation, imageBoundingBox);
console.log('QR code drawn on image');
} else {
console.log('No QR content to generate');
}
}
console.log('Image processing complete.');
const finalImageData = processImageData(ctx.getImageData(0, 0, frameWidth, frameHeight), settings);
if (waitForOnlineTimeout > 0) {
const online = await waitForDevice(settings.esp32Ip, waitForOnlineTimeout);
if (!online) {
process.exit(1);
}
}
try {
console.log('Uploading to frame...');
const esp32IP = settings.esp32Ip;
const blob = new Blob([finalImageData], { type: 'application/octet-stream' });
const formData = new FormData();
formData.append('data', blob, 'image_data.bin');
const response = await fetch(`http://${esp32IP}/upload`, {
method: 'POST',
body: formData as any,
});
if (!response.ok) {
throw new Error(`Error uploading to frame: ${response.statusText}`);
}
const responseText = await response.text();
console.log('Upload response:', responseText);
console.log('Successfully uploaded image to the frame.');
// Save dithered image
const outPath = 'dithered_image.png';
try {
writeFileSync(outPath, canvas.toBuffer('image/png'));
console.log(`Dithered image saved to ${outPath}`);
} catch (saveError) {
console.error('Error saving dithered image:', saveError.message);
}
// Update last file if needed
if (shouldUpdateLastFile) {
const fileStats = statSync(imagePathOrUrl);
const currentSize = fileStats.size;
const lastFilePath = '/tmp/neoframe.last';
writeFileSync(lastFilePath, currentSize.toString());
}
} catch (uploadError) {
console.error('An error occurred during upload:', uploadError.message);
process.exit(1);
}
} catch (error) {
console.error('An error occurred during image processing:', error.message);
if (error.cause) {
console.error('Cause:', error.cause);
}
process.exit(1);
}
}
main();