-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathonedrive.js
95 lines (83 loc) · 2.67 KB
/
onedrive.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
import { decode } from 'jsonwebtoken';
import oneDriveAPI from "onedrive-api";
import fs from 'fs'
import axios from "axios";
const clientID = ''
const clientSecret = ''
const refreshToken = ""
let token = '' // essa variavel é preenchida automaticamente.
const onedriveFolder = "0-ipcam"
const addZero = (num) => num.toString().padStart(2, '0');
export default async function sendFile(filepath) {
let atualToken = await getOneDriveToken()
const date = new Date()
const folder = `${onedriveFolder}/${addZero(date.getDate())}-${addZero(date.getMonth() + 1)}-${date.getFullYear()}`
const filename =
addZero(date.getDate()) +
'-' +
addZero(date.getMonth() + 1) +
'-' +
date.getFullYear() +
'_' +
addZero(date.getHours()) +
';' +
addZero(date.getMinutes()) +
';' +
addZero(date.getSeconds()) +
'.mp4';
try {
let result = await oneDriveAPI.items
.uploadSimple({
accessToken: atualToken,
filename: filename,
parentPath: folder,
readableStream: fs.createReadStream(filepath),
})
console.log("sucesso")
return result
} catch (error) {
console.log(error)
}
}
async function getOneDriveToken() {
if (token.length > 1) {
let valido = verificarToken(token)
if (valido) return token
}
const bodyFormData = new FormData();
bodyFormData.append('client_id', clientID);
bodyFormData.append('scope', 'files.readwrite.all');
bodyFormData.append('refresh_token', refreshToken);
bodyFormData.append('grant_type', "refresh_token");
bodyFormData.append('client_secret', clientSecret);
try {
const response = await axios({
method: "post",
url: 'https://#.microsoftonline.com/organizations/oauth2/v2.0/token',
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
console.log('atualizando token')
token = response.data.access_token
return response.data.access_token
} catch (error) {
console.error(error);
}
}
function verificarToken(token) {
try {
const decoded = decode(token);
const exp = decoded.exp;
// Obtenha a data atual em segundos
const now = Math.floor(Date.now() / 1000);
// Verifique se a data de expiração (exp) ainda não foi ultrapassada
if (exp > now) {
return true;
} else {
return false;
}
} catch (error) {
console.error('Erro ao decodificar o token:', error.message);
return false;
}
}