-
Notifications
You must be signed in to change notification settings - Fork 2
/
OneDrivePhotos.js
307 lines (281 loc) · 9.59 KB
/
OneDrivePhotos.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
"use strict";
const EventEmitter = require("events");
const { writeFile } = require("fs/promises");
const moment = require("moment");
const { Client } = require('@microsoft/microsoft-graph-client');
const { LogLevel } = require("@azure/msal-node");
const path = require("path");
const { error_to_string } = require("./error_to_string");
const { msalConfig, protectedResources } = require("./msal/authConfig");
const AuthProvider = require("./msal/AuthProvider");
const { convertHEIC } = require("./PhotosConverter");
const sleep = require("./sleep");
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
class Auth extends EventEmitter {
#debug = {};
/** @type {AuthProvider} */
#authProvider = null;
constructor(debug = false) {
super();
this.#debug = debug;
this.init().then(() =>
process.nextTick(() =>
this.emit("ready")
),
(err) =>
this.emit("error", err)
);
}
async init() {
if (this.#debug) {
msalConfig.system.loggerOptions = LogLevel.Verbose;
}
this.#authProvider = new AuthProvider(msalConfig);
console.log("[ONEDRIVE:CORE] Auth -> AuthProvider created");
}
get AuthProvider() { return this.#authProvider; }
}
class OneDrivePhotos {
/** @type {Client} */
#graphClient = null;
/** @type {string} */
#userId = null;
#debug = false;
constructor(options) {
this.options = options;
this.#debug = options.debug ? options.debug : this.debug;
this.config = options.config;
}
debug(...args) {
if (this.#debug) console.debug("[ONEDRIVE:CORE]", ...args);
}
log(...args) {
console.log("[ONEDRIVE:CORE]", ...args);
}
logError(...args) {
console.error("[ONEDRIVE:CORE]", ...args);
}
logTrace(...args) {
console.trace("[ONEDRIVE:CORE]", ...args);
}
async onAuthReady() {
const auth = new Auth(this.#debug);
const _this = this;
return new Promise((resolve, reject) => {
auth.on("ready", async () => {
_this.log("onAuthReady ready");
const authProvider = auth.AuthProvider;
const tokenRequest = {
scopes: protectedResources.graphMe.scopes,
};
const tokenResponse = await authProvider.getToken(tokenRequest);
_this.debug("onAuthReady token responed");
_this.#graphClient = Client.init({
authProvider: (done) => {
done(null, tokenResponse.accessToken);
},
});
const graphResponse = await this.#graphClient.api(protectedResources.graphMe.endpoint).get();
_this.#userId = graphResponse.id;
_this.log("onAuthReady done");
resolve();
});
auth.on("error", (error) => {
reject(error);
});
});
}
async request(url = "", method = "get", data = null) {
try {
const ret = await this.#graphClient.api(url)[method](data);
return ret;
} catch (error) {
this.logTrace("request fail with URL", url);
this.logTrace("data", JSON.stringify(data));
this.logError(error_to_string(error));
throw error;
}
}
async getAlbums() {
let albums = await this.getAlbumType();
return albums;
}
async getAlbumType() {
await this.onAuthReady();
let url = protectedResources.listAllAlbums.endpoint.replace("$$userId$$", this.#userId);
/** @type {microsoftgraph.DriveItem[]} */
let list = [];
let found = 0;
/**
*
* @param {string} pageUrl
* @returns {microsoftgraph.DriveItem[]} DriveItem
*/
const getAlbum = async (pageUrl) => {
this.log("Getting Album info chunks.");
try {
/** @type {import("@microsoft/microsoft-graph-client").PageCollection} */
let response = await this.request(pageUrl, "get");
if (Array.isArray(response.value)) {
found += response.value.length;
list = list.concat(response.value);
for (let album of response.value) {
album.coverPhotoBaseUrl = await this.getAlbumThumbnail(album);
}
}
if (response["@odata.nextLink"]) {
await sleep(500);
return getAlbum(response["@odata.nextLink"]);
} else {
return list;
}
} catch (err) {
this.log(err.toString());
throw err;
}
};
return getAlbum(url);
}
async getAlbumThumbnail(album) {
const thumbnailUrl = protectedResources.getThumbnail.endpoint.replace("$$drive-id$$", album.parentReference.driveId).replace('$$item-id$$', album.id) + "?select=mediumSquare";
let response2 = await this.request(thumbnailUrl, "get");
if (Array.isArray(response2.value) && response2.value.length > 0) {
const thumbnail = response2.value[0];
return thumbnail.mediumSquare?.url;
}
}
async getImageFromAlbum(albumId, isValid = null, maxNum = 99999) {
await this.onAuthReady();
let url = protectedResources.getChildrenInAlbum.endpoint.replace("$$userId$$", this.#userId).replace("$$albumId$$", albumId);
/**
* @type {OneDriveMediaItem[]}
*/
let list = [];
/**
*
* @param {string} pageUrl
* @returns {Promise<OneDriveMediaItem[]>} DriveItem
*/
const getImage = async (pageUrl) => {
this.log("Indexing photos now. total: ", list.length);
try {
/** @type {import("@microsoft/microsoft-graph-client").PageCollection} */
let response = await this.request(pageUrl, "get");
if (Array.isArray(response.value)) {
/** @type {microsoftgraph.DriveItem[]} */
const childrenItems = response.value;
for (let item of childrenItems) {
/** @type {OneDriveMediaItem} */
const itemVal = {
id: item.id,
_albumId: albumId,
mimeType: item.file?.mimeType,
baseUrl: item['@microsoft.graph.downloadUrl'],
filename: item.name,
mediaMetadata: {},
parentReference: item.parentReference,
};
if (list.length < maxNum) {
if (item.image) {
itemVal.mediaMetadata.creationTime = item.fileSystemInfo?.createdDateTime;
itemVal.mediaMetadata.width = item.image.width;
itemVal.mediaMetadata.height = item.image.height;
}
if (item.photo) {
itemVal.mediaMetadata.photo = {
cameraMake: item.photo.cameraMake,
cameraModel: item.photo.cameraModel,
focalLength: item.photo.focalLength,
apertureFNumber: item.photo.fNumber,
isoEquivalent: item.photo.iso,
exposureTime: (item.photo.exposureNumerator * 1.0 / item.photo.exposureDenominator).toFixed(2) + 's',
};
}
if (item.video) {
itemVal.mediaMetadata.creationTime = item.fileSystemInfo?.createdDateTime;
itemVal.mediaMetadata.width = item.video.width;
itemVal.mediaMetadata.height = item.video.height;
itemVal.mediaMetadata.video = item.video;
}
if (typeof isValid === "function") {
if (isValid(itemVal)) list.push(itemVal);
} else {
list.push(itemVal);
}
}
}
if (list.length >= maxNum) {
return list; // full with maxNum
} else {
if (response["@odata.nextLink"]) {
await sleep(500);
return getImage(response["@odata.nextLink"]);
} else {
return list; // all found but lesser than maxNum
}
}
} else {
return list; // empty
}
} catch (err) {
this.logError(".getImageFromAlbum()", err.toString());
this.logError(err);
throw err;
}
};
return getImage(url);
}
/**
*
* @param {OneDriveMediaItem[]} items
* @param {string} cachePath
* @returns {OneDriveMediaItem[]} items
*/
async updateTheseMediaItems(items, cachePath) {
if (items.length <= 0) {
return [];
}
await this.onAuthReady();
this.log("received: ", items.length, " to refresh");
/**
* https://learn.microsoft.com/en-us/graph/json-batching#batch-size-limitations
* @type {[OneDriveMediaItem[]]}
*/
const chunkGroups = chunk(items, 20);
for (let grp of chunkGroups) {
const requestsValue = grp.filter(i => i.item?.parentReference).map((item, i) => ({
id: i,
method: "GET",
url: protectedResources.getItem.endpoint.replace("$$drive-id$$", item.parentReference.driveId).replace('$$item-id$$', item.id),
}));
if (requestsValue.length > 0) {
const requestsPayload = {
"requests": requestsValue,
};
const response = await this.request(protectedResources.$batch.endpoint, "post", requestsPayload);
for (let r of response.response) {
if (r.status < 400) {
grp[r.id].baseUrl = r.body.value['@microsoft.graph.downloadUrl'];
}
else {
console.error(r);
grp[r.id].baseUrl = null;
}
}
}
}
const heicPhotos = items.filter(i => i.mimeType === "image/heic" && i.baseUrl);
for (let photo of heicPhotos) {
const buf = await convertHEIC(photo.baseUrl);
const cacheFilename = encodeURI(path.join(cachePath, photo.id + "-convert.jpg"));
await writeFile(cacheFilename, buf);
photo._buffer = cacheFilename;
photo._bufferFilename = photo.id + "-convert.jpg";
}
return items;
}
}
module.exports = OneDrivePhotos;