-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
236 lines (201 loc) · 6.02 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
var url = require('url')
var request = require('request')
var concat = require('concat-stream')
var mime = require('mime-types')
var through = require('through2')
var duplexify = require('duplexify')
var formEncoder = require('form-urlencoded')
var debug = require('debug')('google-drive-blobs')
// google APIs are weird
var baseURL = 'https://www.googleapis.com/drive/v2/'
var uploadBaseURL = 'https://www.googleapis.com/upload/drive/v2/'
function Blobs(options) {
if (!(this instanceof Blobs)) return new Blobs(options)
this.options = options
}
module.exports = Blobs
Blobs.prototype.createWriteStream = function(options, cb) {
var self = this
if (!options) options = {}
var filename = options.filename
var mimeType
if (filename) {
mimeType = mime.lookup(filename)
}
var parentID = options.parent
var metaOpts = {
query: '?uploadType=resumable',
json: {
title: filename,
mimeType: mimeType
},
contentType: 'application/json'
}
if (parentID) metaOpts.json.parents = [{
"kind": "drive#fileLink",
"id": parentID
}]
// always start by refreshing the token to make sure it's active
self.refreshToken(function(err, resp, body) {
if (err) {
return cb(err)
}
self.request(metaOpts, function(err, resp, body) {
if (err || resp.statusCode > 299) return cb(err || resp.headers)
var parsed = url.parse(resp.headers.location, true)
var session = parsed.query.upload_id
upload(session)
})
})
var proxy = through()
return proxy
function upload(session) {
var opts = {
query: '?uploadType=resumable&upload_id=' + session
}
var put = self.request(opts)
put.on('response', function(resp) {
resp.pipe(handleUploadResponse())
})
put.on('error', function(err) {
cb(err)
})
proxy.pipe(put)
function handleUploadResponse() {
return concat(function(body) {
var response = JSON.parse(body)
self.addProperty(response.id, 'key', response.md5Checksum, function(err, resp, props) {
if (err) return cb(err)
if (resp.statusCode > 299) return cb(new Error(JSON.stringify(props)))
response.key = response.md5Checksum
response.size = +response.fileSize
if (process.env['DEBUG']) debug('createWriteStream done', JSON.stringify(response))
cb(null, response)
})
})
}
}
}
Blobs.prototype.addProperty = function(id, key, val, cb) {
var hashProp = {
"kind": "drive#property",
"key": key,
"value": val
}
var reqOpts = {
url: baseURL + 'files/' + id + '/properties',
json: hashProp,
contentType: 'application/json'
}
return this.request(reqOpts, cb)
}
Blobs.prototype.createReadStream = function(opts) {
var self = this
var duplex = duplexify()
debug('createReadStream', JSON.stringify(opts))
self.get(opts.key, function(err, file) {
if (err) return duplex.destroy(err)
if (!file) return duplex.destroy(new Error('Blob not found'))
var req = self.request({
url: file.downloadUrl,
method: 'GET',
})
duplex.setReadable(req)
})
return duplex
}
Blobs.prototype.exists = function(opts, cb) {
var self = this
self.get(opts.key, function(err, file) {
if (err) return cb(err)
cb(null, !!file)
})
}
Blobs.prototype.mkdir = function(filename, opts, cb) {
var self = this
var reqOpts = {
json: {
title: filename,
mimeType: "application/vnd.google-apps.folder"
},
contentType: 'application/json',
base: opts.baseURL
}
var put = self.request(reqOpts, cb)
}
Blobs.prototype.request = function(opts, cb) {
var self = this
if (!opts) opts = {}
var token = self.options.access_token
if (!token) return cb(new Error('you must specify google token'))
var reqOpts = {
method: opts.method || 'POST',
url: (opts.base || uploadBaseURL) + 'files' + (opts.query || ''),
headers: {
'Content-Type': opts.contentType || 'text/plain',
'Authorization': "Bearer " + token
},
json: opts.json
}
if (opts.url) reqOpts.url = opts.url
return request(reqOpts, function(err, resp, body) {
if (process.env['DEBUG']) {
var bodyStr = body
if (bodyStr && typeof bodyStr.length === 'undefined') bodyStr = JSON.stringify(bodyStr)
debug(resp.statusCode, JSON.stringify(reqOpts), bodyStr)
}
// token may have expired, refresh + retry
if (resp.statusCode > 299) return self.refreshToken(function(err) {
if (err) return cb(err)
request(reqOpts, cb)
})
if (cb) cb(err, resp, body)
})
}
Blobs.prototype.get = function(hash, cb) {
var self = this
var query = "properties has { key='key' and value='" + hash + "' and visibility='PRIVATE' } and trashed = false"
var reqOpts = {
contentType: 'application/json',
query: '?' + formEncoder.encode({q: query}),
method: 'GET',
base: baseURL,
json: true
}
return self.request(reqOpts, function(err, resp, results) {
if (err || resp.statusCode > 299) return cb(results)
cb(null, results.items[0])
})
}
Blobs.prototype.remove = function(opts, cb) {
var self = this
self.get(opts.key, function(err, file) {
if (err) return cb(err)
var reqOpts = {
method: 'DELETE',
url: baseURL + 'files/' + file.id
}
self.request(reqOpts, function(err, resp, results) {
if (err || resp.statusCode > 299) return cb(results || new Error('could not delete'))
cb(null)
})
})
}
Blobs.prototype.refreshToken = function(cb) {
var self = this
var opts = {
refresh_token: self.options.refresh_token,
client_id: self.options.client_id,
client_secret: self.options.client_secret,
grant_type: 'refresh_token'
}
request.post('https://accounts.google.com/o/oauth2/token', {
form: opts,
json: true
}, function (err, res, body) {
if (err) return cb(err, res, body)
if (res.statusCode > 299) return cb(new Error('refresh error'), res, body)
self.options.access_token = body.access_token
cb(null, res, body)
})
}