public static FileInfo LocalSiteTagListFileInfo(this UserSettings settings, string tag)
        {
            var directory  = settings.LocalSiteTagsDirectory();
            var sluggedTag = SlugUtility.Create(true, tag);

            return(new FileInfo($"{Path.Combine(directory.FullName, $"TagList-{sluggedTag}")}.html"));
        }
        public static async Task <(GenerationReturn, PhotoContent)> PhotoMetadataToNewPhotoContent(FileInfo selectedFile,
                                                                                                   IProgress <string> progress, string photoContentCreatedBy = null)
        {
            selectedFile.Refresh();

            if (!selectedFile.Exists)
            {
                return(await GenerationReturn.Error("File Does Not Exist?"), null);
            }

            var metadataReturn = await PhotoMetadataFromFile(selectedFile, progress);

            if (metadataReturn.generationReturn.HasError)
            {
                return(metadataReturn.generationReturn, null);
            }

            var toReturn = new PhotoContent();

            toReturn.InjectFrom(metadataReturn.metadata);

            toReturn.OriginalFileName = selectedFile.Name;
            toReturn.ContentId        = Guid.NewGuid();
            toReturn.CreatedBy        = string.IsNullOrWhiteSpace(photoContentCreatedBy)
                ? UserSettingsSingleton.CurrentSettings().DefaultCreatedBy
                : photoContentCreatedBy.Trim();
            toReturn.CreatedOn         = DateTime.Now;
            toReturn.Slug              = SlugUtility.Create(true, toReturn.Title);
            toReturn.BodyContentFormat = ContentFormatDefaults.Content.ToString();
            toReturn.UpdateNotesFormat = ContentFormatDefaults.Content.ToString();

            var possibleTitleYear = Regex
                                    .Match(toReturn.Title,
                                           @"\A(?<possibleYear>\d\d\d\d) (?<possibleMonth>January?|February?|March?|April?|May|June?|July?|August?|September?|October?|November?|December?) .*",
                                           RegexOptions.IgnoreCase).Groups["possibleYear"].Value;

            if (!string.IsNullOrWhiteSpace(possibleTitleYear))
            {
                if (int.TryParse(possibleTitleYear, out var convertedYear))
                {
                    if (convertedYear >= 1826 && convertedYear <= DateTime.Now.Year)
                    {
                        toReturn.Folder = convertedYear.ToString("F0");
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(toReturn.Folder))
            {
                toReturn.Folder = toReturn.PhotoCreatedOn.Year.ToString("F0");
            }

            return(await GenerationReturn.Success($"Parsed Photo Metadata for {selectedFile.FullName} without error"),
                   toReturn);
        }
示例#3
0
        private void SetContentDispositionHeader(HttpContentHeaders headers)
        {
            if (this._contentType != "application/pdf")
            {
                return;
            }

            var dispositionType = this._contentDelivery == ContentDelivery.Inline ? "inline" : "attachment";

            var contentDisposition = new ContentDispositionHeaderValue(dispositionType);

            if (!string.IsNullOrWhiteSpace(this._fileName))
            {
                var fileName = $"{SlugUtility.GenerateSlug(Path.GetFileNameWithoutExtension(this._fileName))}{Path.GetExtension(this._fileName)}";

                contentDisposition.FileName = fileName;
            }

            headers.ContentDisposition = contentDisposition;
        }
示例#4
0
        public static async Task <string> UniqueNoteSlug()
        {
            var attemptCount = 1;

            var db = await Db.Context();

            var currentLength = 6;

            if (await db.NoteContents.AnyAsync())
            {
                var dbMaxLength = await db.NoteContents.MaxAsync(x => x.Slug.Length);

                currentLength = dbMaxLength > currentLength ? dbMaxLength : currentLength;
            }

            var possibleSlug = SlugUtility.RandomLowerCaseString(currentLength);

            async Task <bool> SlugAlreadyExists(string slug)
            {
                return(await db.NoteContents.AnyAsync(x => x.Slug == slug));
            }

            while (await SlugAlreadyExists(possibleSlug))
            {
                if (attemptCount > 1000)
                {
                    throw new DataException(
                              "Could not create a unique note slug in 1000 iterations - this almost certainly represents an error.");
                }
                if (attemptCount % 10 == 0)
                {
                    currentLength++;
                }
                attemptCount++;
                possibleSlug = SlugUtility.RandomLowerCaseString(currentLength);
            }

            return(possibleSlug);
        }
示例#5
0
        public static async Task PdfPageToImageWithPdfToCairo(StatusControlContext statusContext,
                                                              List <FileContent> selected, int pageNumber)
        {
            await ThreadSwitcher.ThreadSwitcher.ResumeBackgroundAsync();


            var pdfToCairoDirectoryString = UserSettingsSingleton.CurrentSettings().PdfToCairoExeDirectory;

            if (string.IsNullOrWhiteSpace(pdfToCairoDirectoryString))
            {
                statusContext.ToastError(
                    "Sorry - this function requires that pdftocairo.exe be on the system - please set the directory... ");
                return;
            }

            var pdfToCairoDirectory = new DirectoryInfo(pdfToCairoDirectoryString);

            if (!pdfToCairoDirectory.Exists)
            {
                statusContext.ToastError(
                    $"{pdfToCairoDirectory.FullName} doesn't exist? Check your pdftocairo bin directory setting.");
                return;
            }

            var pdfToCairoExe = new FileInfo(Path.Combine(pdfToCairoDirectory.FullName, "pdftocairo.exe"));

            if (!pdfToCairoExe.Exists)
            {
                statusContext.ToastError(
                    $"{pdfToCairoExe.FullName} doesn't exist? Check your pdftocairo bin directory setting.");
                return;
            }

            var toProcess = new List <(FileInfo targetFile, FileInfo destinationFile, FileContent content)>();

            foreach (var loopSelected in selected)
            {
                var targetFile = new FileInfo(Path.Combine(
                                                  UserSettingsSingleton.CurrentSettings().LocalSiteFileContentDirectory(loopSelected).FullName,
                                                  loopSelected.OriginalFileName));

                if (!targetFile.Exists)
                {
                    continue;
                }

                if (!targetFile.Extension.ToLower().Contains("pdf"))
                {
                    continue;
                }

                FileInfo destinationFile;
                if (pageNumber == 1)
                {
                    destinationFile = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                                $"{Path.GetFileNameWithoutExtension(targetFile.Name)}-CoverPage.jpg"));

                    if (destinationFile.Exists)
                    {
                        destinationFile.Delete();
                        destinationFile.Refresh();
                    }
                }
                else
                {
                    destinationFile = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                                $"{Path.GetFileNameWithoutExtension(targetFile.Name)}-Page.jpg"));
                }

                toProcess.Add((targetFile, destinationFile, loopSelected));
            }

            if (!toProcess.Any())
            {
                statusContext.ToastError("No PDFs found? This process can only generate PDF previews...");
                return;
            }

            foreach (var loopSelected in toProcess)
            {
                if (loopSelected.destinationFile.Directory == null)
                {
                    statusContext.ToastError(
                        $"Problem with {loopSelected.destinationFile.FullName} - Directory is Null?");
                    continue;
                }

                var executionParameters = pageNumber == 1
                    ? $"-jpeg -singlefile \"{loopSelected.targetFile.FullName}\" \"{Path.Combine(loopSelected.destinationFile.Directory.FullName, Path.GetFileNameWithoutExtension(loopSelected.destinationFile.FullName))}\""
                    : $"-jpeg -f {pageNumber} -l {pageNumber} \"{loopSelected.targetFile.FullName}\" \"{Path.Combine(loopSelected.destinationFile.Directory.FullName, Path.GetFileNameWithoutExtension(loopSelected.destinationFile.FullName))}\"";

                var(success, _, errorOutput) = ProcessHelpers.ExecuteProcess(pdfToCairoExe.FullName,
                                                                             executionParameters, statusContext.ProgressTracker());

                if (!success)
                {
                    if (await statusContext.ShowMessage("PDF Generation Problem",
                                                        $"Execution Failed for {loopSelected.content.Title} - Continue??{Environment.NewLine}{errorOutput}",
                                                        new List <string> {
                        "Yes", "No"
                    }) == "No")
                    {
                        return;
                    }

                    continue;
                }

                FileInfo updatedDestination = null;

                if (pageNumber == 1)
                {
                    //With the singlefile option pdftocairo uses your filename directly
                    loopSelected.destinationFile.Refresh();
                    updatedDestination = loopSelected.destinationFile;
                }
                else
                {
                    var directoryToSearch = loopSelected.destinationFile.Directory;

                    var possibleFiles = directoryToSearch
                                        .EnumerateFiles($"{Path.GetFileNameWithoutExtension(loopSelected.destinationFile.Name)}-*.jpg")
                                        .ToList();

                    foreach (var loopFiles in possibleFiles)
                    {
                        var fileNamePageNumber = loopFiles.Name.Split("-Page-").ToList().Last().Replace(".jpg", "");

                        if (int.TryParse(fileNamePageNumber, out var possiblePageNumber) &&
                            possiblePageNumber == pageNumber)
                        {
                            updatedDestination = loopFiles;
                            break;
                        }
                    }
                }

                if (updatedDestination == null || !updatedDestination.Exists)
                {
                    if (await statusContext.ShowMessage("PDF Generation Problem",
                                                        $"Execution Failed for {loopSelected.content.Title} - Continue??{Environment.NewLine}{errorOutput}",
                                                        new List <string> {
                        "Yes", "No"
                    }) == "No")
                    {
                        return;
                    }

                    continue;
                }

                await ThreadSwitcher.ThreadSwitcher.ResumeForegroundAsync();

                var newImage = new ImageContent {
                    ContentId = Guid.NewGuid()
                };

                if (pageNumber == 1)
                {
                    newImage.Title   = $"{loopSelected.content.Title} Cover Page";
                    newImage.Summary = $"Cover Page from {loopSelected.content.Title}.";
                }
                else
                {
                    newImage.Title   = $"{loopSelected.content.Title} - Page {pageNumber}";
                    newImage.Summary = $"Page {pageNumber} from {loopSelected.content.Title}.";
                }

                newImage.ShowInSearch      = false;
                newImage.Folder            = loopSelected.content.Folder;
                newImage.Tags              = loopSelected.content.Tags;
                newImage.Slug              = SlugUtility.Create(true, newImage.Title);
                newImage.BodyContentFormat = ContentFormatDefaults.Content.ToString();
                newImage.BodyContent       = $"Generated by pdftocairo from {BracketCodeFiles.Create(loopSelected.content)}.";
                newImage.UpdateNotesFormat = ContentFormatDefaults.Content.ToString();

                var editor = new ImageContentEditorWindow(newImage, updatedDestination);
                editor.Show();

                await ThreadSwitcher.ThreadSwitcher.ResumeBackgroundAsync();
            }
        }
        public static string TagPageUrl(this UserSettings settings, string tag)
        {
            var sluggedTag = SlugUtility.Create(true, tag);

            return($"//{settings.SiteUrl}/Tags/TagList-{sluggedTag}.html");
        }