Example #1
0
        public async Task <(bool success, string failureMessage)> LoginAsync(string account, string password)
        {
            var client = new RestClient(CloudUtils.Api.GetCliUrl(RestUrlLogin))
            {
                Timeout = -1
            };
            var request = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", TranslateUtils.JsonSerialize(new LoginRequest
            {
                Account      = account,
                Password     = AuthUtils.Md5ByString(password),
                IsPersistent = true
            }), ParameterType.RequestBody);
            var response = client.Execute <LoginResult>(request);

            if (!response.IsSuccessful)
            {
                return(false, "your account or password was incorrect");
            }

            var loginResult = response.Data;

            var status = new ConfigStatus
            {
                UserName    = loginResult.UserName,
                AccessToken = loginResult.AccessToken
            };

            await _configService.SaveStatusAsync(status);

            return(true, null);
        }
        public (bool success, string failureMessage) UnPluginsPublish(string pluginId)
        {
            var status = _configService.Status;

            if (status == null || string.IsNullOrEmpty(status.UserName) || string.IsNullOrEmpty(status.AccessToken))
            {
                return(false, "you have not logged in");
            }

            var client = new RestClient(CloudUtils.Api.GetCliUrl(RestUrlPluginUnPublish))
            {
                Timeout = -1
            };
            var request = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {status.AccessToken}");
            request.AddParameter("application/json", TranslateUtils.JsonSerialize(new UnPublishRequest
            {
                PluginId = pluginId
            }), ParameterType.RequestBody);
            var response = client.Execute(request);

            if (!response.IsSuccessful)
            {
                return(false, StringUtils.Trim(response.Content, '"'));
            }

            return(true, null);
        }
Example #3
0
        protected void Finish(object retval)
        {
            var response = HttpContext.Current.Response;

            response.ContentType = "application/json";
            response.Write(TranslateUtils.JsonSerialize(retval));
            response.End();
        }
Example #4
0
        public void Edit(TemplateInfo templateInfo)
        {
            var plugin        = _pluginManager.GetPlugin(PluginId);
            var directoryPath = PathUtils.Combine(plugin.ContentRootPath, "assets/form/templates");

            var configJson = TranslateUtils.JsonSerialize(templateInfo);
            var configPath = PathUtils.Combine(directoryPath, templateInfo.Name, "config.json");

            FileUtils.WriteText(configPath, configJson);
        }
Example #5
0
 public override string ToString()
 {
     return(TranslateUtils.JsonSerialize(new
     {
         DateTime,
         Detail,
         Exception?.Message,
         Exception?.StackTrace
     }));
 }
Example #6
0
        public static void SaveSettings(string contentRootPath, bool isProtectData, bool isSafeMode, bool isDisablePlugins, string securityKey, string databaseType, string databaseConnectionString, string redisConnectionString, string adminRestrictionHost, string[] adminRestrictionAllowList, string[] adminRestrictionBlockList)
        {
            var path = PathUtils.Combine(contentRootPath, Constants.ConfigFileName);

            if (adminRestrictionAllowList == null)
            {
                adminRestrictionAllowList = new string[] { };
            }
            if (adminRestrictionBlockList == null)
            {
                adminRestrictionBlockList = new string[] { };
            }

            var json = SettingsManager.RunningInContainer
                ? $@"
{{
  ""IsDisablePlugins"": {StringUtils.ToLower(isDisablePlugins.ToString())},
  ""AdminRestriction"": {{
    ""Host"": ""{adminRestrictionHost}"",
    ""AllowList"": {TranslateUtils.JsonSerialize(adminRestrictionAllowList)},
    ""BlockList"": {TranslateUtils.JsonSerialize(adminRestrictionBlockList)}
  }}
}}"
                : $@"
{{
  ""IsProtectData"": {StringUtils.ToLower(isProtectData.ToString())},
  ""IsSafeMode"": {StringUtils.ToLower(isSafeMode.ToString())},
  ""SecurityKey"": ""{securityKey}"",
  ""Database"": {{
    ""Type"": ""{databaseType}"",
    ""ConnectionString"": ""{StringUtils.ToJsonString(databaseConnectionString)}""
  }},
  ""Redis"": {{
    ""ConnectionString"": ""{redisConnectionString}""
  }},
  ""IsDisablePlugins"": {StringUtils.ToLower(isDisablePlugins.ToString())},
  ""AdminRestriction"": {{
    ""Host"": ""{adminRestrictionHost}"",
    ""AllowList"": {TranslateUtils.JsonSerialize(adminRestrictionAllowList)},
    ""BlockList"": {TranslateUtils.JsonSerialize(adminRestrictionBlockList)}
  }}
}}";



            FileUtils.WriteText(path, json.Trim());

            var webConfigPath = PathUtils.Combine(contentRootPath, "Web.config");

            if (FileUtils.IsFileExists(webConfigPath))
            {
                var webConfigContent = FileUtils.ReadText(webConfigPath);
                FileUtils.WriteText(webConfigPath, webConfigContent);
            }
        }
