-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonedrive.rs
339 lines (286 loc) · 9.47 KB
/
onedrive.rs
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
use std::{
io::Read,
time::{SystemTime, UNIX_EPOCH},
};
use curl::easy::{Easy, Form, List};
use serde::{Deserialize, Serialize};
use crate::{parse_iso_date, urlencode, Account, DriveDelta, DriveDeltaType, Token};
const CLIENT_ID: &str = "3dceca68-abd4-46a1-9e72-9dda8a80d9c1";
const REDIRECT_URL: &str = "https://login.microsoftonline.com/common/oauth2/nativeclient";
const SCOPES: &str = "User.Read%20Files.ReadWrite.All%20offline_access";
pub fn get_oauth_url() -> String {
let auth_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
format!(
"{}?client_id={}&response_type=code&redirect_uri={}&scope={}",
auth_url, CLIENT_ID, REDIRECT_URL, SCOPES,
)
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
struct FileProperties {
mimeType: Option<String>,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
struct FolderProperties {
childCount: Option<u32>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct ParentReference {
path: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Deleted {
state: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone)]
struct OneDriveItem {
id: String,
name: Option<String>,
// Deleted files do not have
// path in parent reference
parentReference: ParentReference,
lastModifiedDateTime: Option<String>,
file: Option<FileProperties>,
folder: Option<FolderProperties>,
deleted: Option<Deleted>,
}
#[derive(Serialize, Deserialize, Debug)]
struct OneDriveListItems {
#[serde(rename = "@odata.nextLink")]
next_link: Option<String>,
#[serde(rename = "@odata.deltaLink")]
delta_link: Option<String>,
value: Vec<OneDriveItem>,
}
fn get_delta(account: &mut Account, api_url: &str, items: &mut Vec<OneDriveItem>) {
let mut headers = List::new();
headers
.append(format!("Authorization:Bearer {}", account.token.access_token).as_str())
.unwrap();
let mut handle = Easy::new();
let mut response_body = Vec::new();
handle.url(api_url).unwrap();
handle.http_headers(headers).unwrap();
{
let mut transfer = handle.transfer();
transfer
.write_function(|data| {
response_body.extend_from_slice(data);
Ok(data.len())
})
.unwrap();
transfer.perform().unwrap();
}
let drive_items = serde_json::from_slice::<OneDriveListItems>(&response_body).unwrap();
items.extend(drive_items.value);
// Last page conatins deltaLink for next time
// sync
if let Some(delta_link) = drive_items.delta_link {
let delta_link_key = "delta_link".to_string();
account.attributes.insert(delta_link_key, delta_link);
}
if let Some(next_link) = drive_items.next_link {
get_delta(account, next_link.as_str(), items);
}
}
pub fn download_file(account: &Account, item_path: &str) -> Result<Vec<u8>, String> {
let mut headers = List::new();
headers
.append(format!("Authorization:Bearer {}", account.token.access_token).as_str())
.unwrap();
let item_path_escaped = urlencode(item_path);
let api_url = format!(
"https://graph.microsoft.com/v1.0/me/drive/root:/{}:/content",
item_path_escaped
);
let mut handle = Easy::new();
let mut response_body = Vec::new();
handle.url(&api_url).unwrap();
handle.follow_location(true).unwrap();
handle.http_headers(headers).unwrap();
handle.fail_on_error(true).unwrap();
{
let mut transfer = handle.transfer();
transfer
.write_function(|data| {
response_body.extend_from_slice(data);
Ok(data.len())
})
.unwrap();
transfer
.perform()
.map_err(|err| format!("Cannot perform request: {}", err))?;
}
Ok(response_body)
}
pub fn upload_new_file(
account: &Account,
item_path: &str,
mut contents: &[u8],
) -> Result<String, String> {
let mut headers = List::new();
headers
.append(format!("Authorization:Bearer {}", account.token.access_token).as_str())
.unwrap();
headers.append("Content-Type: text/plain").unwrap();
let item_path_escaped = urlencode(item_path);
let api_url = format!(
"https://graph.microsoft.com/v1.0/me/drive/root:{}:/content",
item_path_escaped
);
let mut handle = Easy::new();
let mut response_body = Vec::new();
handle.url(&api_url).unwrap();
handle.http_headers(headers).unwrap();
handle.put(true).unwrap();
handle.fail_on_error(true).unwrap();
{
let mut transfer = handle.transfer();
transfer
.read_function(|into| Ok(contents.read(into).unwrap()))
.unwrap();
transfer
.write_function(|data| {
response_body.extend_from_slice(data);
Ok(data.len())
})
.unwrap();
transfer
.perform()
.map_err(|err| format!("Cannot perform request: {}", err))?;
}
let drive_item: OneDriveItem = serde_json::from_slice(&response_body)
.map_err(|err| format!("Cannot parse response: {}", err))?;
Ok(drive_item.id)
}
pub fn delete_file(account: &Account, cloud_id: &str) -> Result<(), String> {
let mut headers = List::new();
headers
.append(format!("Authorization:Bearer {}", account.token.access_token).as_str())
.unwrap();
headers.append("Content-Type: text/plain").unwrap();
let api_url = format!(
"https://graph.microsoft.com/v1.0/me/drive/items/{}",
cloud_id
);
let mut handle = Easy::new();
handle.url(&api_url).unwrap();
handle.http_headers(headers).unwrap();
handle.custom_request("DELETE").unwrap();
handle.fail_on_error(true).unwrap();
handle
.perform()
.map_err(|err| format!("Cannot perform request: {}", err))
}
pub fn get_drive_delta(account: &mut Account) -> Result<Vec<DriveDelta>, String> {
let mut files = Vec::new();
let root_delta_link = "https://graph.microsoft.com/v1.0/me/drive/root/delta".to_string();
let delta_link_key = "delta_link".to_string();
let delta_link = match account.attributes.get(&delta_link_key) {
Some(val) => val.clone(),
None => root_delta_link.clone(),
};
get_delta(account, &delta_link, &mut files);
let mut cloud_files = Vec::new();
for file in files {
// Skipping folders
if file.folder.is_some() {
continue;
}
if file.name.is_none() {
continue;
}
let file_name = file.name.unwrap();
if file_name.is_empty() {
continue;
}
let file_path = if let Some(mut parent) = file.parentReference.path {
let folder = parent.split_off(12);
format!("{}/{}", folder, file_name)
} else {
format!("/{}", file_name)
};
let last_modified = parse_iso_date(&file.lastModifiedDateTime.unwrap());
cloud_files.push(DriveDelta {
cloud_id: file.id,
file_path,
last_modified,
delta_type: if file.deleted.is_some() {
DriveDeltaType::Deleted
} else {
DriveDeltaType::CreatedOrModifiled
},
});
}
Ok(cloud_files)
}
#[derive(Serialize, Deserialize)]
struct MicrosoftGraphToken {
access_token: String,
refresh_token: String,
expires_in: u64,
}
pub fn get_token(code: &str, grant_type: &str) -> Result<Token, String> {
let mut form = Form::new();
form.part("client_id")
.contents(CLIENT_ID.as_bytes())
.add()
.unwrap();
form.part("redirect_uri")
.contents(REDIRECT_URL.as_bytes())
.add()
.unwrap();
form.part("grant_type")
.contents(grant_type.as_bytes())
.add()
.unwrap();
match grant_type {
"authorization_code" => {
form.part("code").contents(code.as_bytes()).add().unwrap();
}
"refresh_token" => {
form.part("refresh_token")
.contents(code.as_bytes())
.add()
.unwrap();
}
_ => return Err("Invalid grant_type".to_string()),
};
let api_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
let mut handle = Easy::new();
let mut response_body = Vec::new();
handle.url(api_url).unwrap();
handle.httppost(form).unwrap();
handle.fail_on_error(true).unwrap();
{
let mut transfer = handle.transfer();
transfer
.write_function(|data| {
response_body.extend_from_slice(data);
Ok(data.len())
})
.unwrap();
transfer
.perform()
.map_err(|err| format!("Cannot perform request: {}", err))?;
}
let microsoft_token: MicrosoftGraphToken =
serde_json::from_slice(&response_body).map_err(|err| {
format!(
"Cannot parse response please relogin : {} :\n{}",
grant_type, err
)
})?;
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_secs();
Ok(Token {
access_token: microsoft_token.access_token,
refresh_token: microsoft_token.refresh_token,
valid_till: since_the_epoch + microsoft_token.expires_in,
})
}