public void PhotoHtmlChecks(PhotoContent newPhotoContent)
        {
            var htmlFile = UserSettingsSingleton.CurrentSettings().LocalSitePhotoHtmlFile(newPhotoContent);

            Assert.True(htmlFile.Exists, "Html File not Found for Html Checks?");

            var config = Configuration.Default;

            var context  = BrowsingContext.New(config);
            var parser   = context.GetService <IHtmlParser>();
            var source   = File.ReadAllText(htmlFile.FullName);
            var document = parser.ParseDocument(source);

            Assert.AreEqual(newPhotoContent.Title, document.Title);

            //Todo - check description

            Assert.AreEqual(newPhotoContent.Tags,
                            document.QuerySelector("meta[name='keywords']")?.Attributes
                            .FirstOrDefault(x => x.LocalName == "content")?.Value);

            Assert.AreEqual(UserSettingsSingleton.CurrentSettings().SiteName,
                            document.QuerySelector("meta[property='og:site_name']")?.Attributes
                            .FirstOrDefault(x => x.LocalName == "content")?.Value);

            Assert.AreEqual($"https:{UserSettingsSingleton.CurrentSettings().PhotoPageUrl(newPhotoContent)}",
                            document.QuerySelector("meta[property='og:url']")?.Attributes
                            .FirstOrDefault(x => x.LocalName == "content")?.Value);

            Assert.AreEqual("article",
                            document.QuerySelector("meta[property='og:type']")?.Attributes
                            .FirstOrDefault(x => x.LocalName == "content")?.Value);

            //Todo: Continue checking...
        }
