public async Task<IHttpActionResult> Post(MSOfficeJob 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"));
 }
        public byte[] ProcessPPTXWithVideo(string source, MSOfficeJob job)
        {
            var guid = job.Id.ToString();

            byte[] result        = null;
            var    tempDirectory = Path.Combine(Path.GetTempPath(), guid);
            var    tempZipFile   = Path.Combine(Path.GetTempPath(), guid + ".zip");

            try
            {
                Directory.CreateDirectory(tempDirectory);
                string text = "";
                foreach (KeyValuePair <int, string> val in ProcessVideoParts(source, job, tempDirectory).Result)
                {
                    text = text + val.Value + Environment.NewLine;
                }

                File.WriteAllText(Path.Combine(tempDirectory, job.FileName + ".txt"), text);

                ZipFile.CreateFromDirectory(tempDirectory, tempZipFile);
                result = File.ReadAllBytes(tempZipFile);
            }
            catch (Exception e)
            {
                result = null;
            }
            finally
            {
                if (Directory.Exists(tempDirectory))
                {
                    Directory.Delete(tempDirectory, true);
                }
                if (File.Exists(tempZipFile))
                {
                    File.Delete(tempZipFile);
                }
            }
            return(result);
        }
示例#3
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 TestPostMSOfficeConversion()
        {
            //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();

            MSOfficeJob moj = new MSOfficeJob()
            {
                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],
                MSOfficeOutput = MSOfficeOutput.txt
            };
            MSOfficeJob moj2 = new MSOfficeJob()
            {
                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<MSOfficeJob> { moj2 }.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);
            
            //TODO refine the call to various libs to be more similar

            //TODO look at the code coverage to cover more code
            //TODO Test and call all possible paths through code mock the interfaces to various libs (not necessarily that important)
            var repo = new MSOfficeRepository(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 MSOfficeConversionController(repo);
            serviceController.Request = request;
            //call
            await serviceController.Post(moj);
            //test
            mockJobs.Verify(m => m.Add(It.IsAny<Job>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
        public static byte[] ProcessDocument(string source, MSOfficeJob job)
        {
            var guid = job.Id.ToString();

            byte[] result = null;
            if (job.MSOfficeOutput.Equals(MSOfficeOutput.html))
            {
                var tempDirectory = Path.Combine(Path.GetTempPath(), guid);
                var tempZipFile   = Path.Combine(Path.GetTempPath(), guid + ".zip");
                try
                {
                    Application app = new Application();
                    app.DisplayAlerts = PpAlertLevel.ppAlertsNone;
                    var pres = app.Presentations.Open(source, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                    pres.SaveCopyAs(tempDirectory, PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoCTrue);
                    pres.Close();
                    app.Quit();
                    app = null;

                    ZipFile.CreateFromDirectory(tempDirectory, tempZipFile);
                    result = File.ReadAllBytes(tempZipFile);
                }
                catch (Exception e)
                {
                    //an exception is thrown if the powerpoint version is too new and does not support save as HTML
                    //instead use spire presentation
                    var tempFile = Path.Combine(Path.GetTempPath(), guid + ".html");
                    SavePPtxAsHtml(source, tempFile);
                    result = File.ReadAllBytes(tempFile);
                    if (File.Exists(tempFile))
                    {
                        File.Delete(tempFile);
                    }
                }
                finally
                {
                    if (Directory.Exists(tempDirectory))
                    {
                        Directory.Delete(tempDirectory, true);
                    }
                    if (File.Exists(tempZipFile))
                    {
                        File.Delete(tempZipFile);
                    }
                }
            }
            else if (job.MSOfficeOutput.Equals(MSOfficeOutput.rtf))
            {
                var tempFile = Path.Combine(Path.GetTempPath(), guid + ".rtf");
                try
                {
                    Application app = new Application();
                    app.DisplayAlerts = PpAlertLevel.ppAlertsNone;
                    var pres = app.Presentations.Open(source, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                    pres.SaveCopyAs(tempFile, PpSaveAsFileType.ppSaveAsRTF, MsoTriState.msoCTrue);
                    pres.Close();
                    app.Quit();
                    app    = null;
                    result = File.ReadAllBytes(tempFile);
                }
                catch (Exception e)
                {
                    Trace.WriteLine(e.Message);
                }
                finally
                {
                    if (File.Exists(tempFile))
                    {
                        File.Delete(tempFile);
                    }
                }
            }
            else if (job.MSOfficeOutput.Equals(MSOfficeOutput.txt))
            {
                string text = "";
                foreach (KeyValuePair <int, string> val in ExtractText(source))
                {
                    text = text + val.Value + Environment.NewLine;
                }
                result = Encoding.UTF8.GetBytes(text);
            }
            return(result);
        }
        /// <summary>
        /// Consider two output types:
        /// .txt if pptx doesn't contain videos
        /// .zip if it contains videos (a .txt file + the video files)
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public async Task <Dictionary <int, string> > ProcessVideoParts(string source, MSOfficeJob job, string tempDirectory)
        {
            Dictionary <int, string> TextContent = new Dictionary <int, string>();
            int index = 1;

            using (PresentationDocument ppt = PresentationDocument.Open(source, false))
            {
                // Get the relationship ID of the first slide.
                PresentationPart   part     = ppt.PresentationPart;
                OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements;
                foreach (SlideId slideID in slideIds)
                {
                    //get the right content according to type. for now only text is getting through
                    string relId = slideID.RelationshipId;

                    // Get the slide part from the relationship ID.
                    SlidePart slide = (SlidePart)part.GetPartById(relId);

                    //extract the videos and put placeholders
                    IEnumerable <A.VideoFromFile> videos = slide.Slide.Descendants <A.VideoFromFile>();
                    foreach (A.VideoFromFile vid in videos)
                    {
                        string videoRelId         = vid.Link;
                        ReferenceRelationship rel = slide.GetReferenceRelationship(videoRelId);
                        Uri    uri        = rel.Uri;
                        var    filename   = uri.ToString().Split('/').Last();
                        var    s          = ppt.Package.GetPart(uri).GetStream();
                        byte[] videoBytes = null;
                        using (BinaryReader br = new BinaryReader(s))
                        {
                            videoBytes = br.ReadBytes((int)s.Length);
                        }
                        //write video to result directory
                        File.WriteAllBytes(Path.Combine(tempDirectory, filename), videoBytes);

                        //send to amara
                        string langauge = "en-us";
                        if (ppt.PackageProperties.Language != null)
                        {
                            langauge = ppt.PackageProperties.Language;
                        }

                        AmaraSubtitleJob vj = new AmaraSubtitleJob()
                        {
                            SubmitTime       = DateTime.Now,
                            FinishTime       = DateTime.Now,
                            Status           = JobStatus.Started,
                            MimeType         = "video/" + filename.Substring(filename.LastIndexOf('.') + 1), //define this properly
                            User             = job.User,
                            UserId           = job.UserId,
                            DownloadCounter  = 0,
                            FileContent      = videoBytes,
                            InputFileHash    = RoboBrailleProcessor.GetMD5Hash(videoBytes),
                            SubtitleFormat   = job.SubtitleFormat,
                            SubtitleLangauge = job.SubtitleLangauge,
                            FileName         = job.Id.ToString() + "-" + filename.Substring(0, filename.LastIndexOf('.')),
                            FileExtension    = filename.Substring(filename.LastIndexOf('.') + 1)
                        };

                        //retrieve the message from amara
                        byte[] filebytes     = null;
                        Guid   subtitleJobId = vcr.SubmitWorkItem(vj).Result;
                        while (vcr.GetWorkStatus(subtitleJobId) == 2)
                        {
                            await Task.Delay(2000);
                        }
                        filebytes = vcr.GetResultContents(subtitleJobId).getFileContents();
                        File.WriteAllBytes(Path.Combine(tempDirectory, filename.Substring(0, filename.LastIndexOf('.')) + vj.ResultFileExtension), filebytes);

                        slide.Slide.CommonSlideData.ShapeTree.AppendChild(
                            new ShapeProperties(
                                new TextBody(
                                    new A.Paragraph(
                                        new A.Run(
                                            new A.Text("Video file name = " + filename + " subtitle attached to video has id: " + vj.Id.ToString())
                                            )))));
                    }


                    // Build a StringBuilder object.
                    StringBuilder paragraphText = new StringBuilder();

                    // Get the inner text of the slide:
                    IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>();
                    foreach (A.Text text in texts)
                    {
                        if (text.Text.Length > 1)
                        {
                            paragraphText.Append(text.Text + " ");
                        }
                        else
                        {
                            paragraphText.Append(text.Text);
                        }
                    }
                    string slideText = paragraphText.ToString();
                    TextContent.Add(index, slideText);
                    index++;
                }
                //until now there are: video files + subtitle files
                //at the end there will be: a txt file + video files + subtitle files (all zipped up)
            }
            return(TextContent);
        }
        /// <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;
            }
        }