-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph-api.js
181 lines (168 loc) · 6.27 KB
/
graph-api.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
import 'isomorphic-fetch';
import * as fs from 'node:fs/promises';
import { Client, LargeFileUploadTask, FileUpload } from '@microsoft/microsoft-graph-client';
import MuAuthenticationProvider from './mu-authentication-provider';
const MS_DRIVE_ID = process.env.MS_DRIVE_ID;
/**
* Client to interact with the MS Graph API. Requests are executed on behalf of a user.
* The client uses the mu-authentication-provider which fetches an access-token from
* the triplestore based on the user's session.
*
* Note: This client is not responsible for inserting/deleting data in the triplestore,
* only for interacting with the O365 Cloud using the Graph API.
*/
export default class GraphApiClient {
constructor(sessionUri) {
this.client = Client.initWithMiddleware({
authProvider: new MuAuthenticationProvider(sessionUri)
});
}
async me() {
const response = await this.client.api('/me').get();
console.log('Retrieved my profile');
console.log(response);
}
/**
* Find the MS fileId of a file in the given directory on the O365 drive
*/
async findFileByLocation({ path, name, search }) {
let msFileId = null;
if (name) {
const filePath = `${path}/${name}`;
try {
const response = await this.client
.api(`/drives/${MS_DRIVE_ID}/root:${filePath}`)
.select('id,name')
.get();
msFileId = response['id'];
} catch (e) {
if (e.code == 'itemNotFound') {
console.log(`File at path ${filePath} not found on drive ${MS_DRIVE_ID}.`);
} else {
console.log(`Failed to find file with path ${filePath} on drive ${MS_DRIVE_ID}`);
throw e;
}
}
}
// Fallback to search if file is not found at exact location (e.g. because customer name changed)
if (!msFileId && search) {
if (name) {
console.log(`File not found at exact location ${path}/${name}. Trying to find it by searching on ${path}/${search} now`);
}
try {
const driveItem = await this.client.api(`/drives/${MS_DRIVE_ID}/root:${path}`).select('id').get();
try {
const searchResult = await this.client
.api(`/drives/${MS_DRIVE_ID}/items/${driveItem.id}/search(q='${search}')`)
.top(1)
.select('id,name')
.get();
msFileId = searchResult['value'][0]?.id;
} catch (e) {
if (e.code == 'itemNotFound') {
console.log(`No search results found for path ${path}/${search} not found on drive ${MS_DRIVE_ID}.`);
} else {
console.log(`Failed to search path ${path}/${search} on drive ${MS_DRIVE_ID}`);
throw e;
}
}
} catch (e) {
if (e.code == 'itemNotFound') {
console.log(`Cannot find directory ${path} on drive ${MS_DRIVE_ID}.`);
} else {
throw e;
}
}
}
return msFileId;
}
/**
* Delete the file with the given MS fileId from the O365 drive.
*/
async deleteFile(fileId) {
try {
await this.client
.api(`/drives/${MS_DRIVE_ID}/items/${fileId}`)
.delete();
console.log(`Deleting file with id ${fileId} from drive ${MS_DRIVE_ID} succeeded.`);
} catch (e) {
console.log(`Failed to delete file with id ${fileId} from drive ${MS_DRIVE_ID}`);
throw e;
}
}
/**
* Get a temporary download URL for the file with the given MS fileId from the O365 drive.
*/
async getDownloadUrl(fileId) {
try {
const response = await this.client
.api(`/drives/${MS_DRIVE_ID}/items/${fileId}`)
.select('@microsoft.graph.downloadUrl')
.get();
return response['@microsoft.graph.downloadUrl'];
} catch (e) {
if (e.code == 'itemNotFound') {
console.log(`File with id ${fileId} not found on drive ${MS_DRIVE_ID}. Unable to download.`);
return null;
} else {
console.log(`Failed to download file with id ${fileId} from drive ${MS_DRIVE_ID}`);
throw e;
}
throw e;
}
}
/**
* Upload a file on the given path to the O365 drive.
*/
uploadFile(path, filename, content, filesize, opts) {
const fullPath = `${path}/${filename}`;
const fileObject = new FileUpload(content, filename, filesize);
return this.uploadFileObject(fullPath, fileObject, opts);
}
/**
* Upload a file from the local drive to a given path on the 0365 drive.
*/
async uploadLocalFile(targetPath, targetName, localFile, opts) {
const [content, stats] = await Promise.all([fs.readFile(localFile), fs.stat(localFile)]);
const size = stats.size;
return this.uploadFile(targetPath, targetName, content, size, opts);
}
/**
* @private
*/
async uploadFileObject(filePath, fileObject, opts) {
const url = `/drives/${MS_DRIVE_ID}/root:${filePath}:/createUploadSession`;
const body = {
item: {
'@microsoft.graph.conflictBehavior': opts?.conflictBehavior ?? 'rename' // one of 'fail', 'replace', 'rename'
}
};
const uploadSession = await LargeFileUploadTask.createUploadSession(this.client, url, body);
const options = {
rangeSize: 320 * 1024, // must be a multiple of 320 KiB
uploadEventHandlers: {
progress(range) {
console.log(`Upload in progress: [${range.minValue}-${range.maxValue}] bytes of content uploaded`);
}
}
};
console.log(`Starting upload file to drive ${MS_DRIVE_ID} on path ${filePath}`);
const uploadTask = new LargeFileUploadTask(this.client, fileObject, uploadSession, options);
try {
const uploadResult = await uploadTask.upload();
console.log(`Uploading file to drive ${MS_DRIVE_ID} on path ${filePath} succeeded. Item id: ${uploadResult.responseBody.id}`);
return {
id: uploadResult.responseBody.id,
name: uploadResult.responseBody.name,
url: uploadResult.responseBody.webUrl,
size: uploadResult.responseBody.size,
format: uploadResult.responseBody.file.mimeType,
created: new Date(Date.parse(uploadResult.responseBody.createdDateTime)),
modified: new Date(Date.parse(uploadResult.responseBody.lastModifiedDateTime))
};
} catch (e) {
console.log(`Uploading file to drive ${MS_DRIVE_ID} on path ${filePath} failed`);
throw e;
}
}
}