Beispiel #2
0
        public static HtmlTag PhotoDetailsDiv(PhotoContent dbEntry)
        {
            var outerContainer = new DivTag().AddClass("photo-details-container");

            outerContainer.Children.Add(new DivTag().AddClass("photo-detail-label-tag").Text("Details:"));

            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.Aperture, "photo-detail", "aperture",
                                                        dbEntry.Aperture));
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.ShutterSpeed, "photo-detail", "shutter-speed",
                                                        dbEntry.ShutterSpeed));
            //InfoDivTag guards against null and empty but because we put ISO in the string guard against blank (and sanity check) ISO.
            if (dbEntry.Iso != null && dbEntry.Iso.Value > 0)
            {
                outerContainer.Children.Add(Tags.InfoDivTag($"ISO {dbEntry.Iso?.ToString("F0")}", "photo-detail", "iso",
                                                            dbEntry.Iso?.ToString("F0")));
            }
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.Lens, "photo-detail", "lens", dbEntry.Lens));
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.FocalLength, "photo-detail", "focal-length",
                                                        dbEntry.FocalLength));
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.CameraMake, "photo-detail", "camera-make",
                                                        dbEntry.CameraMake));
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.CameraModel, "photo-detail", "camera-model",
                                                        dbEntry.CameraModel));
            outerContainer.Children.Add(Tags.InfoDivTag(dbEntry.License, "photo-detail", "license", dbEntry.License));

            //Return empty if there are no details
            return(outerContainer.Children.Count(x => !x.IsEmpty()) > 1 ? outerContainer : HtmlTag.Empty());
        }
        public void PhotoCheckFileCountAndPictureAssetsAfterHtmlGeneration(PhotoContent newPhotoContent, int photoWidth)
        {
            var contentDirectory = UserSettingsSingleton.CurrentSettings()
                                   .LocalSitePhotoContentDirectory(newPhotoContent, false);

            Assert.True(contentDirectory.Exists, "Content Directory Not Found?");

            var expectedNumberOfFiles = PictureResizing.SrcSetSizeAndQualityList().Count(x => x.size < photoWidth) //
                                        + 1                                                                        //Original image
                                        + 1                                                                        //Display image
                                        + 1                                                                        //HTML file
                                        + 1;                                                                       //json file

            Assert.AreEqual(contentDirectory.GetFiles().Length, expectedNumberOfFiles,
                            "Expected Number of Files Does Not Match");

            var pictureAssetInformation  = PictureAssetProcessing.ProcessPictureDirectory(newPhotoContent.ContentId);
            var pictureAssetPhotoDbEntry = (PhotoContent)pictureAssetInformation.DbEntry;

            Assert.IsTrue(pictureAssetPhotoDbEntry.ContentId == newPhotoContent.ContentId,
                          $"Picture Asset appears to have gotten an incorrect DB entry of {pictureAssetPhotoDbEntry.ContentId} rather than {newPhotoContent.ContentId}");

            var maxSize = PictureResizing.SrcSetSizeAndQualityList().Where(x => x.size < photoWidth).Max();
            var minSize = PictureResizing.SrcSetSizeAndQualityList().Min();

            Assert.AreEqual(pictureAssetInformation.LargePicture.Width, maxSize.size,
                            $"Picture Asset Large Width is not the expected Value - Expected {maxSize}, Actual {pictureAssetInformation.LargePicture.Width}");
            Assert.AreEqual(pictureAssetInformation.SmallPicture.Width,
                            PictureResizing.SrcSetSizeAndQualityList().Min().size,
                            $"Picture Asset Small Width is not the expected Value - Expected {minSize}, Actual {pictureAssetInformation.SmallPicture.Width}");

            Assert.AreEqual(pictureAssetInformation.SrcsetImages.Count,
                            PictureResizing.SrcSetSizeAndQualityList().Count(x => x.size < photoWidth),
                            "Did not find the expected number of SrcSet Images");
        }
        public static async Task <(GenerationReturn generationReturn, PhotoContent photoContent)> SaveAndGenerateHtml(
            PhotoContent toSave, FileInfo selectedFile, bool overwriteExistingFiles, DateTime?generationVersion,
            IProgress <string> progress)
        {
            var validationReturn = await Validate(toSave, selectedFile);

            if (validationReturn.HasError)
            {
                return(validationReturn, null);
            }

            Db.DefaultPropertyCleanup(toSave);
            toSave.Tags = Db.TagListCleanup(toSave.Tags);

            FileManagement.WriteSelectedPhotoContentFileToMediaArchive(selectedFile);
            await Db.SavePhotoContent(toSave);

            await WritePhotoFromMediaArchiveToLocalSite(toSave, overwriteExistingFiles, progress);

            GenerateHtml(toSave, generationVersion, progress);
            await Export.WriteLocalDbJson(toSave);

            DataNotifications.PublishDataNotification("Photo Generator", DataNotificationContentType.Photo,
                                                      DataNotificationUpdateType.LocalContent, new List <Guid> {
                toSave.ContentId
            });

            return(await GenerationReturn.Success($"Saved and Generated Content And Html for {toSave.Title}"), toSave);
        }
        /// <summary>
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public static async Task <GenerationReturn> CopyCleanResizePhoto(PhotoContent dbEntry,
                                                                         IProgress <string> progress)
        {
            if (dbEntry == null)
            {
                return(await GenerationReturn.Error("Null Photo Content submitted to Copy Clean and Resize"));
            }

            progress?.Report($"Starting Copy, Clean and Resize for {dbEntry.Title}");

            if (string.IsNullOrWhiteSpace(dbEntry.OriginalFileName))
            {
                return(await GenerationReturn.Error($"Photo {dbEntry.Title} has no Original File", dbEntry.ContentId));
            }

            var photoDirectory = UserSettingsSingleton.CurrentSettings().LocalSitePhotoContentDirectory(dbEntry);

            var syncCopyResults = await FileManagement.CheckPhotoFileIsInMediaAndContentDirectories(dbEntry, progress);

            if (!syncCopyResults.HasError)
            {
                return(syncCopyResults);
            }

            CleanDisplayAndSrcSetFilesInPhotoDirectory(dbEntry, true, progress);

            ResizeForDisplayAndSrcset(new FileInfo(Path.Combine(photoDirectory.FullName, dbEntry.OriginalFileName)),
                                      false, progress);

            return(await GenerationReturn.Success($"{dbEntry.Title} Copied, Cleaned, Resized", dbEntry.ContentId));
        }
        public static PictureAsset ProcessPhotoDirectory(PhotoContent dbEntry)
        {
            var settings         = UserSettingsSingleton.CurrentSettings();
            var contentDirectory = settings.LocalSitePhotoContentDirectory(dbEntry);

            return(ProcessPhotoDirectory(dbEntry, contentDirectory, settings.SiteUrl));
        }
