abraunegg-onedrive/src/main.d

308 lines
9.8 KiB
D
Raw Normal View History

import core.stdc.stdlib: EXIT_SUCCESS, EXIT_FAILURE;
2015-09-20 21:21:51 +02:00
import core.memory, core.time, core.thread;
2017-07-14 11:31:16 +02:00
import std.getopt, std.file, std.path, std.process, std.stdio;
import config, itemdb, monitor, onedrive, selective, sync, util;
static import log;
2015-09-01 20:45:34 +02:00
2017-12-31 17:07:21 +01:00
// only download remote changes
bool downloadOnly;
int main(string[] args)
2015-09-01 20:45:34 +02:00
{
// configuration directory
string configDirName = environment.get("XDG_CONFIG_HOME", "~/.config") ~ "/onedrive";
2017-08-01 19:11:50 +02:00
// override the sync directory
string syncDirName;
// enable monitor mode
bool monitor;
// force a full resync
bool resync;
2016-08-05 00:12:58 +02:00
// remove the current user and sync state
bool logout;
// enable verbose logging
bool verbose;
2017-05-28 20:14:50 +02:00
// print the access token
bool printAccessToken;
2017-07-14 11:31:16 +02:00
// print the version and exit
bool printVersion;
// Additional options added to support MyNAS Storage Appliance
// debug the HTTP(S) operations if required
bool debugHttp;
// This allows for selective directory syncing instead of everything under ~/OneDrive/
string singleDirectory;
// Create a single root directory on OneDrive
string createDirectory;
// Remove a single directory on OneDrive
string removeDirectory;
// The source directory if we are using the OneDrive client to rename a directory
string sourceDirectory;
// The destination directory if we are using the OneDrive client to rename a directory
string destinationDirectory;
// Configure a flag to perform a sync
// This is beneficial so that if just running the client itself - without any options, or sync check, the client does not perform a sync
bool synchronize;
// Local sync - Upload local changes first before downloading changes from OneDrive
bool localFirst;
2015-09-14 19:21:06 +02:00
try {
auto opt = getopt(
args,
std.getopt.config.bundling,
2017-07-14 11:31:16 +02:00
std.getopt.config.caseSensitive,
"confdir", "Set the directory used to store the configuration files", &configDirName,
"create-directory", "Create a directory on OneDrive - no sync will be performed.", &createDirectory,
"destination-directory", "Destination directory for renamed or move on OneDrive - no sync will be performed.", &destinationDirectory,
"debug-http", "Debug OneDrive HTTP communication.", &debugHttp,
2017-12-31 17:07:21 +01:00
"download|d", "Only download remote changes", &downloadOnly,
"local-first", "Synchronize from the local directory source first, before downloading changes from OneDrive.", &localFirst,
2017-07-14 11:31:16 +02:00
"logout", "Logout the current user", &logout,
"monitor|m", "Keep monitoring for local and remote changes", &monitor,
"print-token", "Print the access token, useful for debugging", &printAccessToken,
"resync", "Forget the last saved state, perform a full sync", &resync,
"remove-directory", "Remove a directory on OneDrive - no sync will be performed.", &removeDirectory,
"single-directory", "Specify a single local directory within the OneDrive root to sync.", &singleDirectory,
"source-directory", "Source directory to rename or move on OneDrive - no sync will be performed.", &sourceDirectory,
2018-01-19 17:56:36 +01:00
"syncdir", "Set the directory used to sync the files that are synced", &syncDirName,
"synchronize", "Perform a synchronization", &synchronize,
2017-07-14 11:31:16 +02:00
"verbose|v", "Print more details, useful for debugging", &log.verbose,
"version", "Print the version and exit", &printVersion
2015-09-14 19:21:06 +02:00
);
if (opt.helpWanted) {
2015-09-22 11:20:54 +02:00
defaultGetoptPrinter(
"Usage: onedrive [OPTION]...\n\n" ~
2017-07-14 11:31:16 +02:00
"no option Sync and exit",
2015-09-22 11:20:54 +02:00
opt.options
);
return EXIT_SUCCESS;
2015-09-14 19:21:06 +02:00
}
} catch (GetOptException e) {
2017-12-28 15:21:41 +01:00
log.error(e.msg);
log.error("Try 'onedrive -h' for more information");
return EXIT_FAILURE;
2015-09-14 19:21:06 +02:00
}
2018-02-18 18:24:46 +01:00
// disable buffering on stdout
stdout.setvbuf(0, _IONBF);
2015-09-14 19:21:06 +02:00
2017-07-14 11:31:16 +02:00
if (printVersion) {
2017-08-01 19:11:50 +02:00
std.stdio.write("onedrive ", import("version"));
2017-07-14 11:31:16 +02:00
return EXIT_SUCCESS;
}
// Configure Logging
string logFilePath = "/var/log/onedrive/";
if (!exists(logFilePath)) mkdirRecurse(logFilePath);
log.vlog("Loading config ...");
configDirName = configDirName.expandTilde().absolutePath();
2017-08-01 19:11:50 +02:00
if (!exists(configDirName)) mkdirRecurse(configDirName);
auto cfg = new config.Config(configDirName);
cfg.init();
2017-08-01 19:11:50 +02:00
// command line parameters override the config
if (syncDirName) cfg.setValue("sync_dir", syncDirName);
2016-12-25 19:23:33 +01:00
// upgrades
if (exists(configDirName ~ "/items.db")) {
remove(configDirName ~ "/items.db");
log.log("Database schema changed, resync needed");
resync = true;
}
2016-08-05 00:12:58 +02:00
if (resync || logout) {
2017-05-28 23:14:37 +02:00
log.vlog("Deleting the saved status ...");
2016-08-05 00:12:58 +02:00
safeRemove(cfg.databaseFilePath);
safeRemove(cfg.deltaLinkFilePath);
2016-08-05 00:12:58 +02:00
safeRemove(cfg.uploadStateFilePath);
if (logout) {
safeRemove(cfg.refreshTokenFilePath);
}
2015-09-14 19:21:06 +02:00
}
log.vlog("Initializing the OneDrive API ...");
2015-11-29 21:12:44 +01:00
bool online = testNetwork();
if (!online && !monitor) {
2017-12-28 15:21:41 +01:00
log.error("No network connection");
return EXIT_FAILURE;
2015-11-29 21:12:44 +01:00
}
auto onedrive = new OneDriveApi(cfg, debugHttp);
2017-05-28 20:14:50 +02:00
onedrive.printAccessToken = printAccessToken;
if (!onedrive.init()) {
2017-12-28 15:21:41 +01:00
log.error("Could not initialize the OneDrive API");
// workaround for segfault in std.net.curl.Curl.shutdown() on exit
onedrive.http.shutdown();
return EXIT_FAILURE;
2015-09-01 20:45:34 +02:00
}
// initialize system
log.vlog("Opening the item database ...");
auto itemdb = new ItemDatabase(cfg.databaseFilePath);
// Set the local path root
string syncDir = expandTilde(cfg.getValue("sync_dir"));
log.vlog("All operations will be performed in: ", syncDir);
2017-08-01 19:11:50 +02:00
if (!exists(syncDir)) mkdirRecurse(syncDir);
chdir(syncDir);
// Initialise the sync engine
log.vlog("Initializing the Synchronization Engine ...");
auto selectiveSync = new SelectiveSync();
selectiveSync.load(cfg.syncListFilePath);
selectiveSync.setMask(cfg.getValue("skip_file"));
auto sync = new SyncEngine(cfg, onedrive, itemdb, selectiveSync);
sync.init();
// Do we need to create or remove a directory?
if ((createDirectory != "") || (removeDirectory != "")) {
if (createDirectory != "") {
// create a directory on OneDrive
sync.createDirectoryNoSync(createDirectory);
}
if (removeDirectory != "") {
// remove a directory on OneDrive
sync.deleteDirectoryNoSync(removeDirectory);
}
}
// Are we renaming or moving a directory?
if ((sourceDirectory != "") && (destinationDirectory != "")) {
// We are renaming or moving a directory
sync.renameDirectoryNoSync(sourceDirectory, destinationDirectory);
}
// Are we performing a sync, resync or monitor operation?
if ((synchronize) || (resync) || (monitor)) {
2015-09-01 20:45:34 +02:00
if ((synchronize) || (resync)) {
if (online) {
// Check user entry for local path - the above chdir means we are already in ~/OneDrive/ thus singleDirectory is local to this path
if (singleDirectory != ""){
// Does the directory we want to sync actually exist?
if (!exists(singleDirectory)){
// the requested directory does not exist ..
log.log("The requested local directory does not exist. Please check ~/OneDrive/ for requested path");
onedrive.http.shutdown();
return EXIT_FAILURE;
}
}
// Perform the sync
performSync(sync, singleDirectory, localFirst);
2015-09-20 21:21:51 +02:00
}
}
if (monitor) {
log.vlog("Initializing monitor ...");
Monitor m = new Monitor(selectiveSync);
m.onDirCreated = delegate(string path) {
log.vlog("[M] Directory created: ", path);
try {
sync.scanForDifferences(path);
} catch(Exception e) {
log.log(e.msg);
}
};
m.onFileChanged = delegate(string path) {
log.vlog("[M] File changed: ", path);
try {
sync.scanForDifferences(path);
} catch(Exception e) {
log.log(e.msg);
}
};
m.onDelete = delegate(string path) {
log.vlog("[M] Item deleted: ", path);
try {
sync.deleteByPath(path);
} catch(Exception e) {
log.log(e.msg);
}
};
m.onMove = delegate(string from, string to) {
log.vlog("[M] Item moved: ", from, " -> ", to);
try {
sync.uploadMoveItem(from, to);
} catch(Exception e) {
log.log(e.msg);
}
};
if (!downloadOnly) m.init(cfg, verbose);
// monitor loop
immutable auto checkInterval = dur!"seconds"(45);
auto lastCheckTime = MonoTime.currTime();
while (true) {
if (!downloadOnly) m.update(online);
auto currTime = MonoTime.currTime();
if (currTime - lastCheckTime > checkInterval) {
lastCheckTime = currTime;
online = testNetwork();
if (online) {
performSync(sync, singleDirectory, localFirst);
if (!downloadOnly) {
// discard all events that may have been generated by the sync
m.update(false);
}
2017-12-31 17:07:21 +01:00
}
GC.collect();
} else {
Thread.sleep(dur!"msecs"(100));
2015-11-29 21:12:44 +01:00
}
2015-09-17 00:16:23 +02:00
}
}
2015-09-14 19:21:06 +02:00
}
// workaround for segfault in std.net.curl.Curl.shutdown() on exit
onedrive.http.shutdown();
return EXIT_SUCCESS;
2015-09-01 20:45:34 +02:00
}
2015-09-20 21:21:51 +02:00
// try to synchronize the folder three times
void performSync(SyncEngine sync, string singleDirectory, bool localFirst)
2015-09-20 21:21:51 +02:00
{
int count;
string remotePath = "/";
string localPath = ".";
// Are we doing a single directory sync?
if (singleDirectory != ""){
// Need two different path strings here
remotePath = singleDirectory;
localPath = singleDirectory;
}
2015-09-20 21:21:51 +02:00
do {
try {
if (singleDirectory != ""){
// we were requested to sync a single directory
log.vlog("Syncing changes from this selected path: ", singleDirectory);
if (localFirst) {
log.vlog("Syncing changes from selected local path first before downloading changes from OneDrive ...");
sync.scanForDifferences(localPath);
sync.applyDifferencesSingleDirectory(remotePath);
} else {
log.vlog("Syncing changes from selected OneDrive path first before uploading local changes ...");
sync.applyDifferencesSingleDirectory(remotePath);
sync.scanForDifferences(localPath);
}
} else {
// original onedrive client logic below
2017-12-31 17:07:21 +01:00
sync.applyDifferences();
if (!downloadOnly) {
sync.scanForDifferences(localPath);
// ensure that the current state is updated
sync.applyDifferences();
}
2017-12-31 17:07:21 +01:00
}
2015-09-20 21:21:51 +02:00
count = -1;
2017-12-28 15:03:15 +01:00
} catch (Exception e) {
2015-09-20 21:21:51 +02:00
if (++count == 3) throw e;
else log.log(e.msg);
2015-09-20 21:21:51 +02:00
}
} while (count != -1);
}