Пример #1
0
        static bool TestLogin()
        {
            if (glogin == null)
            {
                glogin      = new CGraphLogin(dh);
                graphClient = glogin.AutomaticGetGraphClient(false);
                if (graphClient == null)
                {
                    WriteEventLog("Authentication failed.", EventLogEntryType.Error);
                    Console.WriteLine("Cannot get access to graph API");
                    return(false);
                }
                StoreDH();
                return(true);
            }
            else
            {
                if (DateTime.Now > dh.Expires)
                {
                    glogin = null;
                    return(TestLogin());
                }
            }

            return(true);
        }
Пример #2
0
        static int Main(string[] args)
        {
            Console.WriteLine("OneDrive Copier - copies files to OneDrive");
            Console.WriteLine("");
            Console.WriteLine("Vulpes SARL, Luxembourg - https://vulpes.lu");
            Console.WriteLine("");

            dh.Tenant = Tenants.Consumers;
            dh.Scope  = new string[] { Scopes.FilesReadWriteAll, Scopes.OfflineAccess };
            dh.State  = Guid.NewGuid().ToString();
            bool   Auth           = false;
            string RemotePath     = "/";
            string NewDir         = "";
            string UploadLocalDir = "";
            bool   SkipFailed     = false;
            bool   RegEventLog    = false;
            int    Command        = 0;

            for (int i = 0; i < args.Length; i++)
            {
                string thiscmd = args[i].ToLower();
                string nextcmd = "";
                if (i + 1 < args.Length)
                {
                    if (args[i + 1].StartsWith("/") == false)
                    {
                        nextcmd = args[i + 1];
                    }
                }

                switch (thiscmd)
                {
                case "/auth":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing Client ID");
                        return(1);
                    }
                    dh.Client_ID = nextcmd;
                    Auth         = true;
                    i++;
                    break;

                case "/skipfailed":
                    SkipFailed = true;
                    break;

                case "/verbose":
                    FailedDetails = true;
                    break;

                case "/tennant":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing Tennant");
                        return(1);
                    }
                    dh.Tenant = nextcmd;
                    i++;
                    break;

                case "/rpath":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing Remote path");
                        return(1);
                    }
                    RemotePath = nextcmd;
                    if (RemotePath.StartsWith("/") == false)
                    {
                        RemotePath = "/" + RemotePath;
                    }
                    i++;
                    break;

                case "/newdir":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing new directory");
                        return(1);
                    }
                    NewDir = nextcmd;
                    if (NewDir.StartsWith("/") == true)
                    {
                        NewDir = NewDir.Substring(1);
                    }
                    i++;
                    break;

                case "/uploadpath":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing local path to upload");
                        return(1);
                    }
                    UploadLocalDir = nextcmd;
                    i++;
                    break;

                case "/eventlog":
                    UseWriteEventLog = true;
                    break;

                case "/registereventlog":
                    RegEventLog = true;
                    break;

                case "/command":
                    if (nextcmd == "")
                    {
                        Console.WriteLine("Missing commnand");
                        return(1);
                    }
                    switch (nextcmd.ToLower())
                    {
                    case "list":
                        Command = 0;
                        break;

                    case "mkdir":
                        Command = 1;
                        break;

                    case "uploaddir":
                        Command = 2;
                        break;

                    default:
                        Console.WriteLine("Unknown commnand");
                        return(1);
                    }
                    i++;
                    break;

                case "/?":
                default:
                    Console.WriteLine("Usage:");
                    Console.WriteLine(" /auth <client id>            Creates a new authentication");
                    Console.WriteLine(" /tennant <tennant>           Selects tennant");
                    Console.WriteLine("                                 consumers  <-- default");
                    Console.WriteLine("                                 common");
                    Console.WriteLine("                                 organizations");
                    Console.WriteLine("                                 GUID");
                    Console.WriteLine(" /command <command>           Performs some action on OneDrive");
                    Console.WriteLine("                                 List       <-- default");
                    Console.WriteLine("                                 MkDir");
                    Console.WriteLine("                                 UploadDir");
                    Console.WriteLine(" /rpath <path>                Set remote path");
                    Console.WriteLine(" /newdir <path>               New directory");
                    Console.WriteLine(" /uploadpath <path>           Local path to upload");
                    Console.WriteLine(" /skipfailed                  Skips failed copies, continues the process");
                    Console.WriteLine(" /eventlog                    Writes error messages and stats to Event Log");
                    Console.WriteLine(" /registereventlog            Register Event Log Source");
                    Console.WriteLine(" /verbose                     Verbose mode (will also log to Event Log if used with /eventlog)");
                    Console.WriteLine("");
                    Console.WriteLine("Register app link:");
                    Console.WriteLine("    https://go.microsoft.com/fwlink/?linkid=2083908");
                    Console.WriteLine("");
                    Console.WriteLine("Set Redirect URI to Public/native (mobile & desktop) and set the URI to");
                    Console.WriteLine("    https://login.microsoftonline.com/common/oauth2/nativeclient");
                    Console.WriteLine("");
                    return(1);
                }
            }

            if (RegEventLog == true)
            {
                Console.WriteLine("Register Eventlog ... ");
                RegisterEventLog();
                return(0);
            }

            if (UseWriteEventLog == true)
            {
                if (EventLog.SourceExists(EventLogTitle) == false)
                {
                    Console.WriteLine("Event Log " + EventLogTitle + " does not exist. Use /registereventlog");
                    return(5);
                }
            }

            if (Auth == true)
            {
                Console.WriteLine("Running Authentication ...");
                CGraphLogin aglogin = new CGraphLogin(dh);
                graphClient = aglogin.AutomaticGetGraphClient(true);
                if (graphClient == null)
                {
                    Console.WriteLine("Cannot get access to graph API");
                    return(5);
                }

                StoreDH();

                WriteEventLog("Authentication stored successfully.", EventLogEntryType.Information);

                Console.WriteLine("Data stored in registry");
                return(0);
            }

            dh.AccessToken  = Reg.ReadValue("AccessToken");
            dh.Client_ID    = Reg.ReadValue("Client_ID");
            dh.Code         = Reg.ReadValue("Code");
            dh.RefreshToken = Reg.ReadValue("RefreshToken");
            dh.State        = Reg.ReadValue("State");
            dh.Tenant       = Reg.ReadValue("Tenant");

            if (dh.AccessToken == "" || dh.Client_ID == "" || dh.Code == "" || dh.RefreshToken == "" || dh.State == "" || dh.Tenant == "")
            {
                WriteEventLog("Missing Authentication data.", EventLogEntryType.Warning);
                Console.WriteLine("No data in registry - rerun /auth parameter");
                return(5);
            }

            Console.Write("Authenticating ... ");

            if (TestLogin() == false)
            {
                return(5);
            }

            Console.WriteLine("OK");

            switch (Command)
            {
            case 0:     //list / dir
            {
                Drive     drv = QuerySync <Drive>(graphClient.Drive.Request().GetAsync());
                DriveItem root;
                if (string.IsNullOrWhiteSpace(RemotePath) == true || RemotePath == "/")
                {
                    root = QuerySync <DriveItem>(graphClient.Drive.Root.Request().Expand("children").GetAsync());
                }
                else
                {
                    root = QuerySync <DriveItem>(graphClient.Drive.Root.ItemWithPath(RemotePath).Request().Expand("children").GetAsync());
                }

                if (root == null)
                {
                    Console.WriteLine("Cannot get data");
                    return(5);
                }

                IDriveItemChildrenCollectionPage currentlist = root.Children;
                ListFiles(root.Children, drv.Quota);
                break;
            }

            case 1:     //new dir
            {
                if (string.IsNullOrWhiteSpace(NewDir) == true)
                {
                    Console.WriteLine("No directoy to be created specified");
                    return(5);
                }

                Drive     drv = QuerySync <Drive>(graphClient.Drive.Request().GetAsync());
                DriveItem newcreateddir;
                DriveItem newfolder = new DriveItem()
                {
                    Name = NewDir, Folder = new Folder()
                };
                if (string.IsNullOrWhiteSpace(RemotePath) == true || RemotePath == "/")
                {
                    newcreateddir = QuerySync <DriveItem>(graphClient.Drive.Root.Children.Request().AddAsync(newfolder));
                }
                else
                {
                    newcreateddir = QuerySync <DriveItem>(graphClient.Drive.Root.ItemWithPath(RemotePath).Children.Request().AddAsync(newfolder));
                }

                if (newcreateddir == null)
                {
                    WriteEventLog("Cannot create directory " + newfolder + " in " + RemotePath + ".", EventLogEntryType.Error);
                    Console.WriteLine("Cannot create directory");
                    return(5);
                }
                Console.WriteLine("Directory " + NewDir + " created");
                break;
            }

            case 2:     //upload dir
            {
                if (string.IsNullOrWhiteSpace(UploadLocalDir) == true)
                {
                    Console.WriteLine("No local directory to upload specified");
                    return(5);
                }

                StatCopyStarted = DateTime.Now;

                bool ProcessFailed = false;

                if (RecurseUploadData(UploadLocalDir, RemotePath, SkipFailed) == false)
                {
                    Console.WriteLine("Process failed!");
                    ProcessFailed = true;
                }

                StatCopyEnded = DateTime.Now;

                string StatResults = "";
                if (ProcessFailed == false)
                {
                    StatResults += "Process completed successfully.\n";
                }
                else
                {
                    StatResults += "Process failed.\n";
                }

                string allargs = "";
                foreach (string a in args)
                {
                    allargs += (a.Contains(" ") == true ? "\"" + a + "\"" : a) + " ";
                }

                StatResults += "Args:                   " + allargs.Trim() + "\n\n";
                StatResults += "Run time:               " + (StatCopyEnded - StatCopyStarted).ToString("hh\\:mm\\:ss").PadLeft(15) + "\n";
                StatResults += "Directory processed:    " + StatNumDirProcessed.ToString().PadLeft(15) + "\n";
                StatResults += "Elements deleted:       " + StatNumDeleted.ToString().PadLeft(15) + "\n\n";
                StatResults += "Successfully processed: " + StatCopyNumSuccess.ToString().PadLeft(15) + " " + NiceSize(StatCopySZSuccess).PadLeft(20) + "\n";
                StatResults += "Skipped:                " + StatCopyNumSkipped.ToString().PadLeft(15) + " " + NiceSize(StatCopySZSkipped).PadLeft(20) + "\n";
                StatResults += "Failed:                 " + StatCopyNumFailed.ToString().PadLeft(15) + " " + NiceSize(StatCopySZFailed).PadLeft(20) + "\n";

                Console.WriteLine(StatResults);
                WriteEventLog(StatResults, ProcessFailed == true ? EventLogEntryType.Error : EventLogEntryType.Information);

                break;
            }
            }

#if DEBUG
            Console.WriteLine("");
            Console.WriteLine("Press any key . . . ");
            Console.ReadKey(true);
#endif

            return(0);
        }