コード例 #1
0
 public OcrConversionRepository(RoboBrailleDataContext context)
 {
     _context       = context;
     supportedLangs = new Dictionary <Language, string>();
     supportedLangs.Add(Language.enUS, "eng");
     supportedLangs.Add(Language.daDK, "dan");
 }
コード例 #2
0
        public FileResult GetResultContents(Guid jobId)
        {
            if (jobId.Equals(Guid.Empty))
            {
                return(null);
            }

            using (var context = new RoboBrailleDataContext())
            {
                var job = context.Jobs.FirstOrDefault(e => jobId.Equals(e.Id));
                if (job == null || job.ResultContent == null)
                {
                    return(null);
                }
                RoboBrailleProcessor.UpdateDownloadCounterInDb(job.Id, _context);
                FileResult result = null;
                try
                {
                    result = new FileResult(job.ResultContent, job.ResultMimeType, job.FileName + job.ResultFileExtension);
                }
                catch (Exception)
                {
                    // ignored
                }
                return(result);
            }
        }
コード例 #3
0
 public static Job CheckForJobInDatabase(Guid jobId, RoboBrailleDataContext context)
 {
     //using (var context = new RoboBrailleDataContext())
     //{
     try
     {
         Job existingJob = context.Jobs.Find(jobId);
         if (existingJob != null)
         {
             if (existingJob.Status.Equals(JobStatus.Done))
             {
                 return(existingJob);
             }
             else
             {
                 return(null);
             }
         }
         else
         {
             return(null);
         }
     }
     catch (Exception)
     {
         // ignored
         return(null);
     }
     //}
 }
コード例 #4
0
 public static void UpdateDownloadCounterInDb(Guid jobId, RoboBrailleDataContext context)
 {
     var task = Task.Factory.StartNew(j =>
     {
         //using (var context = new RoboBrailleDataContext())
         //{
         try
         {
             Job job = context.Jobs.Find(jobId);
             if (job != null)
             {
                 if (job.Status.Equals(JobStatus.Done))
                 {
                     job.DownloadCounter = job.DownloadCounter + 1;
                     context.Jobs.Attach(job);
                     context.Entry(job).State = EntityState.Modified;
                     context.SaveChanges();
                 }
             }
         }
         catch (Exception e)
         {
             // ignored
         }
         //}
     }, jobId);
 }
コード例 #5
0
 public static void UpdateDownloadCounterInDb(Guid jobId,RoboBrailleDataContext context)
 {
     var task = Task.Factory.StartNew(j =>
     {
         //using (var context = new RoboBrailleDataContext())
         //{
             try
             {
                 Job job = context.Jobs.Find(jobId);
                 if (job != null)
                     if (job.Status.Equals(JobStatus.Done))
                     {
                         job.DownloadCounter = job.DownloadCounter + 1;
                         context.Jobs.Attach(job);
                         context.Entry(job).State = EntityState.Modified;
                         context.SaveChanges();
                     }
             }
             catch (Exception)
             {
                 // ignored
             }
         //}
     }, jobId);
 }
コード例 #6
0
 public static bool IsSameJobProcessing(Job job,RoboBrailleDataContext context)
 {
     byte[] fileHash = null;
     using (var md5 = MD5.Create())
     {
         fileHash = md5.ComputeHash(job.FileContent);
     }
     //using (var context = new RoboBrailleDataContext())
     //{
         List<Job> sameJobs = (from j in context.Jobs where j.Status==JobStatus.Started && j.FileName==job.FileName && j.MimeType==job.MimeType && j.FileExtension==job.FileExtension && j.InputFileHash==fileHash select j).ToList();
         if (sameJobs.Count > 0)
             return true;
         else return false;
     //}
 }
コード例 #7
0
        public int GetWorkStatus(Guid jobId)
        {
            if (jobId.Equals(Guid.Empty))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            using (var context = new RoboBrailleDataContext())
            {
                var job = context.Jobs.FirstOrDefault(e => jobId.Equals(e.Id));
                if (job != null)
                {
                    return((int)job.Status);
                }
            }
            return((int)JobStatus.Error);
        }
