@gzhangx/googleapi 0.0.8 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,394 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.getMsGraphConn = exports.axiosErrorProcessing = exports.getDefaultMsGraphConn = exports.getDefaultAuth = exports.getAuth = exports.encodeSharedUrl = exports.GGraphError = void 0;
43
+ var axios_1 = __importDefault(require("axios"));
44
+ //import * as promise from 'bluebird';
45
+ var lodash_1 = require("lodash");
46
+ var util_1 = require("../util");
47
+ function delay(ms) {
48
+ return __awaiter(this, void 0, void 0, function () {
49
+ return __generator(this, function (_a) {
50
+ return [2 /*return*/, new Promise(function (resolve) {
51
+ setTimeout(function () {
52
+ resolve(null);
53
+ }, ms);
54
+ })];
55
+ });
56
+ });
57
+ }
58
+ function GGraphError(message) {
59
+ if (message === void 0) { message = ""; }
60
+ this.name = "GGraphError";
61
+ this.message = message;
62
+ }
63
+ exports.GGraphError = GGraphError;
64
+ GGraphError.prototype = Error.prototype;
65
+ function encodeSharedUrl(sharingUrl) {
66
+ //see https://docs.microsoft.com/en-us/graph/api/shares-get?view=graph-rest-1.0&irgwc=1&OCID=AID2200057_aff_7593_1243925&tduid=(ir__ksd0kmgl9ckf6nyskg6fwnqce32xt3umkhw9f9gn00)(7593)(1243925)(je6NUbpObpQ-XTpQa0NuXTfWX1VU38TMYg)()&irclickid=_ksd0kmgl9ckf6nyskg6fwnqce32xt3umkhw9f9gn00&tabs=http#encoding-sharing-urls&ranMID=24542&ranEAID=je6NUbpObpQ&ranSiteID=je6NUbpObpQ-XTpQa0NuXTfWX1VU38TMYg&epi=je6NUbpObpQ-XTpQa0NuXTfWX1VU38TMYg
67
+ var base64Value = Buffer.from(sharingUrl).toString('base64');
68
+ //string encodedUrl = "u!" + base64Value .TrimEnd('=').Replace('/', '_').Replace('+', '-');
69
+ var encodedUrl = base64Value.replace(/=/g, '').replace(/\//g, '_').replace(/\+/g, '-');
70
+ var resUrl = "u!".concat(encodedUrl);
71
+ return resUrl;
72
+ }
73
+ exports.encodeSharedUrl = encodeSharedUrl;
74
+ function getAuth(opt) {
75
+ var tenantId = opt.tenantId;
76
+ var client_id = opt.client_id;
77
+ if (!tenantId)
78
+ throw {
79
+ message: 'tenantId required'
80
+ };
81
+ if (!client_id)
82
+ throw {
83
+ message: 'client_id required'
84
+ };
85
+ var promptUser = opt.promptUser || console.log;
86
+ var saveToken = opt.saveToken;
87
+ var scope = opt.scope || 'Mail.Read openid profile User.Read email Files.ReadWrite.All Files.ReadWrite Files.Read Files.Read.All Files.Read.Selected Files.ReadWrite.AppFolder Files.ReadWrite.Selected';
88
+ var baseQueryUrl = "https://login.microsoftonline.com/".concat(tenantId, "/oauth2/v2.0");
89
+ var queryCodeurl = "".concat(baseQueryUrl, "/token");
90
+ function doPost(url, data) {
91
+ return __awaiter(this, void 0, void 0, function () {
92
+ var dataStr;
93
+ return __generator(this, function (_a) {
94
+ switch (_a.label) {
95
+ case 0:
96
+ dataStr = (0, util_1.getFormData)(data);
97
+ return [4 /*yield*/, axios_1.default.post(url, dataStr, {
98
+ headers: {
99
+ 'Content-Type': 'application/x-www-form-urlencoded'
100
+ }
101
+ }).then(function (r) {
102
+ return (r.data);
103
+ })];
104
+ case 1: return [2 /*return*/, _a.sent()];
105
+ }
106
+ });
107
+ });
108
+ }
109
+ function getRefreshToken() {
110
+ return __awaiter(this, void 0, void 0, function () {
111
+ var codeWaitInfo, deviceCode, message, rr, err_1, errData;
112
+ return __generator(this, function (_a) {
113
+ switch (_a.label) {
114
+ case 0: return [4 /*yield*/, doPost("".concat(baseQueryUrl, "/devicecode"), {
115
+ scope: scope,
116
+ client_id: client_id,
117
+ })];
118
+ case 1:
119
+ codeWaitInfo = _a.sent();
120
+ deviceCode = codeWaitInfo.device_code;
121
+ message = codeWaitInfo.message;
122
+ return [4 /*yield*/, promptUser(message, codeWaitInfo)];
123
+ case 2:
124
+ _a.sent();
125
+ _a.label = 3;
126
+ case 3:
127
+ if (!true) return [3 /*break*/, 13];
128
+ _a.label = 4;
129
+ case 4:
130
+ _a.trys.push([4, 9, , 12]);
131
+ return [4 /*yield*/, doPost(queryCodeurl, {
132
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
133
+ resource: 'https://graph.microsoft.com',
134
+ scope: scope,
135
+ code: deviceCode,
136
+ client_id: client_id
137
+ })];
138
+ case 5:
139
+ rr = _a.sent();
140
+ if (!(rr.error === 'authorization_pending')) return [3 /*break*/, 7];
141
+ //await promise.Promise.delay(opt.pollTime || 1000);
142
+ return [4 /*yield*/, delay(opt.pollTime || 1000)];
143
+ case 6:
144
+ //await promise.Promise.delay(opt.pollTime || 1000);
145
+ _a.sent();
146
+ return [3 /*break*/, 3];
147
+ case 7:
148
+ ///console.log(rr);
149
+ //const { access_token, refresh_token } = rr;
150
+ //fs.writeFileSync('credentials.json', JSON.stringify(rr, null, 2));
151
+ return [4 /*yield*/, saveToken(rr)];
152
+ case 8:
153
+ ///console.log(rr);
154
+ //const { access_token, refresh_token } = rr;
155
+ //fs.writeFileSync('credentials.json', JSON.stringify(rr, null, 2));
156
+ _a.sent();
157
+ return [2 /*return*/, rr];
158
+ case 9:
159
+ err_1 = _a.sent();
160
+ errData = (0, lodash_1.get)(err_1, 'response.data');
161
+ if (!(errData && errData.error === 'authorization_pending')) return [3 /*break*/, 11];
162
+ return [4 /*yield*/, delay(opt.pollTime || 1000)];
163
+ case 10:
164
+ _a.sent();
165
+ return [3 /*break*/, 3];
166
+ case 11: return [3 /*break*/, 12];
167
+ case 12: return [3 /*break*/, 3];
168
+ case 13: return [2 /*return*/];
169
+ }
170
+ });
171
+ });
172
+ }
173
+ function getAccessToken() {
174
+ return __awaiter(this, void 0, void 0, function () {
175
+ var refresh_token, form, ac;
176
+ return __generator(this, function (_a) {
177
+ switch (_a.label) {
178
+ case 0:
179
+ refresh_token = opt.refresh_token;
180
+ form = {
181
+ scope: scope,
182
+ refresh_token: refresh_token,
183
+ grant_type: 'refresh_token',
184
+ client_id: client_id
185
+ };
186
+ return [4 /*yield*/, doPost(queryCodeurl, form)];
187
+ case 1:
188
+ ac = _a.sent();
189
+ return [2 /*return*/, ac];
190
+ }
191
+ });
192
+ });
193
+ }
194
+ //getAuth({tenantId, client_id, promptUser, saveToken, loadToken})
195
+ return {
196
+ getRefreshToken: getRefreshToken,
197
+ getAccessToken: getAccessToken,
198
+ };
199
+ }
200
+ exports.getAuth = getAuth;
201
+ function getDefaultAuth(opt) {
202
+ var _this = this;
203
+ var tenantId = opt.tenantId, client_id = opt.client_id, refresh_token = opt.refresh_token;
204
+ return getAuth({
205
+ tenantId: tenantId,
206
+ client_id: client_id,
207
+ refresh_token: refresh_token,
208
+ promptUser: function (msg) { return console.log(msg); },
209
+ saveToken: function (res) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
210
+ return [2 /*return*/, console.log(res)];
211
+ }); }); },
212
+ });
213
+ }
214
+ exports.getDefaultAuth = getDefaultAuth;
215
+ function getDefaultMsGraphConn(tenantClientInfo, logger) {
216
+ if (logger === void 0) { logger = function (x) { return console.log(x); }; }
217
+ return __awaiter(this, void 0, void 0, function () {
218
+ return __generator(this, function (_a) {
219
+ return [2 /*return*/, getMsGraphConn({
220
+ tenantClientInfo: tenantClientInfo,
221
+ tokenInfo: null,
222
+ logger: logger,
223
+ })];
224
+ });
225
+ });
226
+ }
227
+ exports.getDefaultMsGraphConn = getDefaultMsGraphConn;
228
+ function axiosErrorProcessing(err) {
229
+ function doSteps(obj, initialMsg, steps) {
230
+ var msg = steps.reduce(function (acc, step) {
231
+ var cur = (0, lodash_1.get)(acc.obj, step);
232
+ if (typeof cur === 'string') {
233
+ if (acc.msg)
234
+ acc.msg = "".concat(acc.msg, " ").concat(cur);
235
+ else
236
+ acc.msg = cur;
237
+ }
238
+ return acc;
239
+ }, {
240
+ obj: obj,
241
+ msg: initialMsg
242
+ });
243
+ return msg.msg;
244
+ }
245
+ var steps = ['response.data.message', 'response.data.error.message'];
246
+ var msg = doSteps(err, err.message, steps);
247
+ return msg;
248
+ }
249
+ exports.axiosErrorProcessing = axiosErrorProcessing;
250
+ function getMsGraphConn(opt) {
251
+ return __awaiter(this, void 0, void 0, function () {
252
+ function getToken() {
253
+ var _a;
254
+ return __awaiter(this, void 0, void 0, function () {
255
+ var now, getAccessToken, tok;
256
+ return __generator(this, function (_b) {
257
+ switch (_b.label) {
258
+ case 0:
259
+ now = new Date().getTime();
260
+ opt.logger("debugrm getMsGraphConn now=".concat(now, " exp=").concat((_a = opt.tokenInfo) === null || _a === void 0 ? void 0 : _a.expires_on));
261
+ if (!(!opt.tokenInfo || opt.tokenInfo.expires_on < now / 1000)) return [3 /*break*/, 2];
262
+ getAccessToken = getDefaultAuth(opt.tenantClientInfo).getAccessToken;
263
+ opt.logger('getting new token');
264
+ return [4 /*yield*/, getAccessToken()];
265
+ case 1:
266
+ tok = _b.sent();
267
+ opt.tokenInfo = tok;
268
+ _b.label = 2;
269
+ case 2: return [2 /*return*/, opt.tokenInfo];
270
+ }
271
+ });
272
+ });
273
+ }
274
+ function getHeaders() {
275
+ return __awaiter(this, void 0, void 0, function () {
276
+ var tok;
277
+ return __generator(this, function (_a) {
278
+ switch (_a.label) {
279
+ case 0: return [4 /*yield*/, getToken()];
280
+ case 1:
281
+ tok = _a.sent();
282
+ return [2 /*return*/, {
283
+ headers: {
284
+ "Authorization": "Bearer ".concat(tok.access_token)
285
+ },
286
+ maxContentLength: Infinity,
287
+ maxBodyLength: Infinity,
288
+ }];
289
+ }
290
+ });
291
+ });
292
+ }
293
+ function parseResp(r) {
294
+ return r.data;
295
+ }
296
+ function errProc(context) {
297
+ return function (err) {
298
+ var message = axiosErrorProcessing(err);
299
+ opt.logger("error on ".concat(context, ": ").concat(message));
300
+ throw new GGraphError(message);
301
+ };
302
+ }
303
+ function doGet(urlPostFix, fmt) {
304
+ if (fmt === void 0) { fmt = function (x) { return x; }; }
305
+ return __awaiter(this, void 0, void 0, function () {
306
+ var uri, _a, _b, _c, _d;
307
+ return __generator(this, function (_e) {
308
+ switch (_e.label) {
309
+ case 0:
310
+ uri = getUserUrl(urlPostFix);
311
+ opt.logger("GET ".concat(uri));
312
+ _b = (_a = axios_1.default).get;
313
+ _c = [uri];
314
+ _d = fmt;
315
+ return [4 /*yield*/, getHeaders()];
316
+ case 1: return [4 /*yield*/, _b.apply(_a, _c.concat([_d.apply(void 0, [_e.sent()])]))
317
+ .then(parseResp).catch(errProc(uri))];
318
+ case 2: return [2 /*return*/, _e.sent()];
319
+ }
320
+ });
321
+ });
322
+ }
323
+ function doPost(urlPostFix, data) {
324
+ return __awaiter(this, void 0, void 0, function () {
325
+ var uri, _a, _b, _c;
326
+ return __generator(this, function (_d) {
327
+ switch (_d.label) {
328
+ case 0:
329
+ uri = getUserUrl(urlPostFix);
330
+ opt.logger("POST ".concat(uri));
331
+ _b = (_a = axios_1.default).post;
332
+ _c = [uri, data];
333
+ return [4 /*yield*/, getHeaders()];
334
+ case 1: return [2 /*return*/, _b.apply(_a, _c.concat([_d.sent()])).then(parseResp).catch(errProc(uri))];
335
+ }
336
+ });
337
+ });
338
+ }
339
+ function doPut(urlPostFix, data) {
340
+ return __awaiter(this, void 0, void 0, function () {
341
+ var uri, _a, _b, _c;
342
+ return __generator(this, function (_d) {
343
+ switch (_d.label) {
344
+ case 0:
345
+ uri = getUserUrl(urlPostFix);
346
+ opt.logger("PUT ".concat(uri));
347
+ _b = (_a = axios_1.default).put;
348
+ _c = [uri, data];
349
+ return [4 /*yield*/, getHeaders()];
350
+ case 1: return [2 /*return*/, _b.apply(_a, _c.concat([_d.sent()])).then(parseResp).catch(errProc(uri))];
351
+ }
352
+ });
353
+ });
354
+ }
355
+ function doPatch(urlPostFix, data) {
356
+ return __awaiter(this, void 0, void 0, function () {
357
+ var uri, _a, _b, _c;
358
+ return __generator(this, function (_d) {
359
+ switch (_d.label) {
360
+ case 0:
361
+ uri = getUserUrl(urlPostFix);
362
+ opt.logger("PATCH ".concat(uri));
363
+ _b = (_a = axios_1.default).patch;
364
+ _c = [uri, data];
365
+ return [4 /*yield*/, getHeaders()];
366
+ case 1: return [2 /*return*/, _b.apply(_a, _c.concat([_d.sent()])).then(parseResp).catch(errProc(uri))];
367
+ }
368
+ });
369
+ });
370
+ }
371
+ function getSharedItemInfo(sharedUrl) {
372
+ return __awaiter(this, void 0, void 0, function () {
373
+ return __generator(this, function (_a) {
374
+ return [2 /*return*/, doGet("shares/".concat(encodeSharedUrl(sharedUrl), "/driveItem")).then(function (r) {
375
+ return r;
376
+ })];
377
+ });
378
+ });
379
+ }
380
+ var ROOT_URL, getUserUrl;
381
+ return __generator(this, function (_a) {
382
+ ROOT_URL = 'https://graph.microsoft.com/v1.0';
383
+ getUserUrl = function (urlPostFix) { return "".concat(ROOT_URL, "/").concat(urlPostFix); };
384
+ return [2 /*return*/, {
385
+ doGet: doGet,
386
+ doPost: doPost,
387
+ doPut: doPut,
388
+ doPatch: doPatch,
389
+ getSharedItemInfo: getSharedItemInfo,
390
+ }];
391
+ });
392
+ });
393
+ }
394
+ exports.getMsGraphConn = getMsGraphConn;
@@ -0,0 +1,105 @@
1
+ /// <reference types="node" />
2
+ import { ILogger, IMsGraphCreds } from "./msauth";
3
+ export interface IMsDirOps {
4
+ createFile: (path: string, data: Buffer) => Promise<IFileCreateResponse>;
5
+ getFileByPath: (itemId: string) => Promise<Buffer>;
6
+ createDir: (path: string, name: string) => Promise<IDirCreateResponse>;
7
+ driveId: string;
8
+ }
9
+ export interface IMsGraphDirPrms {
10
+ logger: ILogger;
11
+ sharedUrl?: string;
12
+ driveId?: string;
13
+ }
14
+ export declare const getDriveUrl: (driveId: string, path: string) => string;
15
+ export declare const getDriveAndByIdUrl: (driveId: string, itemId: string) => string;
16
+ export declare function getMsDir(creds: IMsGraphCreds, prms: IMsGraphDirPrms): Promise<IMsDirOps>;
17
+ export interface IDirCreateResponse {
18
+ "@odata.type": "#microsoft.graph.driveItem";
19
+ createdDateTime: string;
20
+ id: string;
21
+ lastModifiedDateTime: string;
22
+ name: string;
23
+ webUrl: string;
24
+ size: number;
25
+ createdBy: {
26
+ user: {
27
+ email: string;
28
+ displayName: string;
29
+ };
30
+ };
31
+ lastModifiedBy: {
32
+ user: {
33
+ email: string;
34
+ displayName: string;
35
+ };
36
+ };
37
+ parentReference: {
38
+ driveId: string;
39
+ driveType: string;
40
+ id: string;
41
+ };
42
+ fileSystemInfo: {
43
+ createdDateTime: string;
44
+ lastModifiedDateTime: string;
45
+ };
46
+ folder?: {
47
+ childCount: number;
48
+ };
49
+ searchResult: object;
50
+ }
51
+ export interface IFileSearchResult {
52
+ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(driveItem)";
53
+ value: IDirCreateResponse[];
54
+ }
55
+ interface IFileCreateResponse {
56
+ '@odata.context': string;
57
+ '@microsoft.graph.downloadUrl': string;
58
+ createdDateTime: string;
59
+ eTag: string;
60
+ id: string;
61
+ lastModifiedDateTime: string;
62
+ name: string;
63
+ webUrl: string;
64
+ cTag: string;
65
+ size: number;
66
+ createdBy: {
67
+ application: {
68
+ id: string;
69
+ displayName: string;
70
+ };
71
+ user: {
72
+ email: string;
73
+ id: string;
74
+ displayName: string;
75
+ };
76
+ };
77
+ lastModifiedBy: {
78
+ application: {
79
+ id: string;
80
+ displayName: string;
81
+ };
82
+ user: {
83
+ email: string;
84
+ id: string;
85
+ displayName: string;
86
+ };
87
+ };
88
+ parentReference: {
89
+ driveId: string;
90
+ driveType: string;
91
+ id: string;
92
+ path: string;
93
+ };
94
+ file: {
95
+ mimeType: string;
96
+ hashes: {
97
+ quickXorHash: string;
98
+ };
99
+ };
100
+ fileSystemInfo: {
101
+ createdDateTime: string;
102
+ lastModifiedDateTime: string;
103
+ };
104
+ }
105
+ export {};
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.getMsDir = exports.getDriveAndByIdUrl = exports.getDriveUrl = void 0;
51
+ var msauth_1 = require("./msauth");
52
+ var getDriveUrl = function (driveId, path) { return "drives/".concat(driveId, "/root:/").concat(encodeURIComponent(path.replace(/['`;\\",()&^$#!%*=+[\]{}|:<>?]/g, ''))); };
53
+ exports.getDriveUrl = getDriveUrl;
54
+ var getDriveAndByIdUrl = function (driveId, itemId) { return "drives/".concat(driveId, "/items/").concat(itemId); };
55
+ exports.getDriveAndByIdUrl = getDriveAndByIdUrl;
56
+ function getMsDir(creds, prms) {
57
+ return __awaiter(this, void 0, void 0, function () {
58
+ //const getDriveUrl = () => `https://graph.microsoft.com/v1.0/users('${opt.userId}')/drive`
59
+ //const getUrl = (itemId: string, action: string) => `${getDriveUrl()}/items('${itemId}')/${action}`;
60
+ function createFile(path, data) {
61
+ return __awaiter(this, void 0, void 0, function () {
62
+ return __generator(this, function (_a) {
63
+ return [2 /*return*/, ops.doPut("".concat((0, exports.getDriveUrl)(driveId, path), ":/content"), data)];
64
+ });
65
+ });
66
+ }
67
+ function getFileByPath(fname) {
68
+ return __awaiter(this, void 0, void 0, function () {
69
+ return __generator(this, function (_a) {
70
+ return [2 /*return*/, ops.doGet("".concat((0, exports.getDriveUrl)(driveId, fname), ":/content"), function (cfg) {
71
+ return __assign(__assign({}, cfg), { responseType: 'arraybuffer' });
72
+ })];
73
+ });
74
+ });
75
+ }
76
+ function createDir(path, name) {
77
+ return __awaiter(this, void 0, void 0, function () {
78
+ return __generator(this, function (_a) {
79
+ return [2 /*return*/, ops.doPost("".concat((0, exports.getDriveUrl)(driveId, path), ":/children"), {
80
+ name: name,
81
+ "folder": {},
82
+ "@microsoft.graph.conflictBehavior": "replace"
83
+ })];
84
+ });
85
+ });
86
+ }
87
+ var ops, driveId, itmInf, message;
88
+ return __generator(this, function (_a) {
89
+ switch (_a.label) {
90
+ case 0: return [4 /*yield*/, (0, msauth_1.getDefaultMsGraphConn)(creds, prms.logger)];
91
+ case 1:
92
+ ops = _a.sent();
93
+ driveId = prms.driveId;
94
+ if (!!driveId) return [3 /*break*/, 3];
95
+ return [4 /*yield*/, ops.getSharedItemInfo(prms.sharedUrl)];
96
+ case 2:
97
+ itmInf = _a.sent();
98
+ if (!itmInf.parentReference) {
99
+ message = "bad sharedUrl ".concat(prms.sharedUrl);
100
+ prms.logger(message);
101
+ throw {
102
+ message: message
103
+ };
104
+ }
105
+ driveId = itmInf.parentReference.driveId;
106
+ _a.label = 3;
107
+ case 3: return [2 /*return*/, {
108
+ //doGet,
109
+ //doPost,
110
+ //doSearch: (itemId: string, name: string) => doSearch(itemId, name, doGet),
111
+ createFile: createFile,
112
+ //getFileById,
113
+ getFileByPath: getFileByPath,
114
+ createDir: createDir,
115
+ driveId: driveId,
116
+ }];
117
+ }
118
+ });
119
+ });
120
+ }
121
+ exports.getMsDir = getMsDir;
122
+ function doSearch(itemId, name, doGet) {
123
+ return __awaiter(this, void 0, void 0, function () {
124
+ var res;
125
+ return __generator(this, function (_a) {
126
+ switch (_a.label) {
127
+ case 0: return [4 /*yield*/, doGet(itemId, "search(q='".concat(name, "')"))];
128
+ case 1:
129
+ res = _a.sent();
130
+ return [2 /*return*/, res];
131
+ }
132
+ });
133
+ });
134
+ }
@@ -0,0 +1 @@
1
+ export {};