public async Task<IHttpActionResult> Post(HTMLtoPDFJob job)
 {
     Guid userId = RoboBrailleProcessor.getUserIdFromJob(this.Request.Headers.Authorization.Parameter);
     job.UserId = userId;
     if (RoboBrailleProcessor.IsSameJobProcessing(job, _repository.GetDataContext()))
     {
         var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
         {
             Content = new StringContent(string.Format("The file with the name {0} is already being processed", job.FileName)),
             ReasonPhrase = "Job already processing"
         };
         throw new HttpResponseException(resp);
     }
     Guid jobId = await _repository.SubmitWorkItem(job);
     return Ok(jobId.ToString("D"));
 }
Пример #2
0
        /// <summary>
        /// Reads the input from the POST requests and creates the appropriate job instance
        /// </summary>
        /// <param name="type"></param>
        /// <param name="readStream"></param>
        /// <param name="content"></param>
        /// <param name="formatterLogger"></param>
        /// <returns></returns>
        public override async Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (content == null)
            {
                return(null);
            }

            var tempStorage         = Path.GetTempPath();
            var tempStorageProvider = new MultipartFormDataStreamProvider(tempStorage);
            var msp = await content.ReadAsMultipartAsync(tempStorageProvider);

            Job job = null;

            if (type == typeof(AccessibleConversionJob))
            {
                job = new AccessibleConversionJob
                {
                    TargetDocumentFormat = (OutputFileFormatEnum)Enum.Parse(typeof(OutputFileFormatEnum), msp.FormData["targetdocumentformat"])//Convert.ToInt32(msp.FormData["targetformat"]),
                };

                if (msp.FormData.AllKeys.Contains("priority"))
                {
                    ((AccessibleConversionJob)job).Priority = (PriorityEnum)Enum.Parse(typeof(PriorityEnum), msp.FormData["priority"]);
                }
                else
                {
                    ((AccessibleConversionJob)job).Priority = PriorityEnum.P_Normal;
                }
            }
            else if (type == typeof(AudioJob))
            {
                job = new AudioJob()
                {
                    AudioLanguage = (Language)Enum.Parse(typeof(Language), msp.FormData["audiolanguage"]),
                    SpeedOptions  = (AudioSpeed)Enum.Parse(typeof(AudioSpeed), msp.FormData["speedoptions"]),
                    FormatOptions = (AudioFormat)Enum.Parse(typeof(AudioFormat), msp.FormData["formatoptions"])
                };
                if (msp.FormData.AllKeys.Contains("voicepropriety"))
                {
                    string[] props = msp.FormData["voicepropriety"].Split(':');
                    List <VoicePropriety> propList = new List <VoicePropriety>();
                    foreach (string prop in props)
                    {
                        propList.Add((VoicePropriety)Enum.Parse(typeof(VoicePropriety), prop));
                    }
                    ((AudioJob)job).VoicePropriety = propList;
                }
                else
                {
                    ((AudioJob)job).VoicePropriety = new List <VoicePropriety>()
                    {
                        VoicePropriety.None
                    }
                };
            }
            else if (type == typeof(BrailleJob))
            {
                job = new BrailleJob
                {
                    BrailleFormat     = (BrailleFormat)Enum.Parse(typeof(BrailleFormat), msp.FormData["brailleformat"]),
                    BrailleLanguage   = (Language)Enum.Parse(typeof(Language), msp.FormData["language"]),
                    Contraction       = (BrailleContraction)Enum.Parse(typeof(BrailleContraction), msp.FormData["contraction"]),
                    OutputFormat      = (OutputFormat)Enum.Parse(typeof(OutputFormat), msp.FormData["outputformat"]),
                    ConversionPath    = (ConversionPath)int.Parse(msp.FormData["conversionpath"]),
                    CharactersPerLine = int.Parse(msp.FormData["charactersperline"]),
                    LinesPerPage      = int.Parse(msp.FormData["linesperpage"])
                };

                if (msp.FormData.AllKeys.Contains("pagenumbering"))
                {
                    ((BrailleJob)job).PageNumbering = (PageNumbering)int.Parse(msp.FormData["pagenumbering"]);
                }
            }
            else if (type == typeof(DaisyJob))
            {
                job = new DaisyJob
                {
                    DaisyOutput = (DaisyOutput)Enum.Parse(typeof(DaisyOutput), msp.FormData["daisyoutput"])
                };
            }
            else if (type == typeof(EBookJob))
            {
                job = new EBookJob
                {
                    EbookFormat = (EbookFormat)Enum.Parse(typeof(EbookFormat), msp.FormData["format"])
                };
                if (msp.FormData.AllKeys.Contains("basefontsize"))
                {
                    ((EBookJob)job).BaseFontSize = (EbookBaseFontSize)Enum.Parse(typeof(EbookBaseFontSize), msp.FormData["basefontsize"]);
                }
            }
            else if (type == typeof(HTMLtoPDFJob))
            {
                job = new HTMLtoPDFJob
                {
                    paperSize = (PaperSize)Enum.Parse(typeof(PaperSize), msp.FormData["size"])
                };
            }
            else if (type == typeof(MSOfficeJob))
            {
                job = new MSOfficeJob
                {
                    MSOfficeOutput = (MSOfficeOutput)Enum.Parse(typeof(MSOfficeOutput), msp.FormData["msofficeoutput"])
                };
                if (msp.FormData.AllKeys.Contains("subtitlelangauge") && msp.FormData.AllKeys.Contains("subtitleformat"))
                {
                    ((MSOfficeJob)job).SubtitleLangauge = msp.FormData["subtitlelangauge"];
                    ((MSOfficeJob)job).SubtitleFormat   = msp.FormData["subtitleformat"];
                }
            }
            else if (type == typeof(OcrConversionJob))
            {
                job = new OcrConversionJob
                {
                    OcrLanguage = (Language)Enum.Parse(typeof(Language), msp.FormData["language"]),
                    HasTable    = false
                };
                if (msp.FormData.AllKeys.Contains("hastable"))
                {
                    ((OcrConversionJob)job).HasTable = bool.Parse(msp.FormData["hastable"]);
                }
            }
            else if (type == typeof(HTMLToTextJob))
            {
                job = new HTMLToTextJob();
            }
            else if (type == typeof(AmaraSubtitleJob))
            {
                job = new AmaraSubtitleJob()
                {
                    SubtitleLangauge = msp.FormData["language"],
                    SubtitleFormat   = msp.FormData["format"]
                };
                if (msp.FormData.AllKeys.Contains("videourl"))
                {
                    ((AmaraSubtitleJob)job).VideoUrl = msp.FormData["videourl"];
                }
            }
            else if (type == typeof(DocumentStructureJob))
            {
                job = new DocumentStructureJob()
                {
                };
            }
            else if (type == typeof(TranslationJob))
            {
                job = new TranslationJob()
                {
                    SourceLanguage = msp.FormData["sourcelanguage"],
                    TargetLanguage = msp.FormData["targetlanguage"]
                };
            }
            else if (type == typeof(SignLanguageJob))
            {
                job = new SignLanguageJob()
                {
                    SourceTextLanguage = msp.FormData["sourcetextlanguage"],
                    TargetSignLanguage = msp.FormData["targetsignlanguage"]
                };
            }

            if (job == null)
            {
                return(null);
            }
            else
            {
                if (msp.FileData.Count > 0)
                {
                    job.FileContent = File.ReadAllBytes(msp.FileData[0].LocalFileName);
                    string fileName = msp.FileData[0].Headers.ContentDisposition.FileName.Replace("\"", "").ToString();
                    job.FileName      = fileName.Substring(0, fileName.LastIndexOf("."));
                    job.FileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
                    job.MimeType      = msp.FileData[0].Headers.ContentType.MediaType;
                }
                else if (msp.FormData["lastjobid"] != null)
                {
                    //1) check if a guid is present and exists in the database. 2) get the byte content from the database and use it in the new job
                    Guid previousJobId = Guid.Parse(msp.FormData["lastjobid"]);
                    RoboBrailleDataContext _context = new RoboBrailleDataContext();
                    Job previousJob = RoboBrailleProcessor.CheckForJobInDatabase(previousJobId, _context);
                    if (previousJob != null)
                    {
                        job.FileContent   = previousJob.ResultContent;
                        job.FileName      = previousJob.FileName;
                        job.FileExtension = previousJob.ResultFileExtension;
                        job.MimeType      = previousJob.ResultMimeType;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    //if not assume it is a URL
                    if (!String.IsNullOrWhiteSpace(msp.FormData["FileContent"]))
                    {
                        string sorh = msp.FormData["FileContent"];
                        Uri    uriResult;
                        bool   result = Uri.TryCreate(sorh, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                        if (result)
                        {
                            var webRequest = WebRequest.Create(uriResult);

                            using (var response = webRequest.GetResponse())
                                using (var httpcontent = response.GetResponseStream())
                                    using (var reader = new StreamReader(httpcontent))
                                    {
                                        job.FileContent   = Encoding.UTF8.GetBytes(reader.ReadToEnd());
                                        job.FileName      = DateTime.Now.Ticks + "-RoboFile";
                                        job.FileExtension = ".html";
                                        job.MimeType      = "text/html";
                                    }
                        }
                        else //else it must be a file
                        {
                            job.FileContent   = Encoding.UTF8.GetBytes(sorh);
                            job.FileName      = DateTime.Now.Ticks + "-RoboFile";
                            job.FileExtension = ".txt";
                            job.MimeType      = "text/plain";
                        }
                    }
                    else
                    {
                        //it's a video job
                    }
                }
                if (type != typeof(AmaraSubtitleJob))
                {
                    job.InputFileHash = RoboBrailleProcessor.GetMD5Hash(job.FileContent);
                }
                job.Status     = JobStatus.Started;
                job.SubmitTime = DateTime.Now;
                return(job);
            }
        }
        public async Task TestHtmlToPDFConversion()
        {
            //init
            var mockJobs = new Mock<DbSet<Job>>();
            var mockServiceUsers = new Mock<DbSet<ServiceUser>>();
            var mockContext = new Mock<RoboBrailleDataContext>();

            // arrange
            var users = new List<ServiceUser> { 
                new ServiceUser
                {
                EmailAddress = "*****@*****.**",
                UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                ApiKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"),
                FromDate = new DateTime(2015, 1, 1),
                ToDate = new DateTime(2020, 1, 1),
                UserName = "******",
                Jobs = null
                }
            }.AsQueryable();

            HTMLtoPDFJob hpj = new HTMLtoPDFJob()
            {
                Id = Guid.NewGuid(),
                FileContent = new byte[512],
                UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension = ".pdf",
                FileName = "test",
                MimeType = "application/pdf",
                Status = JobStatus.Started,
                SubmitTime = DateTime.Now,
                DownloadCounter = 0,
                InputFileHash = new byte[8],
                paperSize = PaperSize.a4
            };
            HTMLtoPDFJob hpj2 = new HTMLtoPDFJob()
            {
                Id = Guid.NewGuid(),
                FileContent = new byte[256],
                UserId = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension = ".txt",
                FileName = "test2",
                MimeType = "text/plain",
                Status = JobStatus.Done,
                SubmitTime = DateTime.Now,
                DownloadCounter = 2,
                InputFileHash = new byte[2]
            };
            var jobs = new List<HTMLtoPDFJob> { hpj2 }.AsQueryable();

            mockJobs.As<IDbAsyncEnumerable<Job>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<Job>(jobs.GetEnumerator()));
            mockJobs.As<IQueryable<Job>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<Job>(jobs.Provider));

            mockJobs.As<IQueryable<Job>>().Setup(m => m.Expression).Returns(jobs.Expression);
            mockJobs.As<IQueryable<Job>>().Setup(m => m.ElementType).Returns(jobs.ElementType);
            mockJobs.As<IQueryable<Job>>().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator());

            mockServiceUsers.As<IDbAsyncEnumerable<ServiceUser>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<ServiceUser>(users.GetEnumerator()));
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<ServiceUser>(users.Provider));
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Expression).Returns(users.Expression);
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.ElementType).Returns(users.ElementType);
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());

            mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object);
            mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object);

            var repo = new HTMLtoPDFRepository(mockContext.Object);
            var request = new HttpRequestMessage();
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\"");
            var serviceController = new HTMLtoPDFController(repo);
            serviceController.Request = request;
            //call
            await serviceController.Post(hpj);
            //test
            mockJobs.Verify(m => m.Add(It.IsAny<Job>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
        /// <summary>
        /// Reads the input from the POST requests and creates the appropriate job instance
        /// </summary>
        /// <param name="type"></param>
        /// <param name="readStream"></param>
        /// <param name="content"></param>
        /// <param name="formatterLogger"></param>
        /// <returns></returns>
        public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (content == null)
                return null;

            var tempStorage = Path.GetTempPath();
            var tempStorageProvider = new MultipartFormDataStreamProvider(tempStorage);
            var msp = await content.ReadAsMultipartAsync(tempStorageProvider);
            Job job = null;

            if (type == typeof(AccessibleConversionJob))
            {
                job = new AccessibleConversionJob
                {
                    //SourceDocumnetFormat = (SourceFormat)Enum.Parse(typeof(SourceFormat), msp.FormData["sourceformat"]),//Convert.ToInt32(msp.FormData["sourceformat"]),
                    TargetDocumentFormat = (OutputFileFormatEnum)Enum.Parse(typeof(OutputFileFormatEnum), msp.FormData["targetdocumentformat"])//Convert.ToInt32(msp.FormData["targetformat"]),
                };

                if (msp.FormData.AllKeys.Contains("priority"))
                {
                    ((AccessibleConversionJob)job).Priority = (PriorityEnum)Enum.Parse(typeof(PriorityEnum), msp.FormData["priority"]);
                }
                else
                {
                    ((AccessibleConversionJob)job).Priority = PriorityEnum.P_Normal;
                }
            }
            else if (type == typeof(AudioJob))
            {
                job = new AudioJob()
                {
                    AudioLanguage = (Language)Enum.Parse(typeof(Language), msp.FormData["audiolanguage"]),
                    SpeedOptions = (AudioSpeed)Enum.Parse(typeof(AudioSpeed), msp.FormData["speedoptions"]),
                    FormatOptions = (AudioFormat)Enum.Parse(typeof(AudioFormat), msp.FormData["formatoptions"])
                };
                if (msp.FormData.AllKeys.Contains("voicepropriety"))
                {
                    string[] props = msp.FormData["voicepropriety"].Split(':');
                    List<VoicePropriety> propList = new List<VoicePropriety>();
                    foreach (string prop in props)
                    {
                        propList.Add((VoicePropriety)Enum.Parse(typeof(VoicePropriety), prop));
                    }
                    ((AudioJob)job).VoicePropriety = propList;
                }
                else ((AudioJob)job).VoicePropriety = new List<VoicePropriety>() { VoicePropriety.None };
            }
            else if (type == typeof(BrailleJob))
            {
                job = new BrailleJob
                {
                    BrailleFormat = (BrailleFormat)Enum.Parse(typeof(BrailleFormat), msp.FormData["brailleformat"]),
                    BrailleLanguage = (Language)Enum.Parse(typeof(Language), msp.FormData["language"]),
                    Contraction = (BrailleContraction)Enum.Parse(typeof(BrailleContraction), msp.FormData["contraction"]),
                    OutputFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), msp.FormData["outputformat"]),
                    ConversionPath = (ConversionPath)int.Parse(msp.FormData["conversionpath"]),
                    CharactersPerLine = int.Parse(msp.FormData["charactersperline"]),
                    LinesPerPage = int.Parse(msp.FormData["linesperpage"])
                };

                if (msp.FormData.AllKeys.Contains("pagenumbering"))
                {
                    ((BrailleJob)job).PageNumbering = (PageNumbering)int.Parse(msp.FormData["pagenumbering"]);
                }
                if (msp.FormData.AllKeys.Contains("translationtable"))
                {
                    ((BrailleJob)job).TranslationTable = msp.FormData["translationtable"];
                }
            }
            else if (type == typeof(DaisyJob))
            {
                job = new DaisyJob
                {
                    DaisyOutput = (DaisyOutput)Enum.Parse(typeof(DaisyOutput), msp.FormData["daisyoutput"])
                };
            }
            else if (type == typeof(EBookJob))
            {
                job = new EBookJob
                {
                    EbookFormat = (EbookFormat)Enum.Parse(typeof(EbookFormat), msp.FormData["format"])
                };
            }
            else if (type == typeof(HTMLtoPDFJob))
            {
                job = new HTMLtoPDFJob
                {
                    paperSize = (PaperSize)Enum.Parse(typeof(PaperSize), msp.FormData["size"])
                };
            }
            else if (type == typeof(MSOfficeJob))
            {
                job = new MSOfficeJob
                {
                    MSOfficeOutput = (MSOfficeOutput)Enum.Parse(typeof(MSOfficeOutput), msp.FormData["msofficeoutput"])
                };
            }
            else if (type == typeof(OcrConversionJob))
            {
                job = new OcrConversionJob
                {
                    OcrLanguage = (Language)Enum.Parse(typeof(Language), msp.FormData["language"])
                };
            }
            else if (type == typeof(HTMLToTextJob))
            {
                job = new HTMLToTextJob();
            }
            else if (type == typeof(RoboVideo.VideoJob))
            {
                job = new RoboVideo.VideoJob()
                {
                    SubtitleLangauge = msp.FormData["language"],
                    SubtitleFormat = msp.FormData["format"]
                };
                if (msp.FormData.AllKeys.Contains("videourl"))
                {
                    ((RoboVideo.VideoJob)job).VideoUrl = msp.FormData["videourl"];
                }
            }
            else //if (type == typeof(TranslationJob))
            {
                job = new TranslationJob()
                {
                    SourceLanguage = msp.FormData["sourcelanguage"],
                    TargetLanguage = msp.FormData["targetlanguage"]
                };
            }

            if (job == null)
            {
                Console.WriteLine("cum pula mea");
                return null;
            }
            else
            {
                if (msp.FileData.Count > 0)
                {
                    job.FileContent = File.ReadAllBytes(msp.FileData[0].LocalFileName);
                    string fileName = msp.FileData[0].Headers.ContentDisposition.FileName.Replace("\"", "").ToString();
                    job.FileName = fileName.Substring(0, fileName.LastIndexOf("."));
                    job.FileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
                    job.MimeType = msp.FileData[0].Headers.ContentType.MediaType;
                }
                else if (msp.FormData["lastjobid"] != null)
                {
                    //1) check if a guid is present and exists in the database. 2) get the byte content from the database and use it in the new job
                    Guid previousJobId = Guid.Parse(msp.FormData["lastjobid"]);
                    RoboBrailleDataContext _context = new RoboBrailleDataContext();
                    Job previousJob = RoboBrailleProcessor.CheckForJobInDatabase(previousJobId, _context);
                    if (previousJob != null)
                    {
                        job.FileContent = previousJob.ResultContent;
                        job.FileName = previousJob.FileName;
                        job.FileExtension = previousJob.ResultFileExtension;
                        job.MimeType = previousJob.ResultMimeType;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    //if not assume it is a URL
                    if (!String.IsNullOrWhiteSpace(msp.FormData["FileContent"]))
                    {
                        string sorh = msp.FormData["FileContent"];
                        Uri uriResult;
                        bool result = Uri.TryCreate(sorh, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                        if (result)
                        {
                            var webRequest = WebRequest.Create(uriResult);

                            using (var response = webRequest.GetResponse())
                            using (var httpcontent = response.GetResponseStream())
                            using (var reader = new StreamReader(httpcontent))
                            {
                                job.FileContent = Encoding.UTF8.GetBytes(reader.ReadToEnd());
                                job.FileName = DateTime.Now.Ticks + "-RoboFile";
                                job.FileExtension = ".html";
                                job.MimeType = "text/html";
                            }
                        }
                        else //else it must be a file
                        {
                            job.FileContent = Encoding.UTF8.GetBytes(sorh);
                            job.FileName = DateTime.Now.Ticks + "-RoboFile";
                            job.FileExtension = ".txt";
                            job.MimeType = "text/plain";
                        }
                    }
                    else
                    {
                        //it's a video job
                    }
                }
                if (type != typeof(RoboVideo.VideoJob))
                {
                    job.InputFileHash = RoboBrailleProcessor.GetInputFileHash(job.FileContent);
                }
                job.Status = JobStatus.Started;
                job.SubmitTime = DateTime.UtcNow.Date;
                return job;
            }
        }