Beispiel #7
0
        private FrameworkElement ProcessPhoto(PageBlockPhoto block)
        {
            var galleryItem = new GalleryPhotoItem(ViewModel.ProtoService, block.Photo, block.Caption?.ToString());

            ViewModel.Gallery.Items.Add(galleryItem);

            var message = GetMessage(new MessagePhoto(block.Photo, null));
            var element = new StackPanel {
                Tag = message, Style = Resources["BlockPhotoStyle"] as Style
            };

            foreach (var size in block.Photo.Sizes)
            {
                _filesMap[size.Photo.Id].Add(element);
            }

            var content = new PhotoContent(message);

            content.HorizontalAlignment = HorizontalAlignment.Center;
            content.ClearValue(MaxWidthProperty);
            content.ClearValue(MaxHeightProperty);

            element.Children.Add(content);

            var caption = ProcessText(block, true);

            if (caption != null)
            {
                caption.Margin = new Thickness(0, 8, 0, 0);
                element.Children.Add(caption);
            }

            return(element);
        }
        /// <summary>
        ///     This deletes Photo Directory jpeg files that match this programs generated sizing naming conventions. If deleteAll
        ///     is true then all
        ///     files will be deleted - otherwise only files where the width does not match one of the generated widths will be
        ///     deleted.
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <param name="deleteAll"></param>
        /// <param name="progress"></param>
        public static void CleanDisplayAndSrcSetFilesInPhotoDirectory(PhotoContent dbEntry, bool deleteAll,
                                                                      IProgress <string> progress)
        {
            var currentSizes = SrcSetSizeAndQualityList().Select(x => x.size).ToList();

            progress?.Report($"Starting SrcSet Photo Cleaning... Current Size List {string.Join(", ", currentSizes)}");

            var currentFiles = PictureAssetProcessing.ProcessPhotoDirectory(dbEntry);

            foreach (var loopFiles in currentFiles.SrcsetImages)
            {
                if (!currentSizes.Contains(loopFiles.Width) || deleteAll)
                {
                    progress?.Report($"  Deleting {loopFiles.FileName}");
                    loopFiles.File.Delete();
                }
            }

            var sourceFileReference =
                UserSettingsSingleton.CurrentSettings().LocalMediaArchivePhotoContentFile(dbEntry);
            var expectedDisplayWidth = DisplayPictureWidth(sourceFileReference, progress);

            if (currentFiles.DisplayPicture != null && currentFiles.DisplayPicture.Width != expectedDisplayWidth ||
                deleteAll)
            {
                currentFiles.DisplayPicture?.File?.Delete();
            }
        }
        public static async Task WritePhotoFromMediaArchiveToLocalSite(PhotoContent photoContent,
                                                                       bool forcedResizeOverwriteExistingFiles, IProgress <string> progress)
        {
            var userSettings = UserSettingsSingleton.CurrentSettings();

            var sourceFile = new FileInfo(Path.Combine(userSettings.LocalMediaArchivePhotoDirectory().FullName,
                                                       photoContent.OriginalFileName));

            var targetFile = new FileInfo(Path.Combine(
                                              userSettings.LocalSitePhotoContentDirectory(photoContent).FullName, photoContent.OriginalFileName));

            if (targetFile.Exists && forcedResizeOverwriteExistingFiles)
            {
                targetFile.Delete();
                targetFile.Refresh();
            }

            if (!targetFile.Exists)
            {
                await sourceFile.CopyToAndLogAsync(targetFile.FullName);
            }

            PictureResizing.DeleteSupportedPictureFilesInDirectoryOtherThanOriginalFile(photoContent, progress);

            PictureResizing.CleanDisplayAndSrcSetFilesInPhotoDirectory(photoContent, forcedResizeOverwriteExistingFiles,
                                                                       progress);

            await PictureResizing.ResizeForDisplayAndSrcset(photoContent, forcedResizeOverwriteExistingFiles, progress);
        }