Example #7
0
        public async Task SaveStatusAsync(ConfigStatus status)
        {
            var configPath = CliUtils.GetOsUserConfigFilePath();

            var config = new Config
            {
                Status = status
            };

            await FileUtils.WriteTextAsync(configPath, TranslateUtils.JsonSerialize(config));
        }
Example #8
0
        public async Task SaveConfigAsync(string pluginId, Dictionary <string, object> config)
        {
            var plugin = GetPlugin(pluginId);

            if (plugin != null)
            {
                var configPath  = PathUtils.Combine(plugin.ContentRootPath, Constants.PluginConfigFileName);
                var configValue = TranslateUtils.JsonSerialize(config);
                await FileUtils.WriteTextAsync(configPath, configValue);
            }
        }
Example #9
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.");
        }
Example #10
0
        private void Sync(TableStyle style)
        {
            if (style?.Items != null)
            {
                style.ItemValues = TranslateUtils.JsonSerialize(style.Items);
            }

            if (style?.Rules != null)
            {
                style.RuleValues = TranslateUtils.JsonSerialize(style.Rules);
            }
        }
Example #11
0
        private static async Task <string> ParseDynamicAsync(IParseManager parseManager, string testType, string testValue, string testOperate, string loading, string yes, string no, string onBeforeSend, string onSuccess, string onComplete, string onError)
        {
            var pageInfo    = parseManager.PageInfo;
            var contextInfo = parseManager.ContextInfo;

            if (string.IsNullOrEmpty(yes) && string.IsNullOrEmpty(no))
            {
                return(string.Empty);
            }

            await pageInfo.AddPageHeadCodeIfNotExistsAsync(ParsePage.Const.StlClient);

            var elementId = StringUtils.GetElementId();

            //运行解析以便为页面生成所需JS引用
            if (!string.IsNullOrEmpty(yes))
            {
                await parseManager.ParseInnerContentAsync(new StringBuilder(yes));
            }
            if (!string.IsNullOrEmpty(no))
            {
                await parseManager.ParseInnerContentAsync(new StringBuilder(no));
            }

            var dynamicInfo = new DynamicInfo(parseManager.SettingsManager)
            {
                ElementName     = ElementName,
                SiteId          = pageInfo.SiteId,
                ChannelId       = contextInfo.ChannelId,
                ContentId       = contextInfo.ContentId,
                TemplateId      = pageInfo.Template.Id,
                ElementId       = elementId,
                LoadingTemplate = loading,
                SuccessTemplate = yes,
                FailureTemplate = no,
                OnBeforeSend    = onBeforeSend,
                OnSuccess       = onSuccess,
                OnComplete      = onComplete,
                OnError         = onError
            };
            var ifInfo = new DynamicInfo.IfInfo
            {
                Type  = testType,
                Op    = testOperate,
                Value = testValue
            };

            dynamicInfo.ElementValues = TranslateUtils.JsonSerialize(ifInfo);

            var dynamicUrl = parseManager.PathManager.GetIfApiUrl();

            return(dynamicInfo.GetScript(dynamicUrl, true));
        }
        public async Task <ActionResult <List <SubmitResult> > > Submit([FromBody] SubmitRequest request)
        {
            var siteIds = await _authManager.GetSiteIdsAsync();

            if (!ListUtils.Contains(siteIds, request.SiteId))
            {
                return(Unauthorized());
            }

            var site = await _siteRepository.GetAsync(request.SiteId);

            if (site == null)
            {
                return(this.Error("无法确定内容对应的站点"));
            }

            var result = new List <SubmitResult>();

            foreach (var filePath in request.FilePaths)
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    continue;
                }

                var fileName = PathUtils.GetFileName(filePath);

                var virtualUrl = await _pathManager.GetVirtualUrlByPhysicalPathAsync(site, filePath);

                var fileUrl = await _pathManager.ParseSiteUrlAsync(site, virtualUrl, true);


                result.Add(new SubmitResult
                {
                    FileUrl        = fileUrl,
                    FileVirtualUrl = virtualUrl
                });
            }

            var options = TranslateUtils.JsonDeserialize(site.Get <string>($"Home.{nameof(LayerFileUploadController)}"), new Options
            {
                IsChangeFileName = true
            });

            options.IsChangeFileName = request.IsChangeFileName;
            site.Set($"Home.{nameof(LayerFileUploadController)}", TranslateUtils.JsonSerialize(options));

            await _siteRepository.UpdateAsync(site);

            return(result);
        }
