黄贺彬 vor 5 Jahren
Ursprung
Commit
5c935e9d8f

+ 371 - 0
HiTeachCE/Controllers/FileController.cs

@@ -0,0 +1,371 @@
+using DocumentFormat.OpenXml.Packaging;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
+using PdfSharpCore.Pdf;
+using PdfSharpCore.Pdf.IO;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Xml;
+using System.Xml.Linq;
+using TEAMModelOS.SDK.Context.Configuration;
+using TEAMModelOS.SDK.Context.Exception;
+using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
+using TEAMModelOS.SDK.Helper.Security.ShaHash;
+using TEAMModelOS.SDK.Module.AzureBlob.Container;
+
+namespace HiTeachCE.Controllers
+{
+    [Route("api/[controller]")]
+    [ApiController]
+    public class FileController
+    {
+        static XmlNamespaceManager xmlnsManager;
+
+        static FileController()
+        {
+
+            xmlnsManager = new XmlNamespaceManager(new NameTable());
+            xmlnsManager.AddNamespace("p", "http://schemas.openxmlformats.org/presentationml/2006/main");
+            xmlnsManager.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
+            xmlnsManager.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
+            xmlnsManager.AddNamespace("fo", "http://www.w3.org/1999/XSL/Format");
+            xmlnsManager.AddNamespace("app", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties");
+            xmlnsManager.AddNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
+            xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
+            xmlnsManager.AddNamespace("dcterms", "http://purl.org/dc/terms/");
+            xmlnsManager.AddNamespace("dcmitype", "http://purl.org/dc/dcmitype/");
+            xmlnsManager.AddNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
+            xmlnsManager.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
+            xmlnsManager.AddNamespace("cus", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
+            xmlnsManager.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
+            xmlnsManager.AddNamespace("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
+            xmlnsManager.AddNamespace("dsp", "http://schemas.microsoft.com/office/drawing/2008/diagram");
+            xmlnsManager.AddNamespace("dgm", "http://schemas.openxmlformats.org/drawingml/2006/diagram");
+            xmlnsManager.AddNamespace("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
+            xmlnsManager.AddNamespace("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
+            xmlnsManager.AddNamespace("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
+            xmlnsManager.AddNamespace("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
+            xmlnsManager.AddNamespace("pkg", "http://schemas.microsoft.com/office/2006/xmlPackage");
+            xmlnsManager.AddNamespace("p15", "http://schemas.microsoft.com/office/powerpoint/2012/main");
+            xmlnsManager.AddNamespace("a16", "http://schemas.microsoft.com/office/drawing/2014/main");
+            xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
+            xmlnsManager.AddNamespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
+            xmlnsManager.AddNamespace("c14", "http://schemas.microsoft.com/office/drawing/2007/8/2/chart");
+            xmlnsManager.AddNamespace("c16", "http://schemas.microsoft.com/office/drawing/2014/chart");
+            xmlnsManager.AddNamespace("cs", "http://schemas.microsoft.com/office/drawing/2012/chartStyle");
+            xmlnsManager.AddNamespace("thm15", "http://schemas.microsoft.com/office/thememl/2012/main");
+            xmlnsManager.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions");
+        }
+
+        /// <summary>
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("uploadFile")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<BaseJosnRPCResponse> UploadFile([FromForm] IFormFile file)
+        {
+            JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
+
+            // Dictionary<string, object> model = await fileService.UploadDocument(file);
+            string path = BaseConfigModel.ContentRootPath + "/Avatar/" + file.FileName;
+            using (var stream = new FileStream(path, FileMode.Create))
+            {
+                await file.CopyToAsync(stream);
+            }
+            return responseBuilder.Data(path).build();
+        }
+
+        /// <summary>
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("uploadDocument")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<BaseJosnRPCResponse> UploadDocument([FromForm] IFormFile file)
+        {
+            JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
+
+            // Dictionary<string, object> model = await fileService.UploadDocument(file);
+            string path = BaseConfigModel.ContentRootPath + "/Avatar/" + file.FileName;
+            using (var stream = new FileStream(path, FileMode.Create))
+            {
+                await file.CopyToAsync(stream);
+            }
+            return responseBuilder.Data(path).build();
+        }
+
+
+        /// <summary>
+        /// docUrl
+        /// folder
+        /// shaCode
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("UploadDocument")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<BaseJosnRPCResponse> UploadPPT([FromForm] IFormFile file)
+        {
+            //// pdf
+            string pathpdf = BaseConfigModel.ContentRootPath + "/Avatar/" + file.FileName;
+            using (var stream = new FileStream(pathpdf, FileMode.Create))
+            {
+                await file.CopyToAsync(stream);
+            }
+            /////
+            Dictionary<string, object> resdict = new Dictionary<string, object>();
+            string contentRootPath = BaseConfigModel.ContentRootPath;
+            JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
+            XmlDocument xmlDocument = new XmlDocument();
+            string path = contentRootPath + "/OfficeFile/";
+            string filname = ShaHashHelper.GetSHA1(file.OpenReadStream());
+            string extension = System.IO.Path.GetExtension(file.FileName).ToLower();
+            if (System.IO.File.Exists(path + filname + ".pdf") == false)
+            {
+                Console.WriteLine(filname + " Not Exists!");
+                if (extension.Equals(".ppt") || extension.Equals(".doc") || extension.Equals(".pptx") || extension.Equals(".docx"))
+                {
+
+                }
+                else
+                {
+                    throw new BizException("file type does not support!", 500);
+                }
+                if (extension.Equals(".pptx"))
+                {
+                    using (PresentationDocument presentationDocument = PresentationDocument.Open(file.OpenReadStream(), false))
+                    {
+                        if (presentationDocument == null)
+                        {
+                            throw new ArgumentNullException("presentationDocument");
+                        }
+
+                        XDocument xdoc = presentationDocument.ToFlatOpcDocument();
+
+                        xmlDocument.LoadXml(xdoc.ToString());
+
+                        XmlNodeList xmlNodeList = xmlDocument.SelectNodes(@"//mc:Fallback", xmlnsManager);
+                        foreach (XmlNode nodeChild in xmlNodeList)
+                        {
+                            nodeChild.ParentNode.RemoveChild(nodeChild);
+                        }
+                        XmlNodeList xmlNodeListMp4 = xmlDocument.SelectNodes(@"//pkg:part[@pkg:contentType='video/mp4']", xmlnsManager);
+                        XmlDocument document = new XmlDocument();
+                        foreach (XmlNode nodeChild in xmlNodeListMp4)
+                        {
+                            throw new BizException("Please delete the video!/请删除视频再重新上传!", 1001);
+                        }
+                        XmlNodeList xmlNodeListMp3 = xmlDocument.SelectNodes(@"//pkg:part[@pkg:contentType='audio/mpeg']", xmlnsManager);
+                        foreach (XmlNode nodeChild in xmlNodeListMp3)
+                        {
+                            throw new BizException("Please delete the audio!/请删除音频再重新上传!", 1001);
+                        }
+                        var node = xmlDocument.Clone().OuterXml;
+                        XDocument xdocs = XDocument.Parse(node);
+                        presentationDocument.Dispose();
+                        using (PresentationDocument presentationDocumen1t = PresentationDocument.FromFlatOpcDocument(xdocs))
+                        {
+
+                            presentationDocumen1t.SaveAs(path + filname + ".pptx");
+                            presentationDocumen1t.Dispose();
+                        }
+
+                    }
+                    OnWork(path + filname + ".pptx");
+                }
+                else
+                {
+                    Stream sourceStream = file.OpenReadStream();
+                    OnWork(sourceStream, path + filname + extension);
+                }
+            }
+            else { Console.WriteLine(filname + " Exists!"); }
+
+
+
+            PdfDocument inputDocument = PdfSharpCore.Pdf.IO.PdfReader.Open(path + filname + ".pdf", PdfDocumentOpenMode.Import);
+            int count = inputDocument.PageCount;
+            int limit = BaseConfigModel.Configuration.GetSection("HABOOKConfig:PDFLimit").Get<int>();
+            if (count > limit)
+            {
+                throw new BizException("PDF file cannot exceed " + limit + " pages!", 500);
+            }
+            //await ProcessPDF(file, resdict);
+            resdict.Add("page", count);
+            resdict.Add("type", "pdf");
+            resdict.Add("model", new AzureBlobModel()
+            {
+                Folder = "OfficeFile",
+                Sha1Code = filname,
+                BlobUrl = "http://cdhabook.teammodel.cn/pdf/" + filname + ".pdf",
+                ContentType = "application/pdf",
+                ContentDisposition = "form-data; name=\"file\"; filename=\"" + filname + ".pdf\"",
+                Length = inputDocument.FileSize,
+                Name = "file",
+                FileName = filname + ".pdf",
+                RealName = "OfficeFile/" + filname + ".pdf",
+                UploadTime = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000,
+                Extension = "pdf"
+            });
+            return responseBuilder.Data(resdict).build();
+        }
+
+        private bool SaveToFile(Stream stream, string path)
+        {
+            try
+            {
+                byte[] sourceBuffer = new Byte[stream.Length];
+                stream.Read(sourceBuffer, 0, sourceBuffer.Length);
+                stream.Seek(0, SeekOrigin.Begin);
+
+                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
+                {
+                    fs.Write(sourceBuffer, 0, sourceBuffer.Length);
+                    fs.Close();
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine("读取PPT源文件到本地失败:" + ex.Message);
+                return false;
+            }
+            return true;
+        }
+        public bool OnWork(Stream stream, string path)
+        {
+
+            string sourcePath = string.Empty;
+            string destPath = string.Empty;
+            try
+            {
+                //if (FileInfo == null)
+                //    return false;
+                // Stream sourceStream = FileInfo.OpenReadStream();
+                //   string filename = FileInfo.FileName;
+                //  string extension = System.IO.Path.GetExtension(FileInfo.FileName);
+                // sourcePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename + extension);
+                //destPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), string.Format("{0}.pdf", filename));
+
+                if (!SaveToFile(stream, path))
+                {
+                    return false;
+                }
+                var psi = new ProcessStartInfo("libreoffice", string.Format(" --headless --invisible --convert-to pdf {0} --outdir /www/apps/pptx2pdf/OfficeFile/", path)) { RedirectStandardOutput = true };
+                Console.WriteLine(path);
+                //  psi = new ProcessStartInfo("pptx2pdf ", "/www/apps/pptx2pdf/OfficeFile/5e4df6b8-6fbf-4de0-9c94-8de4b5604e45.pptx") { RedirectStandardOutput = true };
+                // 启动
+                var proc = Process.Start(psi);
+                if (proc == null)
+                {
+                    Console.WriteLine("不能执行.");
+                    return false;
+                }
+                else
+                {
+                    Console.WriteLine("-------------开始执行--------------");
+                    //开始读取
+                    using (var sr = proc.StandardOutput)
+                    {
+                        while (!sr.EndOfStream)
+                        {
+                            Console.WriteLine(sr.ReadLine());
+                        }
+                        if (!proc.HasExited)
+                        {
+                            proc.Kill();
+                        }
+                    }
+                    Console.WriteLine("---------------执行完成------------------");
+                    Console.WriteLine($"退出代码 : {proc.ExitCode}");
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+                return false;
+            }
+            finally
+            {
+                //if (System.IO. File.Exists(destPath))
+                //{
+                //    var destFileInfo = UploadFile(destPath, string.Format("{0}.pdf", Path.GetFileNameWithoutExtension( FileInfo.FileName)));
+                //}
+                //if (System.IO.File.Exists(destPath))
+                //{
+                //    System.IO.File.Delete(destPath);
+                //}
+            }
+            return true;
+        }
+        public bool OnWork(string path)
+        {
+
+            //     string sourcePath = string.Empty;
+            //  string destPath = string.Empty;
+            try
+            {
+                //if (FileInfo == null)
+                //    return false;
+                // Stream sourceStream = FileInfo.OpenReadStream();
+                //   string filename = FileInfo.FileName;
+                //  string extension = System.IO.Path.GetExtension(FileInfo.FileName);
+                // sourcePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename + extension);
+                //destPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), string.Format("{0}.pdf", filename));
+
+                //if (!SaveToFile(sourceStream, sourcePath))
+                //    return false;
+                var psi = new ProcessStartInfo("libreoffice", string.Format(" --headless --invisible --convert-to pdf {0} --outdir /www/apps/pptx2pdf/OfficeFile/", path)) { RedirectStandardOutput = true };
+                Console.WriteLine(path);
+                //  psi = new ProcessStartInfo("pptx2pdf ", "/www/apps/pptx2pdf/OfficeFile/5e4df6b8-6fbf-4de0-9c94-8de4b5604e45.pptx") { RedirectStandardOutput = true };
+                // 启动
+                var proc = Process.Start(psi);
+                if (proc == null)
+                {
+                    Console.WriteLine("不能执行.");
+                    return false;
+                }
+                else
+                {
+                    Console.WriteLine("-------------开始执行--------------");
+                    //开始读取
+                    using (var sr = proc.StandardOutput)
+                    {
+                        while (!sr.EndOfStream)
+                        {
+                            Console.WriteLine(sr.ReadLine());
+                        }
+                        if (!proc.HasExited)
+                        {
+                            proc.Kill();
+                        }
+                    }
+                    Console.WriteLine("---------------执行完成------------------");
+                    Console.WriteLine($"退出代码 : {proc.ExitCode}");
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+                return false;
+            }
+            finally
+            {
+                //if (System.IO. File.Exists(destPath))
+                //{
+                //    var destFileInfo = UploadFile(destPath, string.Format("{0}.pdf", Path.GetFileNameWithoutExtension( FileInfo.FileName)));
+                //}
+                //if (System.IO.File.Exists(destPath))
+                //{
+                //    System.IO.File.Delete(destPath);
+                //}
+            }
+            return true;
+        }
+    }
+}

+ 2 - 2
HiTeachCE/Controllers/LoginController.cs

@@ -158,12 +158,12 @@ namespace HiTeachCE.Controllers
         /// <param name="request"></param>
         /// <param name="request"></param>
         /// <returns></returns>
         /// <returns></returns>
         [HttpPost("joinGroup")]
         [HttpPost("joinGroup")]
-        [Authorize(Policy = Constant.Role_Lecturer)]
+        [Authorize(Policy = Constant.Role_LecturerLearner)]
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
         {
             string  ClientId = GetLoginUser(JwtClaimTypes.ClientId);
             string  ClientId = GetLoginUser(JwtClaimTypes.ClientId);
             string  Unionid = GetLoginUser(JwtClaimTypes.Id);
             string  Unionid = GetLoginUser(JwtClaimTypes.Id);
-             string  Role = GetLoginUser(JwtClaimTypes.Role);
+            string  Role = GetLoginUser(JwtClaimTypes.Role);
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
             Dictionary<string, object> dict;
             Dictionary<string, object> dict;
             /**
             /**

+ 1 - 1
HiTeachCE/Controllers/WeChatController.cs

@@ -1,4 +1,4 @@
-using HiTeachCE.Models;
+using HiTeachCE.Models;
 using HiTeachCE.Services;
 using HiTeachCE.Services;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc;

+ 2 - 0
HiTeachCE/Extension/Jwt/JwtAuth.cs

@@ -95,6 +95,8 @@ namespace HiTeachCE.Extension
                 options.AddPolicy(Constant.Role_Learner, policy => policy.RequireRole("learner").Build());
                 options.AddPolicy(Constant.Role_Learner, policy => policy.RequireRole("learner").Build());
                 options.AddPolicy(Constant.Role_RootAdmin, policy => policy.RequireRole("root", "admin").Build());
                 options.AddPolicy(Constant.Role_RootAdmin, policy => policy.RequireRole("root", "admin").Build());
                 options.AddPolicy(Constant.Role_WebAll, policy => policy.RequireRole("root", "admin", "lecturer").Build());
                 options.AddPolicy(Constant.Role_WebAll, policy => policy.RequireRole("root", "admin", "lecturer").Build());
+                options.AddPolicy(Constant.Role_LecturerLearner, policy => policy.RequireRole("lecturer", "learner").Build());
+                
             });
             });
         }
         }
     }
     }

+ 2 - 0
HiTeachCE/Helpers/Constant.cs

@@ -14,5 +14,7 @@ namespace HiTeachCE.Helpers
         public const string Role_Lecturer = "lecturer";
         public const string Role_Lecturer = "lecturer";
         public const string Role_Learner = "learner";
         public const string Role_Learner = "learner";
         public const string Role_RootAdmin = "RootAdmin";
         public const string Role_RootAdmin = "RootAdmin";
+        public const string Role_LecturerLearner = "LecturerLearner";
+        
     }
     }
 }
 }

+ 1 - 0
HiTeachCE/HiTeachCE.csproj

@@ -23,6 +23,7 @@
     <PackageReference Include="TEAMModelOS.SDK" Version="3.0.520" />
     <PackageReference Include="TEAMModelOS.SDK" Version="3.0.520" />
     <PackageReference Include="ToolGood.Words" Version="3.0.1.2" />
     <PackageReference Include="ToolGood.Words" Version="3.0.1.2" />
     <PackageReference Include="VueCliMiddleware" Version="3.0.0" />
     <PackageReference Include="VueCliMiddleware" Version="3.0.0" />
+    <PackageReference Include="PdfSharpCore" Version="1.1.27" />
   </ItemGroup>
   </ItemGroup>
   <ItemGroup>
   <ItemGroup>
     <!-- Don't publish the SPA source files, but do show them in the project files list -->
     <!-- Don't publish the SPA source files, but do show them in the project files list -->