Beispiel #10
0
        public HtmlTag PhotoFigureTag(PhotoContent dbEntry, string sizes)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-photo-container");

            figureTag.Children.Add(Tags.PictureImgTag(Pictures, sizes, true));
            return(figureTag);
        }
Beispiel #11
0
        public IActionResult UpdateThumbnail(int fishId, [FromBody] PhotoContent photo)
        {
            try
            {
                //Access level
                var id     = _accountService.GetCurrentUserId();
                var fish   = _fishService.GetFishById(fishId);
                var access = _accountService.CanModify(id, fish);
                if (!access)
                {
                    return(Unauthorized());
                }
                //todo check if user has access to this photo

                _logger.LogInformation("POST /v1/Fish/{fishId}/UpdateThumbnail called");
                fish.ThumbnailPhotoId = photo.Id;
                fish = _aquariumService.UpdateFish(fish);
                return(new OkObjectResult(fish));
            }
            catch (Exception ex)
            {
                _logger.LogError($"POST /v1/Fish/{fishId}/UpdateThumbnail endpoint caught exception: { ex.Message } Details: { ex.ToString() }");
                return(NotFound());
            }
        }
Beispiel #12
0
        private HtmlTag LocalPhotoFigureTag(PhotoContent dbEntry)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-photo-container");

            figureTag.Children.Add(LocalDisplayPhotoImageTag());
            figureTag.Children.Add(Tags.PhotoFigCaptionTag(dbEntry));
            return(figureTag);
        }
        public static PictureAsset ProcessPhotoDirectory(PhotoContent dbEntry, DirectoryInfo directoryInfo,
                                                         string siteUrl)
        {
            var toReturn = new PictureAsset {
                DbEntry = dbEntry
            };

            var baseFileNameList = dbEntry.OriginalFileName.Split(".").ToList();
            var baseFileName     = string.Join("", baseFileNameList.Take(baseFileNameList.Count - 1));

            var fileVariants = directoryInfo.GetFiles().Where(x => x.Name.StartsWith($"{baseFileName}--")).ToList();

            var displayImageFile = fileVariants.FirstOrDefault(x => x.Name.Contains("--For-Display"));

            if (displayImageFile != null && displayImageFile.Exists)
            {
                toReturn.DisplayPicture = new PictureFile
                {
                    FileName = displayImageFile.Name,
                    SiteUrl  = $@"//{siteUrl}/Photos/{dbEntry.Folder}/{dbEntry.Slug}/{displayImageFile.Name}",
                    File     = displayImageFile,
                    AltText  = dbEntry.AltText ?? string.Empty,
                    Height   =
                        int.Parse(Regex
                                  .Match(displayImageFile.Name, @".*--(?<height>\d*)h.*", RegexOptions.Singleline)
                                  .Groups["height"].Value),
                    Width = int.Parse(Regex
                                      .Match(displayImageFile.Name, @".*--(?<width>\d*)w.*", RegexOptions.Singleline)
                                      .Groups["width"].Value)
                }
            }
            ;

            var srcsetImageFiles = fileVariants.Where(x => x.Name.Contains("--Sized")).ToList();

            toReturn.SrcsetImages = srcsetImageFiles.Select(x => new PictureFile
            {
                FileName = x.Name,
                SiteUrl  = $@"//{siteUrl}/Photos/{dbEntry.Folder}/{dbEntry.Slug}/{x.Name}",
                File     = x,
                AltText  = dbEntry.AltText ?? string.Empty,
                Height   =
                    int.Parse(Regex.Match(x.Name, @".*--(?<height>\d*)h.*", RegexOptions.Singleline)
                              .Groups["height"].Value),
                Width = int.Parse(Regex.Match(x.Name, @".*--(?<width>\d*)w.*", RegexOptions.Singleline)
                                  .Groups["width"].Value)
            }).ToList();

            if (srcsetImageFiles.Any())
            {
                toReturn.LargePicture =
                    toReturn.SrcsetImages.OrderByDescending(x => Math.Max(x.Height, x.Width)).First();
                toReturn.SmallPicture = toReturn.SrcsetImages.OrderBy(x => Math.Max(x.Height, x.Width)).First();
            }

            return(toReturn);
        }