コード例 #8
0
 public static void SetJobFaulted(Job job, RoboBrailleDataContext context)
 {
     //using (var context = new RoboBrailleDataContext())
     //{
     try
     {
         job.Status     = JobStatus.Error;
         job.FinishTime = DateTime.Now;
         context.Jobs.Attach(job);
         context.Entry(job).State = EntityState.Modified;
         context.SaveChanges();
         WriteMessageToLog("Job Faulted: " + job.FileName + " ID: " + job.Id + " UserID: " + job.UserId);
     }
     catch (Exception)
     {
         // ignored
     }
     //}
 }
コード例 #9
0
        public async Task <Guid> SubmitWorkItem(GenericJob job)
        {
            try
            {
                using (var context = new RoboBrailleDataContext())
                {
                    context.Jobs.Add(job);
                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException ex)
            {
                string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
                throw new DbEntityValidationException(errorMessages);
            }

            var task = Task.Factory.StartNew(t =>
            {
                try
                {
                    //TODO process the job here
                    Task.Delay(10000);

                    job.ResultContent       = Encoding.UTF8.GetBytes("This is a sample job that ran for 10 seconds.");
                    job.ResultFileExtension = "txt";
                    job.ResultMimeType      = "text/plain";
                    job.DownloadCounter     = 0;
                    job.Status                = JobStatus.Done;
                    job.FinishTime            = DateTime.Now;
                    _context.Entry(job).State = EntityState.Modified;
                    _context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message);
                    RoboBrailleProcessor.SetJobFaulted(job, _context);
                    throw ex;
                }
            }, job);

            //info: add "await task;" here to make it run synced
            return(job.Id);
        }
