This commit is contained in:
Rick Falkvinge
2017-10-01 12:34:18 +02:00
3 changed files with 324 additions and 61 deletions
+18 -1
View File
@@ -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};
}
}
}
+262 -40
View File
@@ -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<FilesStatus> statuses)
{
string guid = context.Request.QueryString["Guid"];
List<string> pdfsForConversion = new List<string>();
List<string> pdfClientNames = new List<string>();
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,227 @@ 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<string> failedConversionFileNames = new List<string>();
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 > /tmp/PdfConversionOutput-" + argsProper.Guid + "\""); // Density 600 means 600dpi means production-grade conversion
process.PriorityClass = ProcessPriorityClass.Idle; // play real nice now
int pageCounter = 0; // the first produced page will be zero
int currentPageBaseProgress = progressFileStep*fileIndex + currentFilePageStep*pageCounter;
int quarterSecondWaiting = 0;
string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
string lastPageFileName = testPageFileName;
while (pageCounter < currentFilePageCount)
{
while (!File.Exists(StorageRoot + testPageFileName))
{
// Wait for file to appear
quarterSecondWaiting++;
progress = currentPageBaseProgress +
Math.Min(quarterSecondWaiting, 50)*currentFilePageStep/2/50; // advance to 1/2 page over 5s while waiting
debugWriter.WriteLine("{0:D2}%, {2:O}, waiting for page #{1} to appear", progress, pageCounter+1, DateTime.UtcNow);
debugWriter.Flush();
GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress);
process.WaitForExit(250); // this is a more elaborate version of thread.sleep that prevents Apache recycling
if (process.HasExited)
{
debugWriter.WriteLine("{0:D2}%, PROCESS HAS EXITED out of order with conversion", progress);
break;
}
}
currentPageBaseProgress = progressFileStep*fileIndex + currentFilePageStep*(pageCounter+1);
progress = currentPageBaseProgress;
quarterSecondWaiting = 0;
if (progress > 99)
{
progress = 99; // can't reach 100 before finished
}
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
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);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
}
// We've seen the last page being written -- wait for process to exit
debugWriter.WriteLine("{0:D2}%, waiting for process exit", progress);
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<FilesStatus> statuses)
{
context.Response.AddHeader("Vary", "Accept");
@@ -400,6 +621,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)
{
+44 -20
View File
@@ -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,21 @@
}
});
$('#<%=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');
setTimeout(function() { <%=this.ClientID%>_repingPdfProgress() }, 500);
});
} else {
<% if (!String.IsNullOrEmpty(this.ClientUploadCompleteCallback))
@@ -84,16 +98,30 @@
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 });
if (progressPercent < 100) {
setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500);
} else {
// PDF CONVERSION COMPLETE, handle this
}
}
},
function(error) {
function (error) {
// try again
setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500);
}
);
SwarmopsJS.ajaxCall()
setTimeout(function() { <%=this.ClientID%>_repingPdfProgress(); }, 500);
}
</script>
@@ -105,19 +133,15 @@
</div>
<div style="height:36px;padding-top:4px;width:270px;margin-right:10px;float:right;border:none">
<div id="<%=this.ClientID %>_DivUploadCount" style='display:none;overflow:hidden;height:'<%=this.DisplayCount < 9? 32: 64%>px'></div>
<div id="<%=this.ClientID %>_DivProgressUpload" style="width:100%;margin-top:8px;display:none"></div>
<div id="<%=this.ClientID %>_DivProgressUpload" style="width:100%;margin-top:10px;display:none"></div>
</div>
</div>
<div id="<%=this.ClientID %>_DivPdfConverting" style="display:none">
<div style="position: relative; width:100%">
<div style="position: absolute; top: 4px; left: 4px; z-index:4"><img src="/Images/Icons/iconshock-pdf-128px.png" height="32" width="32"/></div>
<div style="position: absolute; top: 0; left: -6px; z-index:2"><img src="/Images/Abstract/ajaxloader-48x36px.gif" height="36" width="48"/></div>
<div id="<%=this.ClientID %>_DivProgressPdfConvert" style="position: absolute; top: 10px; z-index: 0"></div>
</div>
</div>
</div>
<div class="stacked-input-control">
<div id="<%=this.ClientID %>_DivPdfConverting">
<div style="position:relative">
<div style="position: absolute; top: 0; left: 0; z-index:0"><img src="/Images/Icons/iconshock-pdf-128px.png" height="32" width="32"/>
<div style="position: absolute; top: 0; left: 0; z-index:1"><img src="/Images/Abstract/ajaxloader-48x36px.gif" height="32" width="32"/></div>
<div id="<%=this.ClientID %>_DivProgressPdfConvert" style="position: absolute; top: 8px; left: 40px; width:100%"></div>
</div>
</div>
</div>
</div>