Beispiel #14
0
        public HtmlTag PhotoFigureWithLinkToPageTag(PhotoContent dbEntry, string sizes)
        {
            var figureTag = new HtmlTag("figure").AddClass("single-photo-container");
            var linkTag   = new LinkTag(string.Empty, PageUrl);

            linkTag.Children.Add(Tags.PictureImgTag(Pictures, sizes, true));
            figureTag.Children.Add(linkTag);
            return(figureTag);
        }
        public static void ConfirmOrGeneratePhotoDirectoryAndPictures(PhotoContent dbEntry, IProgress <string> progress)
        {
            StructureAndMediaContent.CheckPhotoFileIsInMediaAndContentDirectories(dbEntry, progress).Wait();

            var targetDirectory = UserSettingsSingleton.CurrentSettings().LocalSitePhotoContentDirectory(dbEntry);

            var sourceImage = new FileInfo(Path.Combine(targetDirectory.FullName, dbEntry.OriginalFileName));

            PictureResizing.ResizeForDisplayAndSrcset(sourceImage, false, null);
        }
        public PhotoContentEditorWindow(PhotoContent toLoad)
        {
            InitializeComponent();

            StatusContext = new StatusControlContext();
            PhotoEditor   = new PhotoContentEditorContext(StatusContext, toLoad);

            DataContext            = this;
            AccidentalCloserHelper = new WindowAccidentalClosureHelper(this, StatusContext, PhotoEditor);
        }
        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);
        }
        public static async Task <List <FileInfo> > ResizeForDisplayAndSrcset(PhotoContent dbEntry,
                                                                              bool overwriteExistingFiles, IProgress <string> progress)
        {
            await FileManagement.CheckPhotoFileIsInMediaAndContentDirectories(dbEntry, progress);

            var targetDirectory = UserSettingsSingleton.CurrentSettings().LocalSitePhotoContentDirectory(dbEntry);

            var sourceImage = new FileInfo(Path.Combine(targetDirectory.FullName, dbEntry.OriginalFileName));

            return(ResizeForDisplayAndSrcset(sourceImage, overwriteExistingFiles, progress));
        }
