-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
473 lines (425 loc) · 14.5 KB
/
App.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
View,
Text,
Dimensions,
PermissionsAndroid,
TouchableHighlight,
ActivityIndicator
} from 'react-native';
import GoogleSignIn from 'react-native-google-sign-in';
import GDrive from "react-native-google-drive-api-wrapper";
import RNFS from "react-native-fs"
import Video from "react-native-video";
const { width, height } = Dimensions.get('window');
let apiToken = null
const min = 1;
const max = 1000;
const random = min + (Math.random() * (max - min));
const url = 'https://www.googleapis.com/drive/v3' // demo method to understand easier https://developers.google.com/drive/v3/reference/files/list
const uploadUrl = 'https://www.googleapis.com/upload/drive/v3'
const downloadHeaderPath = `${RNFS.ExternalDirectoryPath}/MyVideos_${random}.mp4` // see more path directory https://github.com/itinance/react-native-fs#api
const boundaryString = 'foo_bar_baz' // can be anything unique, needed for multipart upload https://developers.google.com/drive/v3/web/multipart-upload
import ImagePicker from 'react-native-image-picker';
//react-native-camera-roll-picker
/**
* Set api token
*/
function setApiToken(token) {
//console.warn(token)
apiToken = token
}
/**
* require write storage permission
*/
async function requestWriteStoragePermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
'title': 'Write your android storage Permission',
'message': 'Write your android storage to save your data'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can write storage")
} else {
console.log("Write Storage permission denied")
}
} catch (err) {
console.warn(err)
}
}
/**
* * require read storage permission
*/
async function requestReadStoragePermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
'title': 'Read your android storage Permission',
'message': 'Read your android storage to save your data'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can Read storage")
} else {
console.log("Read Storage permission denied")
}
} catch (err) {
console.warn(err)
}
}
export default class App extends React.PureComponent {
constructor(props) {
super(props);
this.checkPermission()
this.imageUri = undefined
}
state = {
data: null,
messageImage: undefined,
isLoading: false,
driveVideoURL: 'https://drive.google.com/file/d/1zsbeKc9r_yznL-xEDFnNUnofNKyFJQjk/view',
uploadingDownloading: false,
downloadedDriveVideoObj: undefined,
//Need to save database
rootFolderId: undefined,
driveUploadedVideoID: undefined
}
componentDidMount() {
}
// check storage permission
checkPermission = () => {
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE).then((writeGranted) => {
console.log('writeGranted', writeGranted)
if (!writeGranted) {
requestWriteStoragePermission()
}
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE).then((readGranted) => {
console.log('readGranted', readGranted)
if (!readGranted) {
requestReadStoragePermission()
}
})
})
}
getDataFromGoogleDrive = async () => {
await this.initialGoogle()
if (apiToken) {
this.checkFile()
}
}
setDataFromGoogleDrive = async (calling_type) => {
await this.initialGoogle()
if (apiToken) {
if (calling_type == 'upload_video') {
this.finalUploadImageVideoDrive()
} else {
this.createFolderDrive()
}
}
}
//scropes: 'https://www.googleapis.com/auth/drive.appdata'
//scopes:'https://www.googleapis.com/auth/drive' Full, permissive scope to access all of a user's files, excluding the Application Data folder.
//scopes:'https://www.googleapis.com/auth/drive.activity' Allows read and write access to the Drive Activity API.
//scopes:'https://www.googleapis.com/auth/drive.metadata' Allows read-write access to file metadata (excluding downloadUrl and contentHints.thumbnail),
//but does not allow any access to read, download, write or upload file content. Does not support file creation, trashing or deletion.
//Also does not allow changing folders or sharing in order to prevent access escalation.
initialGoogle = async () => {
// ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.metadata']
await GoogleSignIn.configure({
scopes: ['https://www.googleapis.com/auth/drive'],
shouldFetchBasicProfile: true,
offlineAccess: true
});
const user = await GoogleSignIn.signInPromise();
//set api token
setApiToken(user.accessToken)
}
selectPhotoTapped = () => {
const options = {
title: "Choose Video",
mediaType: "video"
};
let that = this
ImagePicker.showImagePicker(options, (response) => {
let sourceUri = undefined;
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
// that.setState({
// isLoading: false,
// });
} else if (response.error) {
console.log('ImagePicker Error: ', response);
var message = 'To be able to take pictures with your camera and choose images from your library.'
that.twoButtonAlert('Permission denied', message, 'RE-TRY', 'I\'M SURE', function (status) {
console.log('The button tapped is: ', status);
if (status == 1) {
that.openSettingsPage()
}
}, function (error) {
console.log('There was an error fetching the location');
});
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
// that.setState({
// isLoading: true,
// });
} else {
sourceUri = { uri: response.uri };
console.warn('sourceUri' + JSON.stringify(response))
that.setState({
imageUri: response
}, () => {
this.setDataFromGoogleDrive('upload_video')
})
}
});
}
finalUploadImageVideoDrive = () => {
if (apiToken != null && apiToken != undefined) {
GDrive.setAccessToken(apiToken);
GDrive.init();
GDrive.isInitialized() ? true : false;
this.setState({
uploadingDownloading: true
})
RNFS.readFile(this.state.imageUri.path, 'base64')
.then((res => {
GDrive.files.createFileMultipart(
res,
"video/mp4",//"video/mp4", image/jpg
{
parents: ["1WYGqCQv8BHlpGjDsM5-yIVdkhQgTSxrR"], //or any path
name: "my_second.mp4"
},
true)//make it true because you are passing base64 string otherwise the uploaded file will be not supported
.then((response) => {
this.setState({
uploadingDownloading: false
})
this.getVideoIdDrive('my_second.mp4', '1WYGqCQv8BHlpGjDsM5-yIVdkhQgTSxrR', 'video/mp4')
})
.catch((message) => {
this.setState({
uploadingDownloading: false
})
console.warn(message)
})
}))
} else {
alert('Token not found for upload video on google drive!!')
}
}
createFolderDrive = () => {
if (apiToken != null && apiToken != undefined) {
GDrive.setAccessToken(apiToken);
GDrive.init();
GDrive.isInitialized() ? true : false;
GDrive.files.safeCreateFolder({
name: "praveen_singh",
parents: ["root"]
})
.then((response) => {
this.setState({
rootFolderId: response
})
}).
catch((message) => {
console.warn(message)
})
} else {
alert('Token not found for create folder!!')
}
}
getVideoIdDrive = (name, parent, mimeType) => {
console.warn('parentt' + JSON.stringify(parent))
GDrive.setAccessToken(apiToken);
GDrive.init();
GDrive.isInitialized() ? true : false;
GDrive.files.getId(name, [parent], mimeType, false)
.then((response) => {
this.setState({
driveUploadedVideoID: response
})
}).
catch((message) => {
console.warn('videoIDDrive' + message)
})
}
downloadVideoFromDrive = () => {
GDrive.setAccessToken(apiToken);
GDrive.init();
GDrive.isInitialized() ? true : false;
this.setState({
uploadingDownloading: true
})
const queryParams = { alt: "media" };
GDrive.files.get(this.state.driveUploadedVideoID, queryParams)
.then((response) => {
console.warn('downloadingFile' + JSON.stringify(response))
this.setState({
uploadingDownloading: false
})
})
}
// download and read file to get data content in downloaded file
downloadAndReadFile = () => {
const fromUrl = this.downloadFile(this.state.driveUploadedVideoID)
let downloadFileOptions = {
fromUrl: fromUrl,
toFile: downloadHeaderPath,
}
downloadFileOptions.headers = Object.assign({
"Authorization": `Bearer ${apiToken}`
}, downloadFileOptions.headers);
this.setState({
uploadingDownloading: true
})
console.warn('downloadFileOptions', JSON.stringify(downloadFileOptions))
RNFS.downloadFile(downloadFileOptions).promise.then(res => {
console.warn('downloadFileObj1' + JSON.stringify(res))
this.setState({
uploadingDownloading: false
})
return RNFS.readFile(downloadHeaderPath, 'utf8');
}).then(content => {
console.warn('downloadFileObj2' + JSON.stringify(content))
// this.setState({
// downloadedDriveVideoObj: content
// })
}).catch(err => {
console.log('error downloadFileObj', err)
});
}
/**
* create download url based on id
*/
downloadFile = (existingFileId) => {
console.log(existingFileId)
if (!existingFileId) throw new Error('Didn\'t provide a valid file id.')
return `${url}/files/${existingFileId}?alt=media`
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight style={styles.buttonGetData} onPress={() => {
//this.setDataFromGoogleDrive('create_folder')
this.downloadAndReadFile()
//this.downloadVideoFromDrive()
//this.getDataFromGoogleDrive
}}>
<Text style={styles.text}>
Get data from Google Drive/Create Folder
</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonGetData} onPress={() => {
this.selectPhotoTapped()
}}>
<Text style={styles.text}>
Create data or Update data
</Text>
</TouchableHighlight>
{this.state.uploadingDownloading &&
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}
>
<ActivityIndicator size="large" color="#0000ff" />
{/* <Text>{Math.floor(this.state.progress * 100)}%</Text> */}
<Text> Please wait while Uploding/Downloading video </Text>
</View>
}
{/* {this.state.driveVideoURL != undefined &&
<Video
source={{
uri: 'https://www.googleapis.com/drive/v3/files?/1zsbeKc9r_yznL-xEDFnNUnofNKyFJQjk?alt=mediaS&name=my_first_video.mp4',//'https://gdurl.com/zxRE',
//'https://drive.google.com/open?id=1zsbeKc9r_yznL-xEDFnNUnofNKyFJQjk&name=my_first_video.mp4'
headers: {
Authorization: 'Bearer ya29.ImDBB7EOdNLF_cL7VTrgxOrraYyNDCjmxUq4CymRpVutTUD3xYuG9kLUk74dTYH7iyzrclDfz9LH3tXA5fxY1v4K3wztI2QXtZI78kcHeurH3HQsh76uL8N-xFuFApsNXTg',
}
}}
style={{
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0
}}
//poster={this.state.thumbnail}
fullscreen={true}
resizeMode="contain"
controls={true}
//onEnd={() => this.setState({ playVideo: false })}
/>} */}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
textAlign: 'center',
color: '#FFFFFF',
margin: 10,
},
textData: {
textAlign: 'center',
color: '#333333',
margin: 10,
},
buttonGetData: {
backgroundColor: '#333',
padding: 10,
margin: 10,
}
});
// var photo = {
// uri: 'file:///storage/emulated/0/Pictures/images/image-dd85ef2d-0b3b-4fca-9015-9787f9a3666a.jpg',
// type: ['image/png', 'image/jpeg', 'image/jpg'],
// name: 'image-dd85ef2d-0b3b-4fca-9015-9787f9a3666a.jpg',
// };
// let header = {
// 'Authorization': `Bearer ${'ya29.Il_AB9LHI1vO586z8ZX6lUSS2pzYdAbc9WPU89wwQpIwFjue6o3k75kqfM7hwlrJer8ubODoGx06Qh99a0-D9sSd2NmA2T15R76R7XCveSiCi3AuEjmLJt5aJeR45I8tzA'}`,
// 'Accept': 'application/json',
// //'Content-Type': 'multipart/form-data',
// 'Content-Type': ['image/png', 'image/jpeg', 'image/jpg'],
// }
// const ending = `\n${'foo_bar_baz'}--`;
// let body = `\n${'foo_bar_baz'}\n` +
// `Content-Type: ${'application/json; charset=UTF-8'}\n\n` +
// `${JSON.stringify({
// parents: ["root"], //or any path
// name: "photo2.jpg"
// })}\n\n${'foo_bar_baz'}\n` + `Content-Type: ${"'image/jpeg'"}\n\n`;
// body += `${'file:///storage/emulated/0/Pictures/images/image-dd85ef2d-0b3b-4fca-9015-9787f9a3666a.jpg'}${ending}`;
// // let body = {
// // uri: 'file:///storage/emulated/0/Pictures/images/image-dd85ef2d-0b3b-4fca-9015-9787f9a3666a.jpg',
// // mimeType:['image/png', 'image/jpeg', 'image/jpg'],
// // name:'abc.jpg'
// // };
// //multipart
// fetch(uploadUrl + '/files?uploadType=media', { method: 'POST', headers: header, body: body })
// .then((response) => {
// console.warn('responseUPLOAD1' + JSON.stringify(response))
// })
// .then((responseJson) => {
// console.warn('responseUPLOAD2' + JSON.stringify(responseJson))
// })
// .catch((err) => {
// console.log('responseUPLOAD3' + JSON.stringify(err))
// console.log(err)
// });