-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDownload.ts
162 lines (142 loc) · 5.8 KB
/
Download.ts
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
import { create as createRequest, ISPRequest } from 'sp-request';
import { getAuth, IAuthOptions } from 'node-sp-auth';
import { AuthConfig, IAuthContext } from 'node-sp-auth-config';
import * as fs from 'fs';
import * as path from 'path';
import * as mkdirp from 'mkdirp';
import * as https from 'https';
import * as colors from 'colors';
import * as request from 'request';
import { HTTPError } from 'got';
import { Logger, resolveLogLevel } from '../utils/logger';
import { IDownloadOptions } from '../interface/IDownload';
const isUrlHttps = (url: string): boolean => {
return url.split('://')[0].toLowerCase() === 'https';
};
export class Download {
private spr: ISPRequest;
private context: IAuthOptions;
private agent: https.Agent;
private logger: Logger;
constructor (context: IAuthOptions, options: IDownloadOptions = {}) {
this.initContext(context);
this.logger = new Logger(resolveLogLevel(options.logLevel));
}
public downloadFile = async (spFileAbsolutePath: string, saveTo = './'): Promise<string> => {
this.logger.info(colors.gray(`Downloading: ${colors.green(spFileAbsolutePath)}`));
const childUrlArr = spFileAbsolutePath.split('/');
childUrlArr.pop();
const childUrl = childUrlArr.join('/');
const web = await this.getWebByAnyChildUrl(childUrl);
const baseHostPath = web.Url.replace(web.ServerRelativeUrl, '');
const spRelativeFilePath = spFileAbsolutePath.replace(baseHostPath, '');
const saveFilePath = this.getSaveFilePath(saveTo, spRelativeFilePath);
const saveFolderPath = path.dirname(saveFilePath);
await mkdirp(saveFolderPath);
const req = await this.downloadFileAsStream(web.Url, spRelativeFilePath);
return new Promise((resolve, reject) => {
req.pipe(fs.createWriteStream(saveFilePath))
.on('error', reject)
.on('finish', () => resolve(saveFilePath));
});
}
public downloadFileFromSite = async (siteUrl: string, spRelativeFilePath: string, saveTo = './'): Promise<string> => {
this.logger.info(colors.gray(`Downloading: ${colors.green(spRelativeFilePath)}`));
const saveFilePath = this.getSaveFilePath(saveTo, spRelativeFilePath);
const saveFolderPath = path.dirname(saveFilePath);
await mkdirp(saveFolderPath);
const req = await this.downloadFileAsStream(siteUrl, spRelativeFilePath);
return new Promise((resolve, reject) => {
req.pipe(fs.createWriteStream(saveFilePath))
.on('error', reject)
.on('finish', () => resolve(saveFilePath));
});
}
public downloadFileAsStream = async (siteUrl: string, spRelativeFilePath: string): Promise<request.Request> => {
const hostUrl = siteUrl.split('/').slice(0, 3).join('/');
const endpointUrl = spRelativeFilePath.indexOf('/_vti_history/') !== -1
? `${hostUrl}${encodeURIComponent(spRelativeFilePath).replace(/%2F/g, '/')}`
: `${siteUrl}/_api/Web/GetFileByServerRelativeUrl(@FileServerRelativeUrl)/$value` +
`?@FileServerRelativeUrl='${encodeURIComponent(spRelativeFilePath)}'`;
const auth = await Promise.resolve(getAuth(siteUrl, this.context));
const options: request.OptionsWithUrl = {
url: endpointUrl,
headers: {
...auth.headers,
'User-Agent': 'sp-download'
},
encoding: null,
strictSSL: false,
gzip: true,
agent: isUrlHttps(siteUrl) ? this.agent : undefined,
...auth.options
};
return request.get(options);
}
private getWebByAnyChildUrl = (anyChildUrl: string): Promise<{ Url: string; ServerRelativeUrl: string }> => {
return new Promise((resolve, reject) => {
const restUrl = `${anyChildUrl}/_api/web?$select=Url,ServerRelativeUrl`;
this.spr.get(restUrl,{
headers: {
Accept: 'application/json;odata=verbose'
}
})
.then((response) => resolve(response.body.d))
.catch((err: HTTPError) => {
const statusCode = err instanceof HTTPError ? err.response.statusCode : '500';
if (statusCode === 404) {
const childUrlArr = anyChildUrl.split('/');
childUrlArr.pop();
const childUrl = childUrlArr.join('/');
if (childUrlArr.length <= 2) {
return reject(`Wrong url, can't get Web property`);
} else {
return resolve(this.getWebByAnyChildUrl(childUrl));
}
} else if (statusCode === 401) {
this.logger.error(colors.red('401, Access Denied'));
this.promptForCreds()
.then(() => resolve(this.getWebByAnyChildUrl(anyChildUrl)))
.catch(reject);
} else {
return reject(err);
}
});
});
}
private initContext = (context: IAuthOptions): void => {
this.spr = createRequest(context);
this.context = context;
this.agent = new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
keepAliveMsecs: 10000
});
}
private promptForCreds = async (): Promise<IAuthContext> => {
const context = await new AuthConfig({
authOptions: this.context,
forcePrompts: true
})
.getContext();
this.initContext(context.authOptions);
this.logger.info(colors.gray('Trying to download with new creds...'));
return context;
}
private getSaveFilePath = (saveTo: string, spRelativeFilePath: string): string => {
let saveFilePath = path.resolve(saveTo);
const originalFileName = decodeURIComponent(spRelativeFilePath).split('/').pop();
try {
if (fs.lstatSync(saveFilePath).isDirectory()) {
saveFilePath = path.join(saveFilePath, originalFileName);
}
} catch (e) {
//
}
if (path.parse(saveFilePath).ext !== path.parse(originalFileName).ext) {
saveFilePath = path.join(saveFilePath, originalFileName);
}
return saveFilePath;
}
}
export { IDownloadOptions } from '../interface/IDownload';