From 6c8bf8c9c60e38a0f93c0f70bf2fbb52d1078535 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 28 Sep 2017 17:27:33 +0200 Subject: [PATCH 01/11] Cosmetics --- Site/Controls/v5/Base/FileUpload.ascx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Site/Controls/v5/Base/FileUpload.ascx b/Site/Controls/v5/Base/FileUpload.ascx index c6bccec8..b5e5c7a9 100644 --- a/Site/Controls/v5/Base/FileUpload.ascx +++ b/Site/Controls/v5/Base/FileUpload.ascx @@ -111,13 +111,11 @@
-
-
-
-
-
+
+
+
+
-
From 6a0d7fb89a06bfcf2dc5b61998cd5c69876f6f47 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 28 Sep 2017 17:40:08 +0200 Subject: [PATCH 02/11] Cosmetics Test --- Site/Controls/v5/Base/FileUpload.ascx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Site/Controls/v5/Base/FileUpload.ascx b/Site/Controls/v5/Base/FileUpload.ascx index b5e5c7a9..04766119 100644 --- a/Site/Controls/v5/Base/FileUpload.ascx +++ b/Site/Controls/v5/Base/FileUpload.ascx @@ -105,7 +105,7 @@
- +
@@ -113,8 +113,8 @@
-
-
+
+
From 9d07124ea99c37a634270f338fc9cf123de14679 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 28 Sep 2017 17:52:03 +0200 Subject: [PATCH 03/11] Cosmetics Test --- Site/Controls/v5/Base/FileUpload.ascx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Site/Controls/v5/Base/FileUpload.ascx b/Site/Controls/v5/Base/FileUpload.ascx index 04766119..1be64f4a 100644 --- a/Site/Controls/v5/Base/FileUpload.ascx +++ b/Site/Controls/v5/Base/FileUpload.ascx @@ -114,7 +114,7 @@
-
+
From 2e25fe4cd30dc7d9c7bab32f61fad95fa8b35991 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Fri, 29 Sep 2017 13:28:33 +0200 Subject: [PATCH 04/11] Pdf async conversion - Code test --- Site/Automation/Json-ByGuid.aspx.cs | 19 +- Site/Automation/UploadFileHandler.ashx | 291 +++++++++++++++++++++---- Site/Controls/v5/Base/FileUpload.ascx | 38 +++- 3 files changed, 298 insertions(+), 50 deletions(-) diff --git a/Site/Automation/Json-ByGuid.aspx.cs b/Site/Automation/Json-ByGuid.aspx.cs index 08eeceee..226d25a4 100644 --- a/Site/Automation/Json-ByGuid.aspx.cs +++ b/Site/Automation/Json-ByGuid.aspx.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Web.Services; using Swarmops.Logic.Cache; using Swarmops.Frontend; @@ -12,7 +13,7 @@ namespace Swarmops.Frontend.Automation } [WebMethod] - public static int GetProgress (string guid) + public static int GetProgress (string guid) // This is a legacy method { object progressObject = GuidCache.Get (guid + "-Progress"); // suffix because guid may refer to other data too @@ -26,5 +27,21 @@ namespace Swarmops.Frontend.Automation return 0; } + + [WebMethod] + public static AjaxCallResult GetNonsocketProgress (string guid) + { + object progressObject = GuidCache.Get(guid + "-Progress"); + // suffix because guid may refer to other data too + + if (progressObject != null) + { + return new AjaxCallResult {Success = true, DisplayMessage = ((int) progressObject).ToString(CultureInfo.InvariantCulture) }; + } + + // if the progress object doesn't exist, assume it hasn't been initialized yet + + return new AjaxCallResult {Success = false}; + } } } \ No newline at end of file diff --git a/Site/Automation/UploadFileHandler.ashx b/Site/Automation/UploadFileHandler.ashx index 763028d1..9550fa88 100644 --- a/Site/Automation/UploadFileHandler.ashx +++ b/Site/Automation/UploadFileHandler.ashx @@ -7,8 +7,11 @@ using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; +using System.Threading; using System.Web; using System.Web.Script.Serialization; +using System.Web.Services; +using Swarmops.Logic.Cache; using Swarmops.Logic.Structure; using Swarmops.Logic.Support; using Swarmops.Logic.Swarm; @@ -19,7 +22,7 @@ namespace Swarmops.Frontend.Automation { private readonly JavaScriptSerializer js = new JavaScriptSerializer(); - public string StorageRoot + public static string StorageRoot { get { @@ -149,6 +152,10 @@ namespace Swarmops.Frontend.Automation // Upload entire file private void UploadWholeFile(HttpContext context, List statuses) { + string guid = context.Request.QueryString["Guid"]; + List pdfsForConversion = new List(); + List pdfClientNames = new List(); + for (int i = 0; i < context.Request.Files.Count; i++) { HttpPostedFile file = context.Request.Files[i]; @@ -208,8 +215,6 @@ namespace Swarmops.Frontend.Automation } } - string guid = context.Request.QueryString["Guid"]; - if (string.IsNullOrEmpty(guid)) { throw new ArgumentException("No Context Guid supplied with upload"); @@ -255,7 +260,6 @@ namespace Swarmops.Frontend.Automation // Convert PDF file into a series of PNG images, one per page int pageCounter = 0; - Process process = null; if (WeAreInDebugEnvironment) @@ -264,46 +268,44 @@ namespace Swarmops.Frontend.Automation "/c convert -background white -flatten " + StorageRoot + relativeFileName + " " + StorageRoot + relativeFileName + "-%04d.png"); + + process.WaitForExit(); + + if (process.ExitCode != 0) + { + FilesStatus errorStatus = new FilesStatus(fullName, -1); //file.ContentLength); + errorStatus.error = "ERR_BAD_PDF"; + errorStatus.url = string.Empty; + errorStatus.delete_url = string.Empty; + errorStatus.thumbnail_url = string.Empty; + + statuses.Add(errorStatus); + // -1 for length means the file was NOT saved, and that it could not be parsed. + return; + } + + string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + + while (File.Exists(StorageRoot + testPageFileName)) + { + long fileLength = new FileInfo(StorageRoot + testPageFileName).Length; + + Document.Create(testPageFileName, + file.FileName + " " + (pageCounter + 1).ToString(CultureInfo.InvariantCulture), fileLength, + guid, null, authData.CurrentUser); + + pageCounter++; + testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + } } else { - // TODO: Send the tast to do this to backend; tell frontend to display an "in progress" - // TODO icon (rotating cogs on top of document maybe) and to listen for "conversion complete" - // TODO message from backend to know there's an accepted document + FilesStatus requiresConversion = new FilesStatus(fullName, -1); + requiresConversion.requiresPdfConversion = true; + statuses.Add(requiresConversion); - process = Process.Start("bash", - "-c \"convert -density 600 -background white -flatten " + StorageRoot + relativeFileName + " " + - StorageRoot + relativeFileName + - "-%04d.png\""); // Density 600 means 600dpi means production-grade conversion - } - - process.WaitForExit(); - - if (process.ExitCode != 0) - { - FilesStatus errorStatus = new FilesStatus(fullName, -1); //file.ContentLength); - errorStatus.error = "ERR_BAD_PDF"; - errorStatus.url = string.Empty; - errorStatus.delete_url = string.Empty; - errorStatus.thumbnail_url = string.Empty; - - statuses.Add(errorStatus); - // -1 for length means the file was NOT saved, and that it could not be parsed. - return; - } - - string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); - - while (File.Exists(StorageRoot + testPageFileName)) - { - long fileLength = new FileInfo(StorageRoot + testPageFileName).Length; - - Document.Create(testPageFileName, - file.FileName + " " + (pageCounter + 1).ToString(CultureInfo.InvariantCulture), fileLength, - guid, null, authData.CurrentUser); - - pageCounter++; - testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + pdfsForConversion.Add(relativeFileName); + pdfClientNames.Add(file.FileName); } } else @@ -315,8 +317,216 @@ namespace Swarmops.Frontend.Automation statuses.Add(new FilesStatus(fullName, file.ContentLength)); } + + GuidCache.Set("PdfsForConversion-" + guid, pdfsForConversion.ToArray()); + GuidCache.Set("PdfClientNames-" + guid, pdfClientNames.ToArray()); } + + [WebMethod] + public static AjaxCallResult BeginPdfConversion(string guid) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + ProcessThreadArguments args = new ProcessThreadArguments + { + CurrentUser = authData.CurrentUser, + Organization = authData.CurrentOrganization, + Guid = guid + }; + + Thread initThread = new Thread(ConvertPdfThread); + initThread.Start(args); + + return new AjaxCallResult {Success = true}; + } + + [WebMethod] + public static AjaxConversionCallResult GetPdfConversionResult (string guid) + { + return (AjaxConversionCallResult) GuidCache.Get("PdfConversionResult-" + guid); + } + + public class AjaxConversionCallResult: AjaxCallResult + { + public int SuccessCount { get; set; } + public int FailCount { get; set; } + public string[] FailFileNames { get; set; } + } + + private static void ConvertPdfThread(object args) + { + ProcessThreadArguments argsProper = (ProcessThreadArguments) args; + List failedConversionFileNames = new List(); + + using (StreamWriter debugWriter = new StreamWriter("/tmp/PdfConversionDebug-" + argsProper.Guid + ".txt")) + { + + try + { + debugWriter.WriteLine("ConvertPdfThread started"); + + string[] relativeFileNames = (string[]) GuidCache.Get("PdfsForConversion-" + argsProper.Guid); + string[] clientFileNames = (string[]) GuidCache.Get("PdfClientNames-" + argsProper.Guid); + GuidCache.Delete("PdfsForConversion-" + argsProper.Guid); + GuidCache.Delete("PdfsClientNames-" + argsProper.Guid); + int fileCount = relativeFileNames.Length; + int successCount = 0; + int failCount = 0; + + Process process = null; + + for (int fileIndex = 0; fileIndex < fileCount; fileIndex++) + { + // Set progress to indicate we're at file 'index' of 'fileCount' + + int progress = fileIndex*99/fileCount; // 99 at most -- 100 indicates complete + int progressMax = (fileIndex + 1)*99/fileCount - 1; + int progressFileStep = 99/fileCount; + int currentFilePageCount = 0; + int currentFilePageStep = 0; + + string relativeFileName = relativeFileNames[fileIndex]; + + debugWriter.WriteLine("------------------------------------"); + debugWriter.WriteLine("{3:D2}%, Converting PDF file {0} of {1}; {2}", fileIndex + 1, fileCount, + relativeFileName, progress); + + // Use qpdf to determine the number of pages in the PDF + + string pageCountFileName = "/tmp/pagecount-" + argsProper.Guid + ".txt"; + + process = Process.Start("bash", + "-c \"qpdf --show-npages " + StorageRoot + relativeFileName + " > " + pageCountFileName + "\""); + + process.WaitForExit(); + + if (process.ExitCode != 0) + { + // Bad PDF file + failCount ++; + failedConversionFileNames.Add( + ((string[]) GuidCache.Get("PdfClientNames-" + argsProper.Guid))[fileIndex].Replace("'", "") + .Replace("\"", "")); // caution; we're displaying user input, guard against XSS + continue; + } + + // Read the resulting page count from the file we piped + + using (StreamReader pageCountReader = new StreamReader(pageCountFileName)) + { + string pageCountString = pageCountReader.ReadToEnd().Trim(); + debugWriter.WriteLine("{0:D2}%, page count is '{1}'", progress, pageCountString); + currentFilePageCount = Int32.Parse(pageCountString); + debugWriter.WriteLine("{0:D2}%, parsed to int as {1}", progress, currentFilePageCount); + currentFilePageStep = progressFileStep/currentFilePageCount; + } + + File.Delete(pageCountFileName); + + // Begin the conversion + + debugWriter.WriteLine("{0:D2}%, deleted page count file, starting conversion process", progress); + + process = Process.Start("bash", + "-c \"convert -density 600 -background white -flatten " + StorageRoot + relativeFileName + + " " + + StorageRoot + relativeFileName + + "-%04d.png\""); // Density 600 means 600dpi means production-grade conversion + + int pageCounter = 0; // the first produced page will be zero + int currentPageBaseProgress = progressFileStep*fileIndex + currentFilePageStep*pageCounter; + int tenthsSecondWaiting = 0; + string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + string lastPageFileName = testPageFileName; + + while (pageCounter < currentFilePageCount) + { + while (!File.Exists(StorageRoot + testPageFileName)) + { + // Wait for file to appear + + tenthsSecondWaiting++; + progress = currentPageBaseProgress + + Math.Min(tenthsSecondWaiting, 50)*currentFilePageStep/2/50; // advance to 1/2 page over 5s while waiting + debugWriter.WriteLine("{0:D2}%, waiting for page #{1} to appear", progress, pageCounter+1); + GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress); + + Thread.Sleep(100); + } + + progress = currentPageBaseProgress + currentFilePageStep; + if (progress > 99) + { + progress = 99; // can't reach 100 before finished + } + debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter); + GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress); + + // If the page# file that has appeared is 1+, then the preceding file is ready + + if (pageCounter > 0) + { + long fileLength = new FileInfo(StorageRoot + lastPageFileName).Length; + debugWriter.WriteLine("{0:D2}%, saving page #{1}, bytecount {2}", progress, pageCounter, fileLength); + + Document.Create(lastPageFileName, + clientFileNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), + fileLength, argsProper.Guid, null, argsProper.CurrentUser); + + // Prepare to save the next file + lastPageFileName = testPageFileName; + } + + // Increase the page counter and the file we're looking for + + pageCounter++; + testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + } + + // We've seen the last page being written -- wait for process to exit + debugWriter.WriteLine("{0:D2}%, waiting for process exit"); + + process.WaitForExit(); + + // Save the last page + + long fileLengthLastPage = new FileInfo(StorageRoot + lastPageFileName).Length; + debugWriter.WriteLine("{0:D2}%, saving last page #{1}, bytecount {2}", progress, pageCounter, fileLengthLastPage); + + Document.Create(lastPageFileName, + clientFileNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), + fileLengthLastPage, argsProper.Guid, null, argsProper.CurrentUser); + + } + + + } + catch (Exception e) + { + debugWriter.WriteLine("Exception thrown: " + e.ToString()); + + throw; + } + finally + { + debugWriter.WriteLine("Thread exiting"); + + GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", 100); + // only here may the caller fetch the results + } + } + } + + + + private class ProcessThreadArguments + { + public string Guid { get; set; } + public Organization Organization { get; set; } + public Person CurrentUser { get; set; } + } + + private void WriteJsonIframeSafe(HttpContext context, List statuses) { context.Response.AddHeader("Vary", "Accept"); @@ -400,6 +610,7 @@ namespace Swarmops.Frontend.Automation public string delete_url { get; set; } public string delete_type { get; set; } public string error { get; set; } + public bool requiresPdfConversion { get; set; } private void SetValues(string fileName, int fileLength) { diff --git a/Site/Controls/v5/Base/FileUpload.ascx b/Site/Controls/v5/Base/FileUpload.ascx index 1be64f4a..32fe1d76 100644 --- a/Site/Controls/v5/Base/FileUpload.ascx +++ b/Site/Controls/v5/Base/FileUpload.ascx @@ -20,8 +20,11 @@ dataType: 'json', done: function (e, data) { var pdfConversionNeeded = false; - $.each(data.result, function(index, file) { - if (file.error == null || file.error.length < 1) { + $.each(data.result, function (index, file) { + if (file.requiresPdfConversion) { + pdfConversionNeeded = true; + } + else if (file.error == null || file.error.length < 1) { $('#<%=this.ClientID %>_DivUploadCount').append(imageUploadSuccess); } else { $('#<%=this.ClientID %>_DivUploadCount').append(imageUploadFail); // Assume ERR_NOT_IMAGE @@ -29,10 +32,20 @@ } }); + $('#<%=this.ClientID %>_DivProgressUpload').progressbar({ value: 100 }); if (pdfConversionNeeded) { $('#<%=this.ClientID %>_DivProgressPdfConversion').progressbar({ value: 1 }); - $('#<%=this.ClientID %>_DivMainControlArea').fadeOut('400', function() { $('#<%=this.ClientID %>_DivPdfConverting').fadeIn(); }); + $('#<%=this.ClientID %>_DivMainControlArea').fadeOut('400', function () { $('#<%=this.ClientID %>_DivPdfConverting').fadeIn(); }); + var jsonData = {}; + jsonData.guid = '<%=GuidString%>'; + + SwarmopsJS.ajaxCall("/Automation/UploadFileHandler.ashx/BeginPdfConversion", + jsonData, + function() { + // Successful start + alertify.success('Started PDF conversion thread'); + }); } else { <% if (!String.IsNullOrEmpty(this.ClientUploadCompleteCallback)) @@ -84,16 +97,23 @@ jsonData.guid = "Pdf-<%=GuidString%>"; SwarmopsJS.ajaxCall( - "/Automation/Json-ByGuid.aspx/GetProgress2", + "/Automation/Json-ByGuid.aspx/GetNonsocketProgress", jsonData, - function(result) { + function (result) { + if (result.Success) { + var progressPercent = parseInt(result.DisplayMessage); + $("#<%=this.ClientID %>_DivProgressPdfConvert .progressbar-value").animate( + { + width: progressPercent + "%" + }, { queue: false }); + + setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500); + } }, function(error) { } ); - SwarmopsJS.ajaxCall() - setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500); } @@ -112,9 +132,9 @@
-
+
-
+
From 911b6154f2221522e826d4107b40aacf737c2796 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Fri, 29 Sep 2017 13:38:10 +0200 Subject: [PATCH 05/11] Pdf async conversion - Code test 2 --- Site/Automation/UploadFileHandler.ashx | 4 ++-- Site/Controls/v5/Base/FileUpload.ascx | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Site/Automation/UploadFileHandler.ashx b/Site/Automation/UploadFileHandler.ashx index 9550fa88..eeeeb3e2 100644 --- a/Site/Automation/UploadFileHandler.ashx +++ b/Site/Automation/UploadFileHandler.ashx @@ -459,7 +459,7 @@ namespace Swarmops.Frontend.Automation { progress = 99; // can't reach 100 before finished } - debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter); + debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter+1); GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress); // If the page# file that has appeared is 1+, then the preceding file is ready @@ -484,7 +484,7 @@ namespace Swarmops.Frontend.Automation } // We've seen the last page being written -- wait for process to exit - debugWriter.WriteLine("{0:D2}%, waiting for process exit"); + debugWriter.WriteLine("{0:D2}%, waiting for process exit", progress); process.WaitForExit(); diff --git a/Site/Controls/v5/Base/FileUpload.ascx b/Site/Controls/v5/Base/FileUpload.ascx index 32fe1d76..f5e9b2e7 100644 --- a/Site/Controls/v5/Base/FileUpload.ascx +++ b/Site/Controls/v5/Base/FileUpload.ascx @@ -45,6 +45,7 @@ function() { // Successful start alertify.success('Started PDF conversion thread'); + setTimeout(function() { <%=this.ClientID%>_repingPdfProgress() }, 500); }); } else { @@ -107,7 +108,11 @@ width: progressPercent + "%" }, { queue: false }); - setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500); + if (progressPercent < 100) { + setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500); + } else { + // PDF CONVERSION COMPLETE, handle this + } } }, function(error) { @@ -128,9 +133,7 @@ - -
-
+