コード例 #10
0
        internal async static Task <Guid> DeleteJobFromDb(Guid jobId, Guid userId, RoboBrailleDataContext context)
        {
            var task = Task.Factory.StartNew(j =>
            {
                try
                {
                    Job job = context.Jobs.Find(jobId);
                    if (job != null && job.UserId.ToString().Equals(userId.ToString()))
                    {
                        context.Jobs.Remove(job);
                        context.Entry(job).State = EntityState.Deleted;
                        context.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }, jobId);

            return(jobId);
        }
コード例 #11
0
        private static Credential OnCredentialsCallback(string id)
        {
            Guid userId;
            if (!Guid.TryParse(id, out userId))
                return null;

            using (var context = new RoboBrailleDataContext())
            {
                var user = context.ServiceUsers.FirstOrDefault(e => e.UserId.Equals(userId));
                if (user != null)
                {
                    return new Credential()
                    {
                        Id = id,
                        User = user.UserName,
                        Algorithm = SupportedAlgorithms.SHA256,
                        Key = user.ApiKey
                    };
                }
            }

            return null;
        }
コード例 #12
0
        public static bool IsSameJobProcessing(Job job, RoboBrailleDataContext context)
        {
            byte[] fileHash = null;
            using (var md5 = MD5.Create())
            {
                fileHash = md5.ComputeHash(job.FileContent);
            }
            //09.02.2017 added also check for user id

            //using (var context = new RoboBrailleDataContext())
            //{
            List <Job> sameJobs = (from j in context.Jobs where j.UserId == job.UserId && j.Status == JobStatus.Started && j.FileName == job.FileName && j.MimeType == job.MimeType && j.FileExtension == job.FileExtension && j.InputFileHash == fileHash select j).ToList();

            if (sameJobs.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
            //}
        }
コード例 #13
0
        private static Credential CredentialsCallback(string id)
        {
            string dbid     = "d2b97532-e8c5-e411-8270-f0def103cfd0";
            string userName = "******";

            byte[] dbKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd");
            try
            {
                Guid guid = Guid.Parse(id);
                using (var context = new RoboBrailleDataContext())
                {
                    var user = context.ServiceUsers.FirstOrDefault(e => e.UserId.Equals(guid));
                    if (user != null)
                    {
                        if (user.ToDate >= DateTime.UtcNow || user.ToDate.Equals(user.FromDate))
                        {
                            dbid     = user.UserId.ToString().ToLower().Trim();
                            userName = user.UserName.Trim();
                            dbKey    = user.ApiKey;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }
            Credential credential = new Credential()
            {
                Id        = dbid,
                Algorithm = SupportedAlgorithms.SHA256,
                User      = userName,
                Key       = dbKey
            };

            return(credential);
        }
コード例 #14
0
 public HTMLToTextRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #15
0
 public HTMLToTextRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #16
0
 public TranslationRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #17
0
 public MSOfficeRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #18
0
        public async System.Threading.Tasks.Task <Guid> SubmitWorkItem(DocumentStructureJob job)
        {
            try
            {
                using (var context = new RoboBrailleDataContext())
                {
                    context.Jobs.Add(job);
                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException ex)
            {
                string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
                throw new DbEntityValidationException(errorMessages);
            }

            var task = Task.Factory.StartNew(t =>
            {
                bool success = true;
                try
                {
                    /*
                     * TODO process the job here
                     * if at any point it fails change the success flag to false (success=false)
                     */

                    //get the document
                    byte[] sourceDocument = job.FileContent;

                    //submit to structure recognition engine/service/library
                    Tuple <DocumentElement, string>[] elements = MockRecognizeStructure(sourceDocument);

                    //get result and save to database
                    string result = null;
                    foreach (Tuple <DocumentElement, string> tuple in elements)
                    {
                        result += tuple.Item1.ToString() + " = " + tuple.Item2 + Environment.NewLine;
                    }
                    job.ResultContent = Encoding.UTF8.GetBytes(result);
                    using (var context = new RoboBrailleDataContext())
                    {
                        job.Status               = JobStatus.Done;
                        job.FinishTime           = DateTime.Now;
                        context.Entry(job).State = EntityState.Modified;
                        context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    Trace.WriteLine(ex.Message);
                }

                if (!success)
                {
                    try
                    {
                        using (var context = new RoboBrailleDataContext())
                        {
                            job.Status               = JobStatus.Error;
                            job.FinishTime           = DateTime.UtcNow;
                            context.Entry(job).State = EntityState.Modified;
                            context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.Message);
                    }
                }
            }, job);

            return(job.Id);
        }
コード例 #19
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
                {
                    //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;
            }
        }
コード例 #20
0
 public SignLanguageRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #21
0
 public static Job CheckForJobInDatabase(Guid jobId,RoboBrailleDataContext context)
 {
     //using (var context = new RoboBrailleDataContext())
     //{
         try
         {
             Job existingJob = context.Jobs.Find(jobId);
             if (existingJob != null)
                 if (existingJob.Status.Equals(JobStatus.Done))
                     return existingJob;
                 else return null;
             else return null;
         }
         catch (Exception)
         {
             // ignored
             return null;
         }
     //}
 }
コード例 #22
0
 public AudioRepository(RoboBrailleDataContext context, IAudioJobSender auSender)
 {
     _context  = context;
     _auSender = auSender;
 }
コード例 #23
0
 public AmaraSubtitleRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #24
0
 public AmaraSubtitleRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #25
0
 public RoboBrailleJobRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #26
0
 public DaisyRepository()
 {
     _context   = new RoboBrailleDataContext();
     _daisyCall = new DaisyRpcCall();
 }
コード例 #27
0
 public RoboBrailleJobRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #28
0
 public DaisyRepository(RoboBrailleDataContext context, IDaisyRpcCall daisyCall)
 {
     _context   = context;
     _daisyCall = daisyCall;
 }
コード例 #29
0
 public MSOfficeRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #30
0
 public GenericJobRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #31
0
 public static void SetJobFaulted(Job job,RoboBrailleDataContext context)
 {
     //using (var context = new RoboBrailleDataContext())
     //{
         try
         {
             job.Status = JobStatus.Error;
             context.Jobs.Attach(job);
             context.Entry(job).State = EntityState.Modified;
             context.SaveChanges();
         }
         catch (Exception)
         {
             // ignored
         }
     //}
 }
コード例 #32
0
 public AudioRepository()
 {
     _context  = new RoboBrailleDataContext();
     _auSender = new AudioJobSender();
 }
コード例 #33
0
 public HTMLtoPDFRepository()
 {
     _context = new RoboBrailleDataContext();
 }
コード例 #34
0
 public TranslationRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }
コード例 #35
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);
            }
        }
コード例 #36
0
 public HTMLtoPDFRepository(RoboBrailleDataContext context)
 {
     _context = context;
 }