-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathsnapshotUtil.ts
More file actions
176 lines (151 loc) · 4.02 KB
/
snapshotUtil.ts
File metadata and controls
176 lines (151 loc) · 4.02 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
import { baseUrl } from "@/api/baseUrl";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
type SnapshotResponse = {
dataUrl: string;
blob: Blob;
contentType: string;
};
export type SnapshotResult =
| {
success: true;
data: SnapshotResponse;
}
| {
success: false;
error: string;
};
export async function fetchCameraSnapshot(
name: string,
): Promise<SnapshotResult> {
try {
const url = `${baseUrl}api/${encodeURIComponent(name)}/latest.jpg`;
const response = await fetch(url, {
method: "GET",
cache: "no-store",
credentials: "same-origin",
});
if (!response.ok) {
return {
success: false,
error: `Snapshot request failed with status ${response.status}`,
};
}
const blob = await response.blob();
if (!blob || blob.size === 0) {
return {
success: false,
error: "Snapshot response was empty",
};
}
const dataUrl = await blobToDataUrl(blob);
const contentType = response.headers.get("content-type") ?? `image/jpeg`;
return {
success: true,
data: {
dataUrl,
blob,
contentType,
},
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error occurred",
};
}
}
function blobToDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (typeof reader.result === "string") {
resolve(reader.result);
} else {
reject(new Error("Failed to convert blob to data URL"));
}
};
reader.onerror = () => {
reject(reader.error ?? new Error("Failed to read snapshot blob"));
};
reader.readAsDataURL(blob);
});
}
export function downloadSnapshot(dataUrl: string, filename: string): void {
try {
const link = document.createElement("a");
link.href = dataUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Failed to download snapshot for ${filename}:`, error);
}
}
export function generateSnapshotFilename(
cameraName: string,
timestampSeconds?: number,
timezone?: string,
): string {
const seconds =
typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds)
? timestampSeconds
: Date.now() / 1000;
const timestamp = formatUnixTimestampToDateTime(seconds, {
timezone,
date_format: "yyyy-MM-dd'T'HH-mm-ss",
});
return `${cameraName}_snapshot_${timestamp}.jpg`;
}
export async function grabVideoSnapshot(
targetVideo?: HTMLVideoElement | null,
): Promise<SnapshotResult> {
try {
const videoElement =
targetVideo ??
(document.querySelector("#player-container video") as HTMLVideoElement);
if (!videoElement) {
return {
success: false,
error: "Video element not found",
};
}
const width = videoElement.videoWidth;
const height = videoElement.videoHeight;
if (width === 0 || height === 0) {
return {
success: false,
error: "Video element has no dimensions",
};
}
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context) {
return {
success: false,
error: "Failed to get canvas context",
};
}
context.drawImage(videoElement, 0, 0, width, height);
const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
// Convert data URL to blob
const response = await fetch(dataUrl);
const blob = await response.blob();
return {
success: true,
data: {
dataUrl,
blob,
contentType: "image/jpeg",
},
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error occurred",
};
}
}