forked from Richienb/drive-url
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
34 lines (26 loc) · 912 Bytes
/
index.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
const formatRegexes = new Set([
/https:\/\/drive\.google\.com\/file\/d\/(?<id>.*?)\/(?:edit|view)/,
/https:\/\/drive\.google\.com\/open\?id=(?<id>.*?)$/,
]);
const alphanumericRegex = /^[\w-]+$/;
function extractId(urlOrId) {
for (const format of formatRegexes) {
if (format.test(urlOrId)) {
return format.exec(urlOrId).groups.id;
}
}
if (alphanumericRegex.test(urlOrId)) {
return urlOrId;
}
throw new Error('Invalid URL provided.');
}
export default function driveUrl(url, {apiKey} = {}) {
if (typeof url !== 'string') {
throw new TypeError('Invalid URL provided.');
}
if (typeof apiKey === 'string' && !alphanumericRegex.test(apiKey)) {
throw new Error('Invalid api key provided.');
}
const id = extractId(url.trim());
return apiKey ? `https://www.googleapis.com/drive/v3/files/${id}?alt=media&key=${apiKey.trim()}` : `https://drive.google.com/uc?export=download&id=${id}`;
}