Example #13
0
        public StringResult New()
        {
            var captcha = new CaptchaUtils.Captcha
            {
                Value    = CaptchaUtils.GetCode(),
                ExpireAt = DateTime.Now.AddMinutes(10)
            };
            var json = TranslateUtils.JsonSerialize(captcha);

            return(new StringResult
            {
                Value = _settingsManager.Encrypt(json)
            });
        }
Example #14
0
        protected KeyValuePair <string, TableInfo> GetNewTableInfo(string oldTableName, TableInfo oldTableInfo, string newTableName, List <TableColumn> newColumns, Dictionary <string, string> convertKeyDict, Dictionary <string, string> convertValueDict)
        {
            if (string.IsNullOrEmpty(newTableName))
            {
                newTableName = oldTableName;
            }
            if (newColumns == null || newColumns.Count == 0)
            {
                newColumns = oldTableInfo.Columns;
            }

            var newTableInfo = new TableInfo
            {
                Columns    = newColumns,
                TotalCount = oldTableInfo.TotalCount,
                RowFiles   = oldTableInfo.RowFiles
            };

            CliUtils.PrintRow(oldTableName, newTableName, oldTableInfo.TotalCount.ToString("#,0"));

            var i = 0;

            using (var progress = new ProgressBar())
            {
                foreach (var fileName in oldTableInfo.RowFiles)
                {
                    progress.Report((double)i++ / oldTableInfo.RowFiles.Count);

                    var oldFilePath = OldTreeInfo.GetTableContentFilePath(oldTableName, fileName);
                    var newFilePath = NewTreeInfo.GetTableContentFilePath(newTableName, fileName);

                    if (convertKeyDict != null)
                    {
                        var oldRows =
                            TranslateUtils.JsonDeserialize <List <JObject> >(FileUtils.ReadText(oldFilePath, Encoding.UTF8));

                        var newRows = UpdateUtils.UpdateRows(oldRows, convertKeyDict, convertValueDict);

                        FileUtils.WriteText(newFilePath, Encoding.UTF8, TranslateUtils.JsonSerialize(newRows));
                    }
                    else
                    {
                        FileUtils.CopyFile(oldFilePath, newFilePath);
                    }
                }
            }

            return(new KeyValuePair <string, TableInfo>(newTableName, newTableInfo));
        }
