public HttpResponseMessage Delete(string userName)
        {
            // DELETE /api/users
            try
            {
                // Don't need to check security here because we'll do that in RoleController.DeleteGalleryServerProRole.
                UserController.DeleteGalleryServerProUser(userName, true);

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(String.Format(CultureInfo.CurrentCulture, "User '{0}' has been deleted", Utils.HtmlEncode(userName)))
                });
            }
            catch (GallerySecurityException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    Content      = new StringContent(ex.Message),
                    ReasonPhrase = "Action Forbidden"
                });
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                await _albumController.DeleteAlbum(id);

                return(Ok($"Album {id} deleted..."));
            }
            catch (InvalidAlbumException)
            {
                // HTTP specification says the DELETE method must be idempotent, so deleting a nonexistent item must have
                // the same effect as deleting an existing one. So we simply return HttpStatusCode.OK.
                return(Ok($"Album with ID {id} does not exist."));
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                return(Forbid());
            }
            catch (CannotDeleteAlbumException ex)
            {
                AppEventController.LogError(ex);

                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public Entity.User Get(string userName, int galleryId)
        {
            // GET /api/users/getbyusername?userName=Admin&amp;galleryId=1
            try
            {
                return(UserController.GetUserEntity(userName, galleryId));
            }
            catch (GallerySecurityException)
            {
                // This is thrown when the current user does not have view and edit permission to the requested user.
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (InvalidUserException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("User '{0}' does not exist", userName)),
                    ReasonPhrase = "User Not Found"
                });
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #4
0
        /// <summary>
        /// Initializes the request.
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <returns>
        /// Returns <c>true</c> when the method succeeds; otherwise <c>false</c>.
        /// </returns>
        public override bool InitializeRequest(HttpContext context)
        {
            bool isSuccessfullyInitialized = false;

            try
            {
                if (!GalleryController.IsInitialized)
                {
                    GalleryController.InitializeGspApplication();
                }

                if (InitializeVariables(context))
                {
                    isSuccessfullyInitialized = true;
                }
                else
                {
                    _context.Response.StatusCode = 404;
                }

                return(base.InitializeRequest(context) & isSuccessfullyInitialized);
            }
            catch (System.Threading.ThreadAbortException)
            {
                throw;                 // We don't want these to fall into the generic catch because we don't want them logged.
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);
            }

            return(isSuccessfullyInitialized);
        }
