示例#1
0
        public static async Task <bool> SplitHtmlAsync(FormFileModel file, List <ContentFile> files, uint cid)
        {
            if (files == null)
            {
                return(false);
            }
            var xmlDoc = new HtmlDocument();

            Stream[] scriptStreams = null;
            try
            {
                using (var s = file.File.OpenReadStream())
                {
                    xmlDoc.Load(s);
                }
                var nodes = xmlDoc.DocumentNode.SelectNodes("script");
                if (nodes != null)
                {
                    scriptStreams = new Stream[nodes.Count];
                    string   jsPath = Path.Combine(ContentParseSettings.JsSavePath);
                    string   name   = null;
                    string   path   = null;
                    HtmlNode node;
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        node = nodes[i];
                        name = Guid.NewGuid().ToString() + "." + ContentParseSettings.JsUseType;
                        path = ContentParseSettings.FileFormat(jsPath, name);
                        using (var stream = File.Create(path))
                        {
                            using (var swriter = new StreamWriter(stream))
                            {
                                await swriter.WriteAsync(node.InnerText);
                            }
                        }
                        xmlDoc.DocumentNode.RemoveChild(node);
                        files.Add(new ContentFile(jsPath, name, name, "js", GetUseType("js"))
                        {
                            ContentId = cid,
                            //将js,css文件可下载选项关闭
                            CanDownload = false
                        });
                    }
                    var htmlPath = Path.Combine(ContentParseSettings.HtmlSavePath);
                    name = Guid.NewGuid().ToString() + "." + ContentParseSettings.HtmlUseType;
                    path = ContentParseSettings.FileFormat(htmlPath, name);
                    using (var htmlStream = File.Create(path))
                    {
                        xmlDoc.Save(htmlStream);
                    }
                    files.Add(new ContentFile(htmlPath, name, file.OriginalName, file.ExtensionName, GetUseType(file.ExtensionName))
                    {
                        ContentId   = cid,
                        CanDownload = false
                    });
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        /// <summary>
        /// 提交内容
        /// </summary>
        /// <param name="id">发布者id</param>
        /// <param name="content">内容</param>
        /// <param name="title">标题</param>
        /// <param name="lable">标签_隔开</param>
        /// <param name="files">文件组</param>
        /// <returns>如果返回null就是成功,不成功返回错误信息</returns>
        private async Task <string> MakeContentAsync(string id, string content, string title, string lable, int gid = -1, IEnumerable <FormFileModel> files = null, bool autoJs = true)
        {
            ContentGroup group;

            if (gid != -1)//TODO:没测试
            {
                group = DbContext.Groups.Single(g => g.Id == gid);
            }
            else
            {
                group = DbContext.Groups.First();//暂时是一个默认组
            }
            Debug.Assert(group != null);
            content = content ?? string.Empty;
            //制作html文件
            var c = new Content("default", title, 0, lable, null, null)
            {
                ContentGroupId = group.Id,
                Id             = (uint)(await this.Count()) + 1,//(uint)DbContext.Contents.Count() + 1
                EaUserId       = id,
                Description    = content.Count() > ContentParseSettings.DescriptLength ? content.Substring(0, (int)ContentParseSettings.DescriptLength - 1) : content,
                ContentFiles   = new List <ContentFile>()
            };

            if (files == null && content == null && content.Count() < 10)
            {
                return("没有发送的内容,只是一个文件或者10个字符");
            }
            var xmlDocBuilder = _xmlDataService.CreateXmlDoc()
                                .AndXmlDoc(builder =>
            {
                var nodeContent = builder.XmlDoc.CreateElement(ContentParseSettings.RootNode);
                nodeContent.SetAttribute("class", "user-content row");
                nodeContent.InnerText = content ?? string.Empty;
                builder.RootElement.AppendChild(nodeContent);            //加入节点
                return(builder);
            });

            if (files != null)
            {
                var copyData = files.ToList();
                if (copyData.Count() >= ContentParseSettings.MaxUploadFileCount)
                {
                    return($"最多只能上传{ContentParseSettings.MaxUploadFileCount}个文件");
                }
                //过滤一次文件,将可解析的文件解析,不可解析的文件转存
                //文件解析暂时可以为 .jpg .png .jpeg .js .css
                //储存makefile
                await xmlDocBuilder.AndXmlDocAsync(async (builder) =>
                {
                    var nodeParsed = builder.XmlDoc.CreateElement("user-parsed");
                    //加入可解析文件
                    var parsedResual = await FileParseHelper.ParseAsync(builder.XmlDoc, nodeParsed, copyData);
                    //copyData=copyData.Except(parsedResual).ToList();//将已经完成解析的移除|不移除了,以后会有用
                    builder.RootElement.AppendChild(nodeParsed);
                    return(builder);
                });

                //上面的写好
                //保存其它文件(如果有)--TODO ContentFile参数怎么填是个问题
                //usertype从字典查,如果差不多就用后缀名代替
                string name, path;
                //要特别对待html文件,建议html文件
                var htmlFiles = copyData.Where(f => f.ExtensionName == ContentParseSettings.HtmlUseType);

                /*
                 * if (htmlFiles.Any(file=>FileParseHelper.HasDangrageCore(file.File)))//FIXME:这里验证不了,出现加载异常
                 * {
                 *  return "上传的html文件存在object,iframe,script危险标签,不能上传此文件";
                 * }
                 */
                if (autoJs)
                {
                    FormFileModel ffm;
                    for (int i = 0; i < htmlFiles.Count(); i++)
                    {
                        ffm = htmlFiles.ElementAt(i);
                        var res = await FileParseHelper.SplitHtmlAsync(ffm, c.ContentFiles, c.Id);

                        if (!res)
                        {
                            return($"上传:{ffm.File.Name},时出现异常或文件不存在,上传通道-SplitHtmlAsync");
                        }
                    }
                }
                else if (htmlFiles.Count() != 0)
                {
                    if (htmlFiles.Any(file => FileParseHelper.HasDangrageCore(file.File)))
                    {
                        return("上传的html文件存在object,iframe,script危险标签,不能上传此文件");
                    }
                }
                try
                {
                    string orPath = Path.Combine(ContentParseSettings.OtherSavePath);
                    foreach (var item in copyData)
                    {
                        if (item.ExtensionName != ContentParseSettings.HtmlUseType) //html文件已处理
                        {
                            name = Guid.NewGuid().ToString() + "." + item.ExtensionName;
                            path = ContentParseSettings.FileFormat(orPath, name);
                            await CopyFileAsync(path, item.File);

                            c.ContentFiles.Add(new ContentFile(orPath, name, item.OriginalName, item.ExtensionName, FileParseHelper.GetUseType(item.ExtensionName))
                            {
                                ContentId = c.Id,
                                //将js,css文件可下载选项关闭
                                CanDownload = item.ExtensionName == ContentParseSettings.CssUseType || item.ExtensionName == ContentParseSettings.JsUseType ? false : item.CanDownload
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    return("上传文件时发生异常:" + ex.Message);
                }
            }
            if (!xmlDocBuilder.IsBuild)
            {
                await xmlDocBuilder.BuildAsync();
            }
            var xmlFileName = Guid.NewGuid().ToString() + "." + ContentParseSettings.HtmlUseType;
            var xmlFilePath = Path.Combine(ContentParseSettings.HtmlSavePath);

            using (var fs = File.Create(ContentParseSettings.FileFormat(xmlFilePath, xmlFileName)))
            {
                xmlDocBuilder.XmlDoc.Save(fs);
            }
            c.ContentFiles.Add(new ContentFile(xmlFilePath, xmlFileName, xmlFileName, ContentParseSettings.HtmlUseType, ContentParseSettings.HtmlUseType)
            {
                CanDownload = false, ContentId = c.Id
            });

            await this.AddAsync(c);

            return(null);
        }