Example #15
0
        public static async Task UpdateSitesSplitTableNameAsync(IDatabaseManager databaseManager, TreeInfo newTreeInfo, Dictionary <int, TableInfo> splitSiteTableDict)
        {
            var siteMetadataFilePath = newTreeInfo.GetTableMetadataFilePath(databaseManager.SiteRepository.TableName);

            if (FileUtils.IsFileExists(siteMetadataFilePath))
            {
                var siteTableInfo = TranslateUtils.JsonDeserialize <TableInfo>(FileUtils.ReadText(siteMetadataFilePath, Encoding.UTF8));
                foreach (var fileName in siteTableInfo.RowFiles)
                {
                    var filePath = newTreeInfo.GetTableContentFilePath(databaseManager.SiteRepository.TableName, fileName);
                    var oldRows  = TranslateUtils.JsonDeserialize <List <JObject> >(FileUtils.ReadText(filePath, Encoding.UTF8));
                    var newRows  = new List <Dictionary <string, object> >();
                    foreach (var row in oldRows)
                    {
                        var dict = TranslateUtils.ToDictionaryIgnoreCase(row);
                        if (dict.ContainsKey(nameof(Site.Id)))
                        {
                            //var siteId = Convert.ToInt32(dict[nameof(Site.Id)]);
                            dict[nameof(Site.TableName)] = await databaseManager.ContentRepository.GetNewContentTableNameAsync();
                        }

                        newRows.Add(dict);
                    }

                    await FileUtils.WriteTextAsync(filePath, TranslateUtils.JsonSerialize(newRows));
                }
            }

            //foreach (var siteId in splitSiteTableDict.Keys)
            //{
            //    var siteTableInfo = splitSiteTableDict[siteId];
            //    var siteTableName = UpdateUtils.GetSplitContentTableName(siteId);

            //    siteTableInfo.Columns
            //}

            //var tableFilePath = newTreeInfo.GetTableMetadataFilePath(DataProvider.TableDao.TableName);
            //if (FileUtils.IsFileExists(tableFilePath))
            //{
            //    var siteTableInfo = TranslateUtils.JsonDeserialize<TableInfo>(FileUtils.ReadText(tableFilePath, Encoding.UTF8));
            //    var filePath = newTreeInfo.GetTableContentFilePath(DataProvider.SiteRepository.TableName, siteTableInfo.RowFiles[siteTableInfo.RowFiles.Count]);
            //    var tableInfoList = TranslateUtils.JsonDeserialize<List<CMS.Model.TableInfo>>(FileUtils.ReadText(filePath, Encoding.UTF8));



            //    await FileUtils.WriteTextAsync(filePath, Encoding.UTF8, TranslateUtils.JsonSerialize(tableInfoList));
            //}
        }
Example #16
0
        public IHttpActionResult Submit()
        {
            try
            {
                var request = Context.AuthenticatedRequest;
                var siteId  = request.GetQueryInt("siteId");

                if (!request.IsAdminLoggin ||
                    !request.AdminPermissions.HasSitePermissions(siteId, Utils.PluginId))
                {
                    return(Unauthorized());
                }

                var ruleInfo                = request.GetPostObject <GatherRuleInfo>("ruleInfo");
                var contentHtmlClearList    = request.GetPostObject <List <string> >("contentHtmlClearList");
                var contentHtmlClearTagList = request.GetPostObject <List <string> >("contentHtmlClearTagList");
                var contentAttributeList    = request.GetPostObject <List <string> >("contentAttributeList");
                var attributesDict          = request.GetPostObject <Dictionary <string, string> >("attributesDict");
                ruleInfo.ContentHtmlClearCollection    = TranslateUtils.ObjectCollectionToString(contentHtmlClearList);
                ruleInfo.ContentHtmlClearTagCollection = TranslateUtils.ObjectCollectionToString(contentHtmlClearTagList);
                ruleInfo.ContentAttributes             = TranslateUtils.ObjectCollectionToString(contentAttributeList);
                ruleInfo.ContentAttributesXml          = TranslateUtils.JsonSerialize(attributesDict);

                if (ruleInfo.Id > 0)
                {
                    Main.GatherRuleRepository.Update(ruleInfo);
                }
                else
                {
                    if (Main.GatherRuleRepository.IsExists(siteId, ruleInfo.GatherRuleName))
                    {
                        return(BadRequest("保存失败,已存在相同名称的采集规则!"));
                    }

                    ruleInfo.SiteId = siteId;
                    Main.GatherRuleRepository.Insert(ruleInfo);
                }

                return(Ok(new
                {
                    Value = true
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Example #17
0
        private static string ParseDynamic(PageInfo pageInfo, ContextInfo contextInfo, string testType, string testValue, string testOperate, string loading, string yes, string no, string onBeforeSend, string onSuccess, string onComplete, string onError)
        {
            if (string.IsNullOrEmpty(yes) && string.IsNullOrEmpty(no))
            {
                return(string.Empty);
            }

            pageInfo.AddPageBodyCodeIfNotExists(PageInfo.Const.StlClient);
            var ajaxDivId = StlParserUtility.GetAjaxDivId(pageInfo.UniqueId);

            //运行解析以便为页面生成所需JS引用
            if (!string.IsNullOrEmpty(yes))
            {
                StlParserManager.ParseInnerContent(new StringBuilder(yes), pageInfo, contextInfo);
            }
            if (!string.IsNullOrEmpty(no))
            {
                StlParserManager.ParseInnerContent(new StringBuilder(no), pageInfo, contextInfo);
            }

            var dynamicInfo = new DynamicInfo
            {
                ElementName     = ElementName,
                SiteId          = pageInfo.SiteId,
                ChannelId       = contextInfo.ChannelId,
                ContentId       = contextInfo.ContentId,
                TemplateId      = pageInfo.TemplateInfo.Id,
                AjaxDivId       = ajaxDivId,
                LoadingTemplate = loading,
                SuccessTemplate = yes,
                FailureTemplate = no,
                OnBeforeSend    = onBeforeSend,
                OnSuccess       = onSuccess,
                OnComplete      = onComplete,
                OnError         = onError
            };
            var ifInfo = new DynamicInfo.IfInfo
            {
                Type  = testType,
                Op    = testOperate,
                Value = testValue
            };

            dynamicInfo.ElementValues = TranslateUtils.JsonSerialize(ifInfo);

            return(dynamicInfo.GetScript(ApiRouteActionsIf.GetUrl(pageInfo.ApiUrl)));
        }
Example #18
0
        public void Clone(string nameToClone, TemplateInfo templateInfo, string templateHtml = null)
        {
            var plugin        = _pluginManager.GetPlugin(PluginId);
            var directoryPath = PathUtils.Combine(plugin.WebRootPath, "assets/form/templates");

            DirectoryUtils.Copy(PathUtils.Combine(directoryPath, nameToClone), PathUtils.Combine(directoryPath, templateInfo.Name), true);

            var configJson = TranslateUtils.JsonSerialize(templateInfo);
            var configPath = PathUtils.Combine(directoryPath, templateInfo.Name, "config.json");

            FileUtils.WriteText(configPath, configJson);

            if (templateHtml != null)
            {
                SetTemplateHtml(templateInfo, templateHtml);
            }
        }
Example #19
0
        public string ToString(List <string> excludeKeys)
        {
            if (excludeKeys == null || excludeKeys.Count == 0)
            {
                return(ToString());
            }

            var dict = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (var key in _dataDict.Keys)
            {
                if (!StringUtils.ContainsIgnoreCase(excludeKeys, key))
                {
                    dict[key] = _dataDict[key];
                }
            }
            return(TranslateUtils.JsonSerialize(dict));
        }
Example #20
0
        private static async Task <string> ParseDynamicAsync(IParseManager parseManager, string testType, string testValue, string testOperate, string loading, string yes, string no, string onBeforeSend, string onSuccess, string onComplete, string onError)
        {
            var pageInfo    = parseManager.PageInfo;
            var contextInfo = parseManager.ContextInfo;

            if (string.IsNullOrEmpty(yes) && string.IsNullOrEmpty(no))
            {
                return(string.Empty);
            }

            await pageInfo.AddPageHeadCodeIfNotExistsAsync(ParsePage.Const.StlClient);

            var elementId = StringUtils.GetElementId();

            var dynamicInfo = new Dynamic
            {
                SiteId          = pageInfo.SiteId,
                ChannelId       = contextInfo.ChannelId,
                ContentId       = contextInfo.ContentId,
                TemplateId      = pageInfo.Template.Id,
                ElementId       = elementId,
                LoadingTemplate = loading,
                YesTemplate     = yes,
                NoTemplate      = no,
                IsInline        = true,
                OnBeforeSend    = onBeforeSend,
                OnSuccess       = onSuccess,
                OnComplete      = onComplete,
                OnError         = onError
            };
            var ifInfo = new DynamicIfInfo
            {
                Type  = testType,
                Op    = testOperate,
                Value = testValue
            };

            dynamicInfo.Settings = TranslateUtils.JsonSerialize(ifInfo);

            var dynamicUrl = parseManager.PathManager.GetIfApiUrl(contextInfo.Site);

            return(await StlDynamic.GetScriptAsync(parseManager, dynamicUrl, dynamicInfo));
        }
Example #21
0
        public (bool success, string failureMessage) Register(string userName, string mobile, string email, string password)
        {
            var client = new RestClient(CloudUtils.Api.GetCliUrl(RestUrlRegister))
            {
                Timeout = -1
            };
            var request = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", TranslateUtils.JsonSerialize(new RegisterRequest
            {
                UserName = userName,
                Mobile   = mobile,
                Email    = email,
                Password = password
            }), ParameterType.RequestBody);
            var response = client.Execute(request);

            return(response.IsSuccessful ? (true, null) : (false, StringUtils.Trim(response.Content, '"')));
        }
Example #22
0
        /// <summary>
        /// 获取返回的json字符串
        /// </summary>
        /// <returns></returns>
        private static string GetResponseJson(string fileName, string filePath)
        {
            FileInfo file = null;

            if (!string.IsNullOrEmpty(filePath))
            {
                file = new FileInfo(filePath);
            }
            if (file != null)
            {
                return(TranslateUtils.JsonSerialize(new
                {
                    fileName,
                    length = file?.Length,
                    ret = 1
                }));
            }

            return(TranslateUtils.JsonSerialize(new
            {
                ret = 0
            }));
        }
Example #23
0
        public static void Execute(string[] args)
        {
            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            if (_isHelp)
            {
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Console.WriteLine($"SiteServer CLI Version: {version.Substring(0, version.Length - 2)}");
            Console.WriteLine($"Work Directory: {CliUtils.PhysicalApplicationPath}");
            Console.WriteLine();

            var content = FileUtils.ReadText(PathUtils.Combine(CliUtils.PhysicalApplicationPath, "_metadata.json"), Encoding.UTF8);
            var table   = TranslateUtils.JsonDeserialize <TableInfo>(content);

            Console.WriteLine($"_metadata: {TranslateUtils.JsonSerialize(table.Columns)}");
        }
Example #24
0
 public static string GetSearchApiParameters(ISettingsManager settingsManager, bool isAllSites, string siteName, string siteDir, string siteIds, string channelIndex, string channelName, string channelIds, string type, string word, string dateAttribute, string dateFrom, string dateTo, string since, int pageNum, bool isHighlight, int siteId, string ajaxDivId, string template)
 {
     return(TranslateUtils.JsonSerialize(new StlSearchRequest
     {
         IsAllSites = isAllSites,
         SiteName = siteName,
         SiteDir = siteDir,
         SiteIds = siteIds,
         ChannelIndex = channelIndex,
         ChannelName = channelName,
         ChannelIds = channelIds,
         Type = type,
         Word = word,
         DateAttribute = dateAttribute,
         DateFrom = dateFrom,
         DateTo = dateTo,
         Since = since,
         PageNum = pageNum,
         IsHighlight = isHighlight,
         SiteId = siteId,
         AjaxDivId = ajaxDivId,
         Template = settingsManager.Encrypt(template)
     }));
 }
Example #25
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);
            }
        }
Example #26
0
        internal static string ParseStlElement(string stlElement, PageInfo pageInfo, ContextInfo contextInfo)
        {
            string parsedContent = null;

            var stlElementInfo = StlParserUtility.ParseStlElement(stlElement);

            if (stlElementInfo != null)
            {
                var elementName = stlElementInfo.Name;

                if (ElementsToTranslateDic.ContainsKey(elementName))
                {
                    Func <string, string> func;
                    if (ElementsToTranslateDic.TryGetValue(elementName, out func))
                    {
                        parsedContent = func(stlElement);
                    }
                }
                else if (ElementsToParseDic.ContainsKey(elementName))
                {
                    if (stlElementInfo.IsDynamic)
                    {
                        parsedContent = StlDynamic.ParseDynamicElement(stlElement, pageInfo, contextInfo);
                    }
                    else
                    {
                        try
                        {
                            Func <PageInfo, ContextInfo, object> func;
                            if (ElementsToParseDic.TryGetValue(elementName, out func))
                            {
                                var contextInfoClone = contextInfo.Clone(stlElement, stlElementInfo.InnerHtml, stlElementInfo.Attributes);

                                var obj = func(pageInfo, contextInfoClone);

                                if (obj == null)
                                {
                                    parsedContent = string.Empty;
                                }
                                else if (obj is string)
                                {
                                    parsedContent = (string)obj;
                                }
                                else
                                {
                                    parsedContent = TranslateUtils.JsonSerialize(obj);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            parsedContent = StlParserUtility.GetStlErrorMessage(elementName, stlElement, ex);
                        }
                    }
                }
                else
                {
                    var parsers = PluginStlParserContentManager.GetParses();
                    if (parsers.ContainsKey(elementName))
                    {
                        if (stlElementInfo.IsDynamic)
                        {
                            parsedContent = StlDynamic.ParseDynamicElement(stlElement, pageInfo, contextInfo);
                        }
                        else
                        {
                            try
                            {
                                Func <PluginParseContext, string> func;
                                if (parsers.TryGetValue(elementName, out func))
                                {
                                    var context = new PluginParseContext(stlElementInfo.OuterHtml, stlElementInfo.InnerHtml, stlElementInfo.Attributes, pageInfo, contextInfo);
                                    parsedContent = func(context);
                                }
                            }
                            catch (Exception ex)
                            {
                                parsedContent = StlParserUtility.GetStlErrorMessage(elementName, stlElement, ex);
                            }
                        }
                    }
                }
            }

            return(parsedContent ?? stlElement);
        }
Example #27
0
 public override string ToString()
 {
     return(TranslateUtils.JsonSerialize(_dataDict));
 }
Example #28
0
File: Startup.cs Project: z-kf/cms
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISettingsManager settingsManager, IPluginManager pluginManager, IErrorLogRepository errorLogRepository, IOptions <SenparcSetting> senparcSetting)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionHandler(a => a.Run(async context =>
            {
                var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
                var exception = exceptionHandlerPathFeature.Error;

                string result;
                if (env.IsDevelopment())
                {
                    result = TranslateUtils.JsonSerialize(new
                    {
                        exception.Message,
                        exception.StackTrace,
                        AddDate = DateTime.Now
                    });
                }
                else
                {
                    result = TranslateUtils.JsonSerialize(new
                    {
                        exception.Message,
                        AddDate = DateTime.Now
                    });
                }
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(result);
            }));

            app.UseCors(CorsPolicy);

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            //app.UseHttpsRedirection();

            var options = new DefaultFilesOptions();

            options.DefaultFileNames.Clear();
            options.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(options);

            //if (settingsManager.Containerized)
            //{
            //    app.Map($"/{DirectoryUtils.SiteFiles.DirectoryName}/assets", assets =>
            //    {
            //        assets.UseStaticFiles(new StaticFileOptions
            //        {
            //            FileProvider = new PhysicalFileProvider(PathUtils.Combine(settingsManager.ContentRootPath, "assets"))
            //        });
            //    });
            //}

            app.UseStaticFiles();

            var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("zh-CN")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("zh-CN"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UsePluginsAsync(settingsManager, pluginManager, errorLogRepository).GetAwaiter().GetResult();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/healthz");

                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });
            //api.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}"); });

            app.UseRequestLocalization();

            RegisterService.Start(senparcSetting.Value)
            //自动扫描自定义扩展缓存(二选一)
            .UseSenparcGlobal(true)
            //指定自定义扩展缓存(二选一)
            //.UseSenparcGlobal(false, () => GetExCacheStrategies(senparcSetting.Value))
            ;

            app.UseOpenApi();
            app.UseSwaggerUi3();
            app.UseReDoc(settings =>
            {
                settings.Path         = "/api/docs";
                settings.DocumentPath = "/swagger/v1/swagger.json";
            });
        }