Beispiel #5
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (!GalleryController.IsInitialized)
                {
                    GalleryController.InitializeGspApplication();
                }

                if (InitializeVariables(context))
                {
                    string tvXml = GenerateTreeviewJson();
                    context.Response.ContentType = "text/json";
                    context.Response.Cache.SetCacheability(HttpCacheability.NoCache); // Needed for IE 7
                    context.Response.Write(tvXml);
                }
                else
                {
                    context.Response.End();
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                throw; // We don't want these to fall into the generic catch because we don't want them logged.
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);
                throw;
            }
        }
        public IQueryable <Entity.MediaItem> GetMediaItemsForAlbumId(int id, int sortByMetaNameId = int.MinValue, bool sortAscending = true)
        {
            // GET /api/albums/12/mediaitems - Gets media items for album #12
            try
            {
                return(Controller.GalleryObjectController.GetMediaItemsInAlbum(id, (MetadataItemName)sortByMetaNameId, sortAscending));
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID = {0}", id)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        /// <summary>
        /// Gets the album with the specified <paramref name="id" />. The properties
        /// <see cref="Entity.Album.GalleryItems" /> and <see cref="Entity.Album.MediaItems" />
        /// are set to null to keep the instance small. Example: api/albums/4/
        /// </summary>
        /// <param name="id">The album ID.</param>
        /// <returns>An instance of <see cref="Entity.Album" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException"></exception>
        public Entity.Album Get(int id)
        {
            IAlbum album = null;

            try
            {
                album = AlbumController.LoadAlbumInstance(id, true);
                SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), album.Id, album.GalleryId, Utils.IsAuthenticated, album.IsPrivate, album.IsVirtualAlbum);
                var permissionsEntity = new Entity.Permissions();

                return(AlbumController.ToAlbumEntity(album, permissionsEntity, new Entity.GalleryDataLoadOptions()));
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID = {0}", id)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, (album != null ? album.GalleryId : new int?()));

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #8
0
        public ActionResult PrepareZipDownload(Entity.GalleryItem[] galleryItems, DisplayObjectType mediaSize)
        {
            try
            {
                return(AlbumController.PrepareZipDownload(galleryItems, mediaSize));
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                return(new ActionResult
                {
                    Title = "Cannot Download",
                    Status = ActionResultStatus.Warning.ToString(),
                    Message = ex.Message
                });
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        /// <summary>
        /// Gets a JSON string representing the tags used in the specified gallery. The JSON can be used as the
        /// data source for the jsTree jQuery widget. Only tags the current user has permission to view are
        /// included. The tag tree has a root node containing a single level of tags. Throws an exception when
        /// the application is not running an Enterprise License.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        /// <param name="top">The number of tags to return. Values less than zero are treated the same as zero,
        /// meaning no tags will be returned. Specify <see cref="int.MaxValue" /> to return all tags.</param>
        /// <param name="sortBy">The property to sort the tags by. Specify "count" to sort by tag frequency or
        /// "value" to sort by tag name. When not specified, defaults to "count".</param>
        /// <param name="sortAscending">Specifies whether to sort the tags in ascending order. Specify <c>true</c>
        /// for ascending order or <c>false</c> for descending order. When not specified, defaults to <c>false</c>.</param>
        /// <param name="expanded">if set to <c>true</c> the tree is configured to display in an expanded form.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when an error occurs.</exception>
        public string GetTagTreeAsJson(int galleryId, int top = int.MaxValue, string sortBy = "count", bool sortAscending = false, bool expanded = false)
        {
            try
            {
                ValidateEnterpriseLicense();

                TagSearchOptions.TagProperty sortProperty;
                if (!Enum.TryParse(sortBy, true, out sortProperty))
                {
                    sortProperty = TagSearchOptions.TagProperty.NotSpecified;
                }

                return(MetadataController.GetTagTreeAsJson(TagSearchType.TagsUserCanView, galleryId, top, sortProperty, sortAscending, expanded));
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #10
0
        public Entity.GalleryData GetInflatedMediaObject(int id)
        {
            try
            {
                IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(id);
                return(GalleryController.GetGalleryDataForMediaObject(mediaObject, (IAlbum)mediaObject.Parent, new Entity.GalleryDataLoadOptions {
                    LoadMediaItems = true
                }));
            }
            catch (InvalidMediaObjectException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find media object with ID = {0}", id)),
                    ReasonPhrase = "Media Object Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #11
0
        /// <summary>
        /// Gets the media object with the specified <paramref name="id" />.
        /// Example: api/mediaitems/4/get
        /// </summary>
        /// <param name="id">The media object ID.</param>
        /// <returns>An instance of <see cref="Entity.MediaItem" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when the media object is not found, the user
        /// doesn't have permission to view it, or some other error occurs.</exception>
        public Entity.MediaItem Get(int id)
        {
            try
            {
                IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(id);
                SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), mediaObject.Parent.Id, mediaObject.GalleryId, Utils.IsAuthenticated, mediaObject.Parent.IsPrivate, ((IAlbum)mediaObject.Parent).IsVirtualAlbum);
                var siblings         = mediaObject.Parent.GetChildGalleryObjects(GalleryObjectType.MediaObject, !Utils.IsAuthenticated).ToSortedList();
                int mediaObjectIndex = siblings.IndexOf(mediaObject);

                return(GalleryObjectController.ToMediaItem(mediaObject, mediaObjectIndex + 1, MediaObjectHtmlBuilder.GetMediaObjectHtmlBuilderOptions(mediaObject)));
            }
            catch (InvalidMediaObjectException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find media object with ID = {0}", id)),
                    ReasonPhrase = "Media Object Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public async Task <IActionResult> ReplaceMediaAssetFile(int mediaAssetId, string fileNameOnServer, string fileName)
        {
            try
            {
                var filePath = Path.Combine(AppSetting.Instance.ContentRootPath, GlobalConstants.TempUploadDirectory, fileNameOnServer);

                return(new JsonResult(await _galleryObjectController.ReplaceMediaAssetFile(mediaAssetId, filePath, fileName)));
            }
            catch (InvalidMediaObjectException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Cannot Edit Media Asset",
                    Message = ex.Message
                }));
            }
            catch (GallerySecurityException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Cannot Replace Media Asset",
                    Message = ex.Message
                }));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
Beispiel #13
0
        public IAlbum GetByPeople(string q, int sortByMetaNameId = int.MinValue, bool sortAscending = true, string destinationUrl = null, string filter = "all", int galleryId = int.MinValue)
        {
            IAlbum album = null;

            try
            {
                album = GalleryObjectController.GetGalleryObjectsHavingTags(null, Utils.ToArray(q), GalleryObjectTypeEnumHelper.Parse(filter, GalleryObjectType.All), ValidateGallery(galleryId));

                album.FeedFormatterOptions = new FeedFormatterOptions()
                {
                    SortByMetaName = (MetadataItemName)sortByMetaNameId,
                    SortAscending  = sortAscending,
                    DestinationUrl = String.IsNullOrWhiteSpace(destinationUrl) ? String.Concat(Utils.AppRoot, "/") : destinationUrl
                };

                return(album);
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, (album != null ? album.GalleryId : new int?()));

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public IActionResult PutGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // PUT /api/galleryitemmeta
            try
            {
                _metadataController.SaveGalleryItemMeta(galleryItemMeta);

                if (galleryItemMeta.ActionResult == null)
                {
                    galleryItemMeta.ActionResult = new Business.ActionResult()
                    {
                        Status = ActionResultStatus.Success.ToString(),
                        Title  = "Save successful"
                    };
                }
            }
            catch (GallerySecurityException)
            {
                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }

            return(Ok(galleryItemMeta));
        }
        public IActionResult GetInflatedMediaObject(int id)
        {
            try
            {
                var mediaObject = Factory.LoadMediaObjectInstance(id);

                return(new JsonResult(_galleryController.GetGalleryDataForMediaObject(mediaObject, (IAlbum)mediaObject.Parent, new Entity.GalleryDataLoadOptions {
                    LoadMediaItems = true
                })));
            }
            catch (InvalidMediaObjectException)
            {
                return(NotFound("Media Asset Not Found: Could not find media object with ID {id}."));
            }
            catch (GallerySecurityException)
            {
                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public async Task <IActionResult> DeleteGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // DELETE /api/galleryitemmeta
            try
            {
                var mType = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
                if (mType == MetadataItemName.Tags || mType == MetadataItemName.People)
                {
                    await _metadataController.DeleteTag(galleryItemMeta);
                }
                else
                {
                    await _metadataController.Delete(galleryItemMeta);
                }

                return(Ok("Meta item deleted..."));
            }
            catch (GallerySecurityException)
            {
                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        /// <summary>
        /// Updates the gallery items with the specified metadata value. <see cref="Entity.GalleryItemMeta.ActionResult" />
        /// contains details about the success or failure of the operation.
        /// </summary>
        /// <param name="galleryItemMeta">An instance of <see cref="Entity.GalleryItemMeta" /> that defines
        /// the tag value to be added and the gallery items it is to be added to. It is expected that only
        /// the MTypeId and Value properties of <see cref="Entity.GalleryItemMeta.MetaItem" /> are populated.</param>
        /// <returns>An instance of <see cref="Entity.GalleryItemMeta" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when the current user does not have permission
        /// to carry out the operation or an internal server error occurs.</exception>
        public Entity.GalleryItemMeta PutGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // /api/galleryitemmeta
            try
            {
                MetadataController.SaveGalleryItemMeta(galleryItemMeta);

                if (galleryItemMeta.ActionResult == null)
                {
                    galleryItemMeta.ActionResult = new ActionResult()
                    {
                        Status = ActionResultStatus.Success.ToString(),
                        Title  = "Save successful"
                    };
                }
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }

            return(galleryItemMeta);
        }
        /// <summary>
        /// Deletes the meta tag value from the specified gallery items.
        /// </summary>
        /// <param name="galleryItemMeta">An instance of <see cref="Entity.GalleryItemMeta" /> that defines
        /// the tag value to be added and the gallery items it is to be added to.</param>
        /// <returns><see cref="HttpResponseMessage" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException"></exception>
        public HttpResponseMessage DeleteGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // /api/galleryitemmeta
            try
            {
                var mType = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
                if (mType == MetadataItemName.Tags || mType == MetadataItemName.People)
                {
                    MetadataController.DeleteTag(galleryItemMeta);
                }
                else
                {
                    MetadataController.Delete(galleryItemMeta);
                }

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("Meta item deleted...")
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public void Sort(int id, int sortByMetaNameId, bool sortAscending)
        {
            try
            {
                AlbumController.Sort(id, sortByMetaNameId, sortAscending);
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID = {0}", id)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public async Task <IActionResult> Get(int id)
        {
            // GET /api/mediaitems/get/4
            try
            {
                //var settings = new AddMediaObjectSettings { AlbumId = 2, CurrentUserName = "******", DiscardOriginalFile = false, FileName = "Desert.jpg", FileNameOnServer = "Desert.jpg" };

                //var results = await _galleryObjectController.AddMediaObject(settings);

                IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(id);
                SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, await _userController.GetGalleryServerRolesForUser(), mediaObject.Parent.Id, mediaObject.GalleryId, _userController.IsAuthenticated, mediaObject.Parent.IsPrivate, ((IAlbum)mediaObject.Parent).IsVirtualAlbum);
                var siblings         = mediaObject.Parent.GetChildGalleryObjects(GalleryObjectType.MediaObject, !_userController.IsAuthenticated).ToSortedList();
                int mediaObjectIndex = siblings.IndexOf(mediaObject);

                return(new JsonResult(_galleryObjectController.ToMediaItem(mediaObject, mediaObjectIndex + 1, _htmlController.GetMediaObjectHtmlBuilderOptions(mediaObject))));
            }
            catch (InvalidMediaObjectException)
            {
                return(NotFound($"Could not find media object with ID {id}"));
            }
            catch (GallerySecurityException)
            {
                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public IQueryable <Entity.GalleryItem> Sort(Entity.AlbumAction albumAction)
        {
            // POST /api/albums/getsortedalbum -
            try
            {
                return(GalleryObjectController.SortGalleryItems(albumAction));
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID = {0}", albumAction.Album.Id)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #22
0
        private void Gallery_Error(object sender, EventArgs e)
        {
            // Grab a handle to the exception that is giving us grief.
            Exception ex = Server.GetLastError();

            if (Context != null)
            {
                ex = Context.Error;
            }

            if (ex != null)
            {
                try
                {
                    if (GalleryId > int.MinValue)
                    {
                        AppEventController.HandleGalleryException(ex, GalleryId);
                    }
                    else
                    {
                        AppEventController.HandleGalleryException(ex);
                    }

                    Utils.PerformMaintenance(); // This might fix errors like missing/corrupt records in the database.
                }
                catch { }
            }
        }
Beispiel #23
0
        public IAlbum GetByRating(string rating, int top = 50, int sortByMetaNameId = (int)MetadataItemName.DateAdded, bool sortAscending = false, string destinationUrl = null, string filter = "mediaobject", int galleryId = int.MinValue)
        {
            IAlbum album = null;

            try
            {
                album = GalleryObjectController.GetRatedMediaObjects(rating, top, ValidateGallery(galleryId), GalleryObjectTypeEnumHelper.Parse(filter, GalleryObjectType.MediaObject));

                album.FeedFormatterOptions = new FeedFormatterOptions()
                {
                    SortByMetaName = (MetadataItemName)sortByMetaNameId,
                    SortAscending  = sortAscending,
                    DestinationUrl = String.IsNullOrWhiteSpace(destinationUrl) ? String.Concat(Utils.AppRoot, "/") : destinationUrl
                };

                return(album);
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, (album != null ? album.GalleryId : new int?()));

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #24
0
        private void Gallery_Error(object sender, EventArgs e)
        {
            // Grab a handle to the exception that is giving us grief.
            Exception ex = Server.GetLastError();

            if (Context != null)
            {
                ex = Context.Error;
            }

            if (ex != null)
            {
                try
                {
                    if (GalleryId > int.MinValue)
                    {
                        AppEventController.HandleGalleryException(ex, GalleryId);
                    }
                    else
                    {
                        AppEventController.HandleGalleryException(ex);
                    }
                }
                catch { }
            }
        }
Beispiel #25
0
        public IQueryable <Entity.MetaItem> GetMetaItemsForMediaObjectId(int id)
        {
            // GET /api/mediaitems/12/meta - Gets metadata items for media object #12
            try
            {
                return(GalleryObjectController.GetMetaItemsForMediaObject(id).AsQueryable());
            }
            catch (InvalidMediaObjectException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find media object with ID = {0}", id)),
                    ReasonPhrase = "Media Object Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Beispiel #26
0
        private Stream GetWatermarkedImageStream()
        {
            Image watermarkedImage = null;

            try
            {
                try
                {
                    watermarkedImage = ImageHelper.AddWatermark(MediaObjectFilePath, MediaObject.GalleryId);
                }
                catch (Exception ex)
                {
                    // Can't apply watermark to image. Substitute an error image and send that to the user.
                    if (!(ex is FileNotFoundException))
                    {
                        // Don't log FileNotFoundException exceptions. This helps avoid clogging the error log
                        // with entries caused by search engine retrieving media objects that have been moved or deleted.
                        AppEventController.LogError(ex);
                    }
                    watermarkedImage = Image.FromFile(_context.Request.MapPath(String.Concat(Utils.SkinPath, "/images/error-xl.png")));
                }

                MemoryStream stream = new MemoryStream();
                watermarkedImage.Save(stream, ImageFormat.Jpeg);
                return(stream);
            }
            finally
            {
                if (watermarkedImage != null)
                {
                    watermarkedImage.Dispose();
                }
            }
        }
Beispiel #27
0
        private static void LogUploadZipFileResults(List <ActionResult> results, AddMediaObjectSettings settings)
        {
            var    isSuccessful = results.All(r => r.Status == ActionResultStatus.Success.ToString());
            int?   galleryId    = null;
            IAlbum album        = null;

            try
            {
                album     = Factory.LoadAlbumInstance(settings.AlbumId);
                galleryId = album.GalleryId;
            }
            catch (InvalidAlbumException) { }

            if (isSuccessful)
            {
                AppEventController.LogEvent(String.Format(CultureInfo.InvariantCulture, "{0} files were successfully extracted from the file '{1}' and added to album '{2}'.", results.Count, settings.FileName, album != null ? album.Title : "<Unknown>"), galleryId);

                return;
            }

            // If we get here at least one of the results was an info, warning, error, etc.
            var succesfulResults   = results.Where(m => m.Status == ActionResultStatus.Success.ToString());
            var unsuccesfulResults = results.Where(m => m.Status != ActionResultStatus.Success.ToString());
            var msg = String.Format(CultureInfo.InvariantCulture, "{0} items in the uploaded file '{1}' were added to the gallery, but {2} files were skipped. Review the details for additional information. The file was uploaded by user {3}.", succesfulResults.Count(), settings.FileName, unsuccesfulResults.Count(), settings.CurrentUserName);
            var ex  = new UnsupportedMediaObjectTypeException(msg, null);

            var i = 1;

            foreach (var result in unsuccesfulResults)
            {
                ex.Data.Add("File " + i++, String.Format(CultureInfo.InvariantCulture, "{0}: {1}", result.Title, result.Message));
            }

            AppEventController.LogError(ex, galleryId);
        }
        public async Task <IActionResult> PutMetaItem(Entity.MetaItem metaItem)
        {
            try
            {
                return(new JsonResult(await _metadataController.Save(metaItem)));
            }
            catch (InvalidAlbumException)
            {
                return(NotFound($"Could not find album with ID {metaItem.MediaId}"));
            }
            catch (InvalidMediaObjectException)
            {
                return(NotFound($"Media Asset/Metadata Item Not Found: One of the following errors occurred: (1) Could not find meta item with ID {metaItem.Id} (2) Could not find media asset with ID {metaItem.MediaId}"));
            }
            catch (GallerySecurityException)
            {
                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public IActionResult Delete(int id)
        {
            // DELETE /api/events/delete/12
            IEvent appEvent = null;

            try
            {
                appEvent = Factory.GetAppEvents().FindById(id);

                if (appEvent == null)
                {
                    // HTTP specification says the DELETE method must be idempotent, so deleting a nonexistent item must have
                    // the same effect as deleting an existing one. So we simply return HttpStatusCode.OK.
                    return(Ok(string.Format("Event with ID {0} does not exist.", id)));
                    //return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(String.Format("Event with ID = {0} does not exist.", id)) };
                }

                //var isAuthorized = true;

                //// If the event has a non-template gallery ID (not all do), then check the user's permission. For those errors without a gallery ID,
                //// just assume the user has permission, because there is no way to verify the user can delete this event. We could do something
                //// that mostly works like verifying the user is a gallery admin for at least one gallery, but the function we are trying to
                //// protect is deleting an event message, which is not that important to worry about.
                //if (appEvent.GalleryId != GalleryController.GetTemplateGalleryId())
                //{
                //    isAuthorized = Utils.IsUserAuthorized(SecurityActions.AdministerSite | SecurityActions.AdministerGallery, RoleController.GetGalleryServerRolesForUser(), int.MinValue, appEvent.GalleryId, false, false);
                //}

                //if (isAuthorized)
                //{
                Events.EventController.Delete(id);
                CacheController.RemoveCache(CacheItem.AppEvents);

                return(Ok("Event deleted..."));
                //return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Event deleted...") };
                //}
                //else
                //{
                //    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
                //}
            }
            catch (Exception ex)
            {
                if (appEvent != null)
                {
                    AppEventController.LogError(ex, appEvent.GalleryId);
                }
                else
                {
                    AppEventController.LogError(ex);
                }

                return(StatusCode(500, _exController.GetExString(ex)));
                //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                //{
                //    Content = Utils.GetExStringContent(ex),
                //    ReasonPhrase = "Server Error"
                //});
            }
        }
        /// <summary>
        /// Moves or copies the <paramref name="itemsToTransfer" /> to the <paramref name="destinationAlbumId" />.
        /// </summary>
        /// <param name="destinationAlbumId">The ID of the destination album.</param>
        /// <param name="itemsToTransfer">The items to transfer.</param>
        /// <param name="transferType">Type of the transfer.</param>
        /// <returns>An instance of <see cref="IActionResult" />.</returns>
        private IActionResult TransferTo(int destinationAlbumId, Entity.GalleryItem[] itemsToTransfer, GalleryAssetTransferType transferType)
        {
            try
            {
                //TODO: Need to implement TransferToAlbum()
                var destinationAlbum = _albumController.TransferToAlbum(destinationAlbumId, itemsToTransfer, transferType, out var createdGalleryItems);

                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Success.ToString(),
                    Title = $"{transferType} Successful",
                    Message = "The items were transferred.",
                    ActionTarget = createdGalleryItems
                }));
            }
            catch (GallerySecurityException)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Transfer Aborted - Invalid Selection",
                    Message = "You do not have permission to move or copy media assets to the selected album or you selected an album in a read-only gallery. Review your selection."
                }));
            }
            catch (InvalidAlbumException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Transfer Aborted - Invalid Selection",
                    Message = ex.Message
                }));
            }
            catch (CannotTransferAlbumToNestedDirectoryException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Transfer Aborted - Invalid Selection",
                    Message = ex.Message
                }));
            }
            catch (UnsupportedMediaObjectTypeException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Transfer Aborted - Disabled File Type",
                    Message = $"One or more media assets you selected is a disabled file type ({System.IO.Path.GetExtension(ex.MediaObjectFilePath)}). An administrator can enable this file type on the File Types page."
                }));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }