-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
577 lines (481 loc) · 17.3 KB
/
lib.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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use std::{
collections::HashMap,
io::{Read, Seek},
os::unix::prelude::FileExt,
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
pub mod onedrive;
const BOLD_START: &str = "\x1b[1m";
const BOLD_END: &str = "\x1b[0m";
#[derive(Serialize, Deserialize, Clone)]
pub enum SyncService {
GDrive,
Onedrive,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Token {
pub access_token: String,
pub refresh_token: String,
pub valid_till: u64,
}
#[derive(Debug)]
pub enum DriveDeltaType {
Deleted,
CreatedOrModifiled,
}
#[derive(Debug)]
pub struct DriveDelta {
pub cloud_id: String,
pub file_path: String,
pub last_modified: u64,
pub delta_type: DriveDeltaType,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Account {
pub service: SyncService,
pub token: Token,
pub last_synced: u64,
pub attributes: HashMap<String, String>,
}
#[derive(Serialize, Deserialize)]
struct Config {
accounts: HashMap<String, Account>,
}
#[derive(Serialize, Deserialize)]
struct CloudStateEntry {
cloud_id: String,
last_modified: u64,
}
#[derive(Serialize, Deserialize)]
struct CloudState {
entries: HashMap<String, CloudStateEntry>,
}
pub fn urlencode(data: &str) -> String {
data.replace(' ', "%20")
}
#[derive(Default)]
struct SyncFlags {
fresh: bool,
}
// Assuming args
// clousync sync <folder> <account_name> [--fresh/-f]
pub fn sync(args: &Vec<String>) -> Result<(), String> {
if args.len() < 4 {
return Err("Incorrect no of arguments".to_string());
}
let folder = &args[2];
let account_name = &args[3];
let folder_path = std::fs::canonicalize(folder)
.map_err(|err| format!("Cannot sync to {} because: {}", folder, err))?;
let mut sync_flags = SyncFlags::default();
// Parsing flags
// Flags come after the positional arguments
for flag in args.iter().skip(4) {
match flag.as_str() {
"--fresh" | "-f" => sync_flags.fresh = true,
_ => {
return Err("Invalid flags".to_string());
}
};
}
let folder_path_str = folder_path.to_string_lossy().to_string();
let config_path = config_path();
let config_data = std::fs::read_to_string(config_path)
.map_err(|err| format!("Cannot read config: {}", err))?;
let mut config: Config = serde_json::from_str(config_data.as_str())
.map_err(|err| format!("Cannot read config: {}", err))?;
if let Some(account) = config.accounts.get_mut(account_name) {
sync_files(account, account_name, &folder_path_str, &sync_flags)?;
} else {
return Err("Unknown account name please login first".to_string());
}
Ok(())
}
// Assuming args
// clousync login <gdrive|onedrive>
pub fn login(args: &Vec<String>) -> Result<(), String> {
if args.len() < 3 {
return Err("Incorrect no of arguments".to_string());
}
match args[2].as_str() {
"onedrive" => {
let login_url = onedrive::get_oauth_url();
println!(
"{}Copy paste this url to browser{}: \n\n{}",
BOLD_START, BOLD_END, login_url
);
}
"gdrive" => todo!(),
_ => {
return Err("Please specify a service".to_string());
}
};
Ok(())
}
// Assuming args
// clousync save <gdrive|onedrive> <account_name> <auth_code>
pub fn save(args: &Vec<String>) -> Result<(), String> {
if args.len() < 5 {
return Err("Incorrect no of arguments".to_string());
}
let service = match args[2].as_str() {
"gdrive" => SyncService::GDrive,
"onedrive" => SyncService::Onedrive,
_ => {
return Err("Incorrect sync service".to_string());
}
};
let account_name = &args[3];
let auth_code = &args[4];
let token = match service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => onedrive::get_token(auth_code, "authorization_code"),
}?;
let account = Account {
service: SyncService::Onedrive,
token,
last_synced: 0,
attributes: HashMap::new(),
};
save_account(account_name, &account)?;
println!("INFO: Account saved");
Ok(())
}
fn config_path() -> String {
// TODO: figure out home dir for windows
let home = std::env!("HOME");
format!("{home}/.config/cloudsync.json")
}
// NOTE: We're cloning the entire account struct
// So this will be a costly operation
fn save_account(account_name: &str, account: &Account) -> Result<(), String> {
let config_path = config_path();
let mut config_file = std::fs::File::options()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(config_path)
.map_err(|err| format!("Cannot create config file: {}", err))?;
let mut config_data = String::new();
config_file
.read_to_string(&mut config_data)
.map_err(|err| format!("Cannot read config file: {}", err))?;
let mut config = match serde_json::from_str::<Config>(config_data.as_str()) {
Ok(config) => config,
Err(_) => Config {
accounts: HashMap::new(),
},
};
config
.accounts
.insert(account_name.to_owned(), account.clone());
config_data = serde_json::to_string(&config).unwrap();
config_file
.write_all_at(config_data.as_bytes(), 0)
.map_err(|err| format!("Cannot write config to file: {}", err))?;
Ok(())
}
fn refresh_token(account: &mut Account) -> Result<(), String> {
let token = match account.service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => {
onedrive::get_token(account.token.refresh_token.as_str(), "refresh_token")
}
}?;
account.token = token;
Ok(())
}
// Recursively walk through
fn read_dir_rec(folder: &str, files: &mut HashMap<String, u64>) -> std::io::Result<()> {
let dir_entries = std::fs::read_dir(folder)?;
for entry in dir_entries.flatten() {
let metadata = entry.metadata()?;
let file_path = entry.path().to_str().unwrap().to_string();
if metadata.is_dir() {
read_dir_rec(&file_path, files)?;
} else {
let last_modified = metadata
.modified()?
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
files.insert(file_path, last_modified);
}
}
Ok(())
}
fn timestamp() -> u64 {
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap().as_secs()
}
fn sync_files(
account: &mut Account,
account_name: &str,
folder_to_sync: &String,
sync_flags: &SyncFlags,
) -> Result<(), String> {
println!("Syncing {} to {}", folder_to_sync, account_name);
let now = timestamp();
if now > account.token.valid_till {
println!("INFO: Token refreshed");
refresh_token(account)?;
}
if sync_flags.fresh {
account.last_synced = 0;
account.attributes = HashMap::new();
}
// Getting local changes
let mut local_files = HashMap::new();
read_dir_rec(folder_to_sync, &mut local_files)
.map_err(|err| format!("Cannot walk folder to sync: {}", err))?;
// Deleting local files incase of
// fresh sync
if sync_flags.fresh {
println!("INFO: Cleaning up local files {}", local_files.len());
for file_path in local_files.keys() {
std::fs::remove_file(file_path)
.map_err(|err| format!("Cannot remove file: {}", err))?;
}
local_files = HashMap::new();
}
// Creating a scope so file is closed
// Before we update the last sync
{
println!("INFO: Reading cloudstate");
let cloudstate_file_path = format!("{}/.cloudstate", folder_to_sync);
let mut cloudstate_file = std::fs::File::options()
.read(true)
.write(true)
.create(true)
.open(cloudstate_file_path)
.map_err(|err| err.to_string())?;
let mut cloudstate = if !sync_flags.fresh {
match serde_json::from_reader(&cloudstate_file) {
Ok(state) => state,
Err(_) => CloudState {
entries: HashMap::new(),
},
}
} else {
CloudState {
entries: HashMap::new(),
}
};
// Getting cloud changes
let deltas = match account.service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => onedrive::get_drive_delta(account)?,
};
println!("INFO: Cloud Delta {}", deltas.len());
println!("INFO: Cloud files {}", cloudstate.entries.len());
println!("INFO: Local files {}", local_files.len());
for delta in &deltas {
// Skip the cloud sync cloud we have
// already have this file from the last sync
if account.last_synced >= delta.last_modified {
continue;
}
let (folder, _) = delta.file_path.rsplit_once('/').unwrap();
let file_path = delta.file_path.clone();
let full_file_path = format!("{}{}", folder_to_sync, file_path);
let local_modified = local_files.get(&full_file_path).map_or(0, |val| *val);
// Making sure cloud files get priotity on
// fresh fetch
let cloud_modified = if sync_flags.fresh {
timestamp()
} else {
delta.last_modified
};
match delta.delta_type {
DriveDeltaType::Deleted => {
if cloud_modified > local_modified {
println!("INFO: Deleting local file {}", full_file_path);
match std::fs::remove_file(&full_file_path) {
Ok(_) => {
local_files.remove(&full_file_path);
}
Err(err) => {
println!("ERROR: Cannot remove file: {}", err)
}
};
cloudstate.entries.remove(&file_path);
}
}
DriveDeltaType::CreatedOrModifiled => {
if cloud_modified > local_modified {
println!("INFO: Downloading {}", file_path);
let full_folder_path = format!("{}/{}", folder_to_sync, folder);
std::fs::create_dir_all(&full_folder_path)
.map_err(|err| err.to_string())?;
let response = match account.service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => onedrive::download_file(account, &file_path),
};
match response {
Ok(contents) => {
std::fs::write(&full_file_path, contents)
.map_err(|err| err.to_string())?;
let ts = timestamp();
cloudstate.entries.insert(
file_path,
CloudStateEntry {
cloud_id: delta.cloud_id.to_string(),
last_modified: ts,
},
);
local_files.insert(full_file_path, ts);
}
Err(err) => {
println!("ERROR: Downloading file {}", err);
}
};
} else {
cloudstate.entries.remove(&file_path);
}
}
}
}
// Uploading locally modified files
for (file_path, local_modified) in &local_files {
let local_modified = *local_modified;
let drive_relative_path = file_path.split(folder_to_sync).last().unwrap();
let result = cloudstate.entries.get(drive_relative_path);
let is_file_modified = result.is_some()
&& local_modified > account.last_synced
&& local_modified > result.unwrap().last_modified;
if is_file_modified || result.is_none() {
match std::fs::read(file_path) {
Ok(file_contents) => {
println!("INFO: Uploading {}", file_path);
let response = match account.service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => onedrive::upload_new_file(
account,
drive_relative_path,
&file_contents,
),
};
match response {
Ok(cloud_id) => {
let ts = timestamp();
cloudstate.entries.insert(
drive_relative_path.to_string(),
CloudStateEntry {
cloud_id,
last_modified: ts,
},
);
}
Err(err) => {
println!("ERROR: Uploading file: {}", err);
}
};
}
Err(err) => {
println!("ERROR: Reading file {}: {}", file_path, err);
}
}
}
}
// Removing cloud files
let mut cloudfiles_to_deleted = Vec::new();
{
for file_path in cloudstate.entries.keys() {
let entry = &cloudstate.entries.get(file_path).unwrap();
let full_file_path = format!("{}{}", folder_to_sync, file_path);
if local_files.get(&full_file_path).is_none() {
println!("INFO: Cloud deleting file {}", file_path);
let response = match account.service {
SyncService::GDrive => todo!(),
SyncService::Onedrive => onedrive::delete_file(account, &entry.cloud_id),
};
match response {
Ok(_) => {}
Err(err) => {
println!("ERROR: Cloud deleting file: {}", err);
}
};
cloudfiles_to_deleted.push(file_path.clone());
}
}
}
for file_path in cloudfiles_to_deleted {
cloudstate.entries.remove(&file_path);
}
// Truncating the file
cloudstate_file
.set_len(0)
.map_err(|err| format!("Cannot write to file: {}", err))?;
cloudstate_file.seek(std::io::SeekFrom::Start(0)).unwrap();
serde_json::to_writer(cloudstate_file, &cloudstate).map_err(|err| err.to_string())?;
}
// Save changes to account
account.last_synced = timestamp();
save_account(account_name, account)?;
Ok(())
}
// Assuming date 2023-08-06T13:23:00.093Z (ISO format)
// @Returns unix timestamp
fn parse_iso_date(date_time_str: &str) -> u64 {
let (date_str, time_str) = date_time_str.split_once('T').unwrap();
let date_tokens: Vec<&str> = date_str.split('-').collect();
let year: u64 = date_tokens[0].parse().unwrap();
let month: u64 = date_tokens[1].parse().unwrap();
let date: u64 = date_tokens[2].parse().unwrap();
let time_tokens: Vec<&str> = time_str.split(':').collect();
let hours: u64 = time_tokens[0].parse().unwrap();
let minutes: u64 = time_tokens[1].parse().unwrap();
let seconds_str = &time_tokens[2][0..2];
let seconds: u64 = seconds_str.parse().unwrap();
fn days_per_year(year: u64) -> u64 {
if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {
366
} else {
365
}
}
fn days_per_month(month: u64, year: u64) -> u64 {
match month {
1 => 31,
2 => {
if days_per_year(year) == 365 {
28
} else {
29
}
}
3 => 31,
4 => 30,
5 => 31,
6 => 30,
7 => 31,
8 => 31,
9 => 30,
10 => 31,
11 => 30,
12 => 31,
_ => unreachable!(),
}
}
let mut days_since_epoch = 0;
for y in 1970..year {
days_since_epoch += days_per_year(y);
}
let mut days_in_year_so_far = 0;
for m in 1..month {
days_in_year_so_far += days_per_month(m, year);
}
days_since_epoch += days_in_year_so_far + (date - 1);
let seconds_in_hour = 60 * 60;
(days_since_epoch * 24 * seconds_in_hour) + hours * seconds_in_hour + minutes * 60 + seconds
}
#[cfg(test)]
mod tests {
use crate::parse_iso_date;
#[test]
fn test_date_parsing() {
assert_eq!(parse_iso_date("2023-08-06T13:23:00Z"), 1691328180);
}
}