Beispiel #19
0
 private static string TypeToFilterTag(object content)
 {
     return(content switch
     {
         NoteContent _ => "post",
         PostContent _ => "post",
         ImageContent _ => "image",
         PhotoContent _ => "image",
         FileContent _ => "file",
         LinkStream _ => "link",
         _ => "other"
     });
Beispiel #20
0
        public SinglePhotoDiv(PhotoContent dbEntry)
        {
            DbEntry = dbEntry;

            var settings = UserSettingsSingleton.CurrentSettings();

            SiteUrl  = settings.SiteUrl;
            SiteName = settings.SiteName;
            PageUrl  = settings.PhotoPageUrl(DbEntry);

            PictureInformation = new PictureSiteInformation(DbEntry.ContentId);
        }
        public static void GenerateHtml(PhotoContent toGenerate, DateTime?generationVersion,
                                        IProgress <string> progress)
        {
            progress?.Report($"Photo Content - Generate HTML for {toGenerate.Title}");

            var htmlContext = new SinglePhotoPage(toGenerate)
            {
                GenerationVersion = generationVersion
            };

            htmlContext.WriteLocalHtml();
        }
Beispiel #22
0
        public static async Task <string> ToHtmlEmail(PhotoContent content, IProgress <string> progress)
        {
            if (content == null)
            {
                return(string.Empty);
            }

            var mdBuilder = new StringBuilder();

            mdBuilder.AppendLine(BracketCodePhotos.Create(content));

            var detailsList = new List <string>
            {
                content.Aperture,
                content.ShutterSpeed,
                content.Iso?.ToString("F0"),
                content.Lens,
                content.FocalLength,
                content.CameraMake,
                content.CameraModel,
                content.License
            }.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();

            mdBuilder.AppendLine($"<p style=\"text-align: center;\">Details: {string.Join(", ", detailsList)}</p>");

            var tags = Tags.TagListTextLinkList(content);

            tags.Style("text-align", "center");
            mdBuilder.AppendLine(tags.ToString());

            mdBuilder.AppendLine();

            if (!string.IsNullOrWhiteSpace(content.BodyContent))
            {
                mdBuilder.AppendLine(content.BodyContent);
            }

            mdBuilder.AppendLine();

            mdBuilder.AppendLine($"<p style=\"text-align: center;\">{Tags.CreatedByAndUpdatedOnString(content)}</p>");

            var preprocessResults = BracketCodeCommon.ProcessCodesForEmail(mdBuilder.ToString(), progress);
            var bodyHtmlString    = ContentProcessing.ProcessContent(preprocessResults, content.BodyContentFormat);

            var innerContent = HtmlEmail.ChildrenIntoTableCells(
                $"{await HtmlEmail.EmailSimpleTitle(content)}{bodyHtmlString}{HtmlEmail.EmailSimpleFooter()}");

            var emailHtml = HtmlEmail.WrapInNestedCenteringTable(innerContent);

            return(emailHtml);
        }
        public static HtmlTag PhotoFigCaptionTag(PhotoContent dbEntry, bool includeTitle = false)
        {
            if (string.IsNullOrWhiteSpace(dbEntry.Summary))
            {
                return(HtmlTag.Empty());
            }

            var figCaptionTag = new HtmlTag("figcaption");

            figCaptionTag.AddClass("single-photo-caption");
            figCaptionTag.Text(string.Join(" ", PhotoCaptionText(dbEntry, includeTitle)));

            return(figCaptionTag);
        }
        public static async Task <(GenerationReturn generationReturn, PhotoContent photoContent)> SaveToDb(
            PhotoContent toSave, FileInfo selectedFile, IProgress <string> progress)
        {
            var validationReturn = await Validate(toSave, selectedFile);

            if (validationReturn.HasError)
            {
                return(validationReturn, null);
            }

            FileManagement.WriteSelectedPhotoContentFileToMediaArchive(selectedFile);
            await Db.SavePhotoContent(toSave);

            return(await GenerationReturn.Success($"Saved {toSave.Title}"), toSave);
        }
        private HtmlTag EmailPhotoTableTag(PhotoContent dbEntry)
        {
            var tableContainer = new TableTag();

            tableContainer.Style("margin", "20px").Style("text-align", "center");
            var pictureRow  = tableContainer.AddBodyRow();
            var pictureCell = pictureRow.Cell();

            pictureCell.Children.Add(Tags.PictureEmailImgTag(Pictures, true));

            var captionRow  = tableContainer.AddBodyRow();
            var captionCell = captionRow.Cell(Tags.PhotoCaptionText(dbEntry, false));

            captionCell.Style("opacity", ".5");

            return(tableContainer);
        }
        public PhotoContentEditorWindow(PhotoContent toLoad)
        {
            InitializeComponent();

            StatusContext = new StatusControlContext();

            StatusContext.RunFireAndForgetBlockingTaskWithUiMessageReturn(async() =>
            {
                PhotoEditor = await PhotoContentEditorContext.CreateInstance(StatusContext, toLoad);

                PhotoEditor.RequestContentEditorWindowClose += (sender, args) => { Dispatcher?.Invoke(Close); };
                AccidentalCloserHelper = new WindowAccidentalClosureHelper(this, StatusContext, PhotoEditor);

                await ThreadSwitcher.ResumeForegroundAsync();
                DataContext = this;
            });
        }
        public static async Task <GenerationReturn> Validate(PhotoContent photoContent, FileInfo selectedFile)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    photoContent.ContentId));
            }

            var mediaArchiveCheck = UserSettingsUtilities.ValidateLocalMediaArchive();

            if (!mediaArchiveCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Media Archive: {mediaArchiveCheck.Item2}",
                                                    photoContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(photoContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, photoContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(photoContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, photoContent.ContentId));
            }

            selectedFile.Refresh();

            var photoFileValidation =
                await CommonContentValidation.PhotoFileValidation(selectedFile, photoContent?.ContentId);

            if (!photoFileValidation.isValid)
            {
                return(await GenerationReturn.Error(photoFileValidation.explanation, photoContent.ContentId));
            }

            return(await GenerationReturn.Success("Photo Content Validation Successful"));
        }
        public static string PhotoCaptionText(PhotoContent dbEntry, bool includeTitle = false)
        {
            var summaryStringList = new List <string>();

            string titleSummaryString;

            var summaryHasValue = !string.IsNullOrWhiteSpace(dbEntry.Summary);

            if (includeTitle || !summaryHasValue)
            {
                titleSummaryString = dbEntry.Title;

                if (summaryHasValue)
                {
                    var summaryIsInTitle = titleSummaryString.Replace(".", string.Empty).ToLower()
                                           .Contains(dbEntry.Summary.TrimNullSafe().Replace(".", string.Empty).ToLower());

                    if (!summaryIsInTitle)
                    {
                        titleSummaryString += $": {dbEntry.Summary.TrimNullSafe()}";
                    }
                }

                if (!titleSummaryString.EndsWith("."))
                {
                    titleSummaryString += ".";
                }
            }
            else
            {
                titleSummaryString = dbEntry.Summary.TrimNullSafe();
                if (!titleSummaryString.EndsWith("."))
                {
                    titleSummaryString += ".";
                }
            }

            summaryStringList.Add(titleSummaryString);

            summaryStringList.Add($"{dbEntry.PhotoCreatedBy}.");
            summaryStringList.Add($"{dbEntry.PhotoCreatedOn:M/d/yyyy}.");

            return(string.Join(" ", summaryStringList));
        }
        public void PhotoJsonTest(PhotoContent newPhotoContent)
        {
            //Check JSON File
            var jsonFile =
                new FileInfo(Path.Combine(
                                 UserSettingsSingleton.CurrentSettings().LocalSitePhotoContentDirectory(newPhotoContent).FullName,
                                 $"{Names.PhotoContentPrefix}{newPhotoContent.ContentId}.json"));

            Assert.True(jsonFile.Exists, $"Json file {jsonFile.FullName} does not exist?");

            var jsonFileImported = Import.ContentFromFiles <PhotoContent>(
                new List <string> {
                jsonFile.FullName
            }, Names.PhotoContentPrefix).Single();
            var compareLogic     = new CompareLogic();
            var comparisonResult = compareLogic.Compare(newPhotoContent, jsonFileImported);

            Assert.True(comparisonResult.AreEqual,
                        $"Json Import does not match expected Photo Content {comparisonResult.DifferencesString}");
        }
        public IActionResult UpdateThumbnail([FromBody] PhotoContent photo)
        {
            try
            {
                _logger.LogInformation("POST /v1/Profile/UpdateThumbnail called");

                //Access level
                var id = _accountService.GetCurrentUserId();
                //todo check if user has access to this photo

                var profile = _aquariumService.GetProfileById(id);
                profile.ThumbnailId = photo.Id;
                var p = _accountService.UpdateProfile(profile);
                return(new OkObjectResult(p));
            }
            catch (Exception ex)
            {
                _logger.LogError($"POST /v1/Profile/UpdateThumbnail endpoint caught exception: { ex.Message } Details: { ex.ToString() }");
                return(NotFound());
            }
        }