Example #29
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!");
        }
Example #30
0
        public static async Task Backup(ISettingsManager settingsManager, IDatabaseManager databaseManager, List <string> includes, List <string> excludes, int maxRows, TreeInfo treeInfo, string errorLogFilePath)
        {
            var allTableNames = await settingsManager.Database.GetTableNamesAsync();

            var tableNames = new List <string>();

            foreach (var tableName in allTableNames)
            {
                if (includes != null && !ListUtils.ContainsIgnoreCase(includes, tableName))
                {
                    continue;
                }
                if (ListUtils.ContainsIgnoreCase(excludes, tableName))
                {
                    continue;
                }
                if (ListUtils.ContainsIgnoreCase(tableNames, tableName))
                {
                    continue;
                }
                tableNames.Add(tableName);
            }

            await FileUtils.WriteTextAsync(treeInfo.TablesFilePath, TranslateUtils.JsonSerialize(tableNames));

            await WriteUtils.PrintRowLineAsync();

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

            await WriteUtils.PrintRowLineAsync();

            foreach (var tableName in tableNames)
            {
                try
                {
                    var columns = await settingsManager.Database.GetTableColumnsAsync(tableName);

                    var repository = new Repository(settingsManager.Database, tableName, columns);

                    var tableInfo = new TableInfo
                    {
                        Columns    = repository.TableColumns,
                        TotalCount = await repository.CountAsync(),
                        RowFiles   = new List <string>()
                    };

                    if (maxRows > 0 && tableInfo.TotalCount > maxRows)
                    {
                        tableInfo.TotalCount = maxRows;
                    }

                    await WriteUtils.PrintRowAsync(tableName, tableInfo.TotalCount.ToString("#,0"));

                    var identityColumnName =
                        await settingsManager.Database.AddIdentityColumnIdIfNotExistsAsync(tableName, tableInfo.Columns);

                    if (tableInfo.TotalCount > 0)
                    {
                        var current = 1;
                        if (tableInfo.TotalCount > CliConstants.PageSize)
                        {
                            var pageCount = (int)Math.Ceiling((double)tableInfo.TotalCount / CliConstants.PageSize);

                            using (var progress = new ProgressBar())
                            {
                                for (; current <= pageCount; current++)
                                {
                                    progress.Report((double)(current - 1) / pageCount);

                                    var fileName = $"{current}.json";
                                    tableInfo.RowFiles.Add(fileName);
                                    var offset = (current - 1) * CliConstants.PageSize;
                                    var limit  = tableInfo.TotalCount - offset < CliConstants.PageSize
                                        ? tableInfo.TotalCount - offset
                                        : CliConstants.PageSize;

                                    var rows = await databaseManager.GetPageObjectsAsync(tableName, identityColumnName, offset,
                                                                                         limit);

                                    await FileUtils.WriteTextAsync(
                                        treeInfo.GetTableContentFilePath(tableName, fileName),
                                        TranslateUtils.JsonSerialize(rows));
                                }
                            }
                        }
                        else
                        {
                            var fileName = $"{current}.json";
                            tableInfo.RowFiles.Add(fileName);
                            var rows = await databaseManager.GetObjectsAsync(tableName);

                            await FileUtils.WriteTextAsync(treeInfo.GetTableContentFilePath(tableName, fileName),
                                                           TranslateUtils.JsonSerialize(rows));
                        }
                    }

                    await FileUtils.WriteTextAsync(treeInfo.GetTableMetadataFilePath(tableName),
                                                   TranslateUtils.JsonSerialize(tableInfo));
                }
                catch (Exception ex)
                {
                    await CliUtils.AppendErrorLogAsync(errorLogFilePath, new TextLogInfo
                    {
                        Exception = ex,
                        DateTime  = DateTime.Now,
                        Detail    = tableName
                    });
                }
            }
        }