-
Notifications
You must be signed in to change notification settings - Fork 2k
/
index.js
297 lines (256 loc) · 9.34 KB
/
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
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
/* eslint-disable no-underscore-dangle */
const request = require('request')
const purest = require('purest')({ request })
const { promisify } = require('util')
const Provider = require('../Provider')
const logger = require('../../logger')
const adapter = require('./adapter')
const { ProviderApiError, ProviderAuthError } = require('../error')
const { requestStream } = require('../../helpers/utils')
const DRIVE_FILE_FIELDS = 'kind,id,imageMediaMetadata,name,mimeType,ownedByMe,permissions(role,emailAddress),size,modifiedTime,iconLink,thumbnailLink,teamDriveId,videoMediaMetadata,shortcutDetails(targetId,targetMimeType)'
const DRIVE_FILES_FIELDS = `kind,nextPageToken,incompleteSearch,files(${DRIVE_FILE_FIELDS})`
// using wildcard to get all 'drive' fields because specifying fields seems no to work for the /drives endpoint
const SHARED_DRIVE_FIELDS = '*'
// Hopefully this name will not be used by Google
const VIRTUAL_SHARED_DIR = 'shared-with-me'
async function waitForFailedResponse (resp) {
const buf = await new Promise((resolve) => {
let data = ''
resp.on('data', (chunk) => {
data += chunk
}).on('end', () => resolve(data))
resp.resume()
})
return JSON.parse(buf.toString())
}
function adaptData (listFilesResp, sharedDrivesResp, directory, query, showSharedWithMe) {
const adaptItem = (item) => ({
isFolder: adapter.isFolder(item),
icon: adapter.getItemIcon(item),
name: adapter.getItemName(item),
mimeType: adapter.getMimeType(item),
id: adapter.getItemId(item),
thumbnail: adapter.getItemThumbnailUrl(item),
requestPath: adapter.getItemRequestPath(item),
modifiedDate: adapter.getItemModifiedDate(item),
size: adapter.getItemSize(item),
custom: {
isSharedDrive: adapter.isSharedDrive(item),
imageHeight: adapter.getImageHeight(item),
imageWidth: adapter.getImageWidth(item),
imageRotation: adapter.getImageRotation(item),
imageDateTime: adapter.getImageDate(item),
videoHeight: adapter.getVideoHeight(item),
videoWidth: adapter.getVideoWidth(item),
videoDurationMillis: adapter.getVideoDurationMillis(item),
},
})
const items = adapter.getItemSubList(listFilesResp)
const sharedDrives = sharedDrivesResp ? sharedDrivesResp.drives || [] : []
// “Shared with me” is a list of shared documents,
// not the same as sharedDrives
const virtualItem = showSharedWithMe && ({
isFolder: true,
icon: 'folder',
name: 'Shared with me',
mimeType: 'application/vnd.google-apps.folder',
id: VIRTUAL_SHARED_DIR,
requestPath: VIRTUAL_SHARED_DIR,
})
const adaptedItems = [
...(virtualItem ? [virtualItem] : []), // shared folder first
...([...sharedDrives, ...items].map(adaptItem)),
]
return {
username: adapter.getUsername(listFilesResp),
items: adaptedItems,
nextPagePath: adapter.getNextPagePath(listFilesResp, query, directory),
}
}
/**
* Adapter for API https://developers.google.com/drive/api/v3/
*/
class Drive extends Provider {
constructor (options) {
super(options)
this.authProvider = Drive.authProvider
this.client = purest({
...options,
provider: Drive.authProvider,
alias: 'drive',
version: 'v3',
})
}
static get authProvider () {
return 'google'
}
async list (options) {
const directory = options.directory || 'root'
const query = options.query || {}
const { client } = this
const handleErrorResponse = this._error.bind(this)
const isRoot = directory === 'root'
const isVirtualSharedDirRoot = directory === VIRTUAL_SHARED_DIR
async function fetchSharedDrives (pageToken = null) {
try {
const shouldListSharedDrives = isRoot && !query.cursor
if (!shouldListSharedDrives) return undefined
const resp = await new Promise((resolve, reject) => client
.get('drives')
.qs({ fields: SHARED_DRIVE_FIELDS, pageToken, pageSize: 100 })
.auth(options.token)
.request((err, resp2) => {
if (err || resp2.statusCode !== 200) return reject(handleErrorResponse(err, resp2))
return resolve(resp2)
}))
if (!resp) return resp
const { body } = resp
const nextPageToken = body && body.nextPageToken
if (nextPageToken) {
const nextBody = await fetchSharedDrives(nextPageToken)
if (!nextBody) return body
return { ...nextBody, drives: [...body.drives, ...nextBody.drives] }
}
return body
} catch (err) {
logger.error(err, 'provider.drive.sharedDrive.error')
throw err
}
}
async function fetchFiles () {
// Shared with me items in root don't have any parents
const q = isVirtualSharedDirRoot
? `sharedWithMe and trashed=false`
: `('${directory}' in parents) and trashed=false`
const where = {
fields: DRIVE_FILES_FIELDS,
pageToken: query.cursor,
q,
// pageSize: 10, // can be used for testing pagination if you don't have many files
orderBy: 'folder,name',
includeItemsFromAllDrives: true,
supportsAllDrives: true,
}
try {
const resp = await new Promise((resolve, reject) => client
.query()
.get('files')
.qs(where)
.auth(options.token)
.request((err, resp2) => {
if (err || resp2.statusCode !== 200) return reject(handleErrorResponse(err, resp2))
return resolve(resp2)
}))
return resp && resp.body
} catch (err) {
logger.error(err, 'provider.drive.list.error')
throw err
}
}
const [sharedDrives, filesResponse] = await Promise.all([fetchSharedDrives(), fetchFiles()])
// console.log({ directory, sharedDrives, filesResponse })
return adaptData(
filesResponse,
sharedDrives,
directory,
query,
isRoot && !query.cursor, // we can only show it on the first page request, or else we will have duplicates of it
)
}
async _stats ({ id, token }) {
const getStats = async (statsOfId) => new Promise((resolve, reject) => {
this.client
.query()
.get(`files/${encodeURIComponent(statsOfId)}`)
.qs({ fields: DRIVE_FILE_FIELDS, supportsAllDrives: true })
.auth(token)
.request((err, resp) => {
if (err || resp.statusCode !== 200) return reject(this._error.bind(this)(err, resp))
return resolve(resp.body)
})
})
let stats = await getStats(id)
// If it is a shortcut, we need to get stats again on the target
if (adapter.isShortcut(stats.mimeType)) {
stats = await getStats(stats.shortcutDetails.targetId)
}
return stats
}
_exportGsuiteFile (id, token, mimeType) {
logger.info(`calling google file export for ${id} to ${mimeType}`, 'provider.drive.export')
return this.client
.query()
.get(`files/${encodeURIComponent(id)}/export`)
.qs({ supportsAllDrives: true, mimeType })
.auth(token)
.request()
}
async download ({ id: idIn, token }) {
try {
const { mimeType, id } = await this._stats({ id: idIn, token })
const req = adapter.isGsuiteFile(mimeType)
? this._exportGsuiteFile(id, token, adapter.getGsuiteExportType(mimeType))
: this.client
.query()
.get(`files/${encodeURIComponent(id)}`)
.qs({ alt: 'media', supportsAllDrives: true })
.auth(token)
.request()
return await requestStream(req, async (res) => {
try {
const jsonResp = await waitForFailedResponse(res)
return this._error(null, { ...res, body: jsonResp })
} catch (err2) {
return this._error(err2, res)
}
})
} catch (err) {
logger.error(err, 'provider.drive.download.error')
throw err
}
}
// eslint-disable-next-line class-methods-use-this
async thumbnail () {
// not implementing this because a public thumbnail from googledrive will be used instead
logger.error('call to thumbnail is not implemented', 'provider.drive.thumbnail.error')
throw new Error('call to thumbnail is not implemented')
}
async size ({ id, token }) {
try {
const { mimeType, size } = await this._stats({ id, token })
if (adapter.isGsuiteFile(mimeType)) {
// GSuite file sizes cannot be predetermined (but are max 10MB)
// e.g. Transfer-Encoding: chunked
return undefined
}
return parseInt(size, 10)
} catch (err) {
logger.error(err, 'provider.drive.size.error')
throw err
}
}
_logout ({ token }, done) {
this.client
.get('https://accounts.google.com/o/oauth2/revoke')
.qs({ token })
.request((err, resp) => {
if (err || resp.statusCode !== 200) {
logger.error(err, 'provider.drive.logout.error')
done(this._error(err, resp))
return
}
done(null, { revoked: true })
})
}
_error (err, resp) {
if (resp) {
const fallbackMessage = `request to ${this.authProvider} returned ${resp.statusCode}`
const errMsg = (resp.body && resp.body.error) ? resp.body.error.message : fallbackMessage
return resp.statusCode === 401 ? new ProviderAuthError() : new ProviderApiError(errMsg, resp.statusCode)
}
return err
}
}
Drive.version = 2
Drive.prototype.logout = promisify(Drive.prototype._logout)
module.exports = Drive