Пример #1
0
        public MediaListModel GetMediaByType(string type)
        {
            MediaListModel newModel = new MediaListModel();

            using (var db = new MediaEntities())
            {
                var query = db.Media.Where(x => x.Type == type);

                var mediaSearch = query.ToList();

                mediaSearch.ForEach(media =>
                {
                    newModel.MediaList.Add(
                        new MediaModel()
                    {
                        Id          = media.Id,
                        Author      = media.Author,
                        Path        = media.Path,
                        Caption     = media.Caption,
                        Description = media.Description
                    });
                });
            }

            return(newModel);
        }
Пример #2
0
        public async Task <ActionResult> Index()
        {
            ActionResult result = null;

            var model = new MediaListModel();

            foreach (var i in await Groups.GetGroups())
            {
                model.Groups.Add(new GroupModel()
                {
                    Name    = i.Name,
                    Builtin = i.Builtin
                });
            }

            foreach (var i in await Image.GetImages())
            {
                model.Images.Add(new ImageModel()
                {
                    Name  = i.Name,
                    Group = i.Group
                });
            }

            result = View(model);

            return(result);
        }
Пример #3
0
        public async Task <IActionResult> SaveFolder(MediaFolderModel model, MediaType?filter = null)
        {
            try
            {
                await _service.SaveFolder(model);

                var result = await _service.GetList(model.ParentId, filter);

                result.Status = new StatusMessage
                {
                    Type = StatusMessage.Success,
                    Body = String.Format(_localizer.Media["The folder <code>{0}</code> was saved"], model.Name)
                };

                return(Ok(result));
            }
            catch (ValidationException e)
            {
                var result = new MediaListModel();
                result.Status = new StatusMessage
                {
                    Type = StatusMessage.Error,
                    Body = e.Message
                };
                return(BadRequest(result));
            }
        }
Пример #4
0
        public MediaListModel GetAllMedia()
        {
            MediaListModel model = new MediaListModel();

            using (var db = new MediaEntities())
            {
                var query    = db.Media.Select(x => x);
                var bikeList = query.ToList();

                bikeList.ForEach(x =>
                                 model.MediaList.Add(
                                     new MediaModel()
                {
                    Id          = x.Id,
                    Author      = x.Author,
                    Caption     = x.Caption,
                    Description = x.Description,
                    Path        = x.Path,
                    Type        = (MediaType)Enum.Parse(typeof(MediaType), x.Type),
                    Category    = (MediaCategory)Enum.Parse(typeof(MediaCategory), x.Category)
                }
                                     )
                                 );
            }
            return(model);
        }
Пример #5
0
        public async Task <IActionResult> Delete(Guid id)
        {
            try
            {
                var folderId = await _service.DeleteMedia(id);

                var result = await _service.GetList(folderId);

                result.Status = new StatusMessage
                {
                    Type = StatusMessage.Success,
                    Body = $"The media file was successfully deleted"
                };

                return(Ok(result));
            }
            catch (ValidationException e)
            {
                var result = new MediaListModel();
                result.Status = new StatusMessage
                {
                    Type = StatusMessage.Error,
                    Body = e.Message
                };
                return(BadRequest(result));
            }
        }
Пример #6
0
        public IHtmlContent GetBreadcrumb(MediaListModel model, string targetListDOMObject = "#media-list")
        {
            List <string> links = new List <string>();

            LinkGenerator linkGenerator = Hood.Core.Engine.Services.Resolve <Microsoft.AspNetCore.Routing.LinkGenerator>();
            string        baseUrl       = linkGenerator.GetPathByAction("List", "Media", new { area = "Admin" });


            MediaListModel linkModel = new MediaListModel();

            model.CopyProperties(linkModel);
            string link;

            if (!model.RootId.HasValue)
            {
                linkModel.DirectoryId = null;
                link = linkModel.GetPageUrl(linkModel.PageIndex);
                links.Add($"<a class=\"hood-inline-list-target\" data-target=\"{targetListDOMObject}\" href=\"{baseUrl}{link}\">Everything</a>");
            }

            if (!model.DirectoryId.HasValue)
            {
                return(FormatBreadcrumbLinks(links));
            }

            foreach (MediaDirectory directory in GetHierarchy(model.DirectoryId.Value, model.RootId))
            {
                linkModel.DirectoryId = directory.Id;
                link = linkModel.GetPageUrl(linkModel.PageIndex);
                var linkTitle = directory.DisplayName.IsSet() ? directory.DisplayName : "Untitled";
                links.Add($"<a class=\"hood-inline-list-target\" data-target=\"{targetListDOMObject}\" href=\"{baseUrl}{link}\">{linkTitle}</a>");
            }
            return(FormatBreadcrumbLinks(links));
        }
Пример #7
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            // Wrap each group of tiles to show in an ItemsListWrapper and add
            // the wrapper to the backing list.
            // For the media home content, the firat item is a list of shortcuts
            // to media filters, followed by a group of tiles for each media list.

            // Add the video media filters as the first tile group
            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new VideoYearShortcut(),
                new VideoLocationShortcut(),
                new VideoSystemShortcut(),
                new VideoSizeShortcut(),
                new VideoSearchShortcut()
            }));

            // Add a wrapper for each video media list, we use a separate type for each wrapper
            // so we can use automatic template selection when they are displayed in an ItemsControl.
            _backingList.Add(new LatestVideoList(mlm.Lists["LatestVideo"].AllItems));
            _backingList.Add(new ContinuePlayVideoList(mlm.Lists["ContinuePlayVideo"].AllItems));
            _backingList.Add(new FavoriteVideoList(mlm.Lists["FavoriteVideo"].AllItems));
            _backingList.Add(new UnplayedVideoList(mlm.Lists["UnplayedVideo"].AllItems));
        }
Пример #8
0
        protected override void ForceUpdateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            mlm.ForceUpdate("LatestImages");
            mlm.ForceUpdate("FavoriteImages");
            mlm.ForceUpdate("UnplayedImages");
        }
Пример #9
0
        /// <summary>
        /// Gets the list model for the specified folder, or the root
        /// folder if to folder id is given.
        /// </summary>
        /// <param name="folderId">The optional folder id</param>
        /// <returns>The list model</returns>
        public async Task <MediaListModel> GetList(Guid?folderId = null, MediaType?filter = null)
        {
            var model = new MediaListModel
            {
                CurrentFolderId = folderId,
                ParentFolderId  = null
            };

            if (folderId.HasValue)
            {
                var folder = await _api.Media.GetFolderByIdAsync(folderId.Value);

                if (folder != null)
                {
                    model.ParentFolderId = folder.ParentId;
                }
            }

            model.Media = (await _api.Media.GetAllAsync(folderId))
                          .Select(m => new MediaListModel.MediaItem
            {
                Id           = m.Id,
                FolderId     = m.FolderId,
                Type         = m.Type.ToString(),
                Filename     = m.Filename,
                PublicUrl    = m.PublicUrl.Replace("~", ""),
                ContentType  = m.ContentType,
                Size         = Utils.FormatByteSize(m.Size),
                Width        = m.Width,
                Height       = m.Height,
                LastModified = m.LastModified.ToString("yyyy-MM-dd")
            }).ToList();

            if (filter.HasValue)
            {
                model.Media = model.Media
                              .Where(m => m.Type == filter.Value.ToString())
                              .ToList();
            }

            var structure = await _api.Media.GetStructureAsync();

            model.Folders = structure.GetPartial(folderId)
                            .Select(f => new MediaListModel.FolderItem
            {
                Id   = f.Id,
                Name = f.Name
            }).ToList();

            foreach (var folder in model.Folders)
            {
                //
                // TODO: Optimize, we don't need all this data
                //
                folder.ItemCount = (await _api.Media.GetAllAsync(folder.Id)).Count() + structure.GetPartial(folder.Id).Count();
            }
            return(model);
        }
Пример #10
0
        protected override void ForceUpdateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            mlm.ForceUpdate("LatestMovies");
            mlm.ForceUpdate("ContinuePlayMovies");
            mlm.ForceUpdate("FavoriteMovies");
            mlm.ForceUpdate("UnplayedMovies");
        }
Пример #11
0
        protected override void ForceUpdateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            mlm.ForceUpdate("LatestAudio");
            mlm.ForceUpdate("ContinuePlayAlbum");
            mlm.ForceUpdate("FavoriteAudio");
            mlm.ForceUpdate("UnplayedAlbum");
        }
Пример #12
0
        protected override void ForceUpdateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            mlm.ForceUpdate("LastPlayTV");
            mlm.ForceUpdate("FavoriteTV");
            mlm.ForceUpdate("CurrentPrograms");
            mlm.ForceUpdate("CurrentSchedules");
        }
Пример #13
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new NewsSetupShortcut(),
                new NewsRefreshShortcut(),
            }));
        }
Пример #14
0
        public static MediaListModel  CreateModel(this Medium medium)
        {
            var model = new MediaListModel();

            model.MediaID  = medium.MediaID;
            model.Name     = medium.Name;
            model.Location = medium.Location;

            try
            {
                var location = medium.Location;

                var extension = Path.GetExtension(location);
                if (!String.IsNullOrEmpty(extension) && !String.IsNullOrEmpty(location) && !String.IsNullOrEmpty(extension))
                {
                    var path = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                               HttpRuntime.AppDomainAppVirtualPath;
                    // var path = VirtualPathUtility.ToAbsolute("~/");

                    if (path.Contains("eAd.Website"))
                    {
                        path = "http://localhost/eAd.Website/";
                    }

                    model.ThumbnailUrl = medium.ThumbnailUrl;

                    if (Displayableurls.Contains(Path.GetExtension(location)))
                    {
                        model.DisplayLocation = !(String.IsNullOrEmpty(location))
                                            ? "/Uploads/Temp/Media" + "/" + "Thumb" +
                                                Path.GetFileNameWithoutExtension(location) + extension
                                            : "/Content/Images/no_image.gif";
                    }
                    if (!String.IsNullOrEmpty(medium.ThumbnailUrl) &&
                        Displayableurls.Contains(Path.GetExtension(medium.ThumbnailUrl)))
                    {
                        model.DisplayLocation = medium.ThumbnailUrl;
                    }
                    else
                    {
                        model.DisplayLocation = "/Uploads/Temp/Media" + "/" + "Thumb" +
                                                Path.GetFileNameWithoutExtension(location) + ".jpg";
                    }
                    model.Location        = path + model.Location.Replace("\\", "/");
                    model.DisplayLocation = path + model.DisplayLocation.Replace("\\", "/");
                    model.ThumbnailUrl    = path + model.ThumbnailUrl.Replace("\\", "/");
                }
            }
            catch (Exception)
            {
            }
            return(model);
        }
Пример #15
0
        public List <MediaListModel> GetMyMedia(long stationID)
        {
            var container = new eAdDataContainer();

            var source = new List <MediaListModel>();

            var station = (from s in container.Stations
                           where s.StationID == stationID
                           select s).FirstOrDefault <Station>();

            if (station != null)
            {
                EntityCollection <Grouping> groupings = station.Groupings;

                foreach (Grouping grouping in groupings)
                {
                    foreach (Theme theme in grouping.Themes)
                    {
                        using (IEnumerator <Medium> enumerator3 = theme.Media.GetEnumerator())
                        {
                            Func <MediaListModel, bool> predicate = null;

                            Medium media;

                            while (enumerator3.MoveNext())
                            {
                                media = enumerator3.Current;

                                if (predicate == null)
                                {
                                    predicate = l => l.MediaID == media.MediaID;
                                }

                                if (source.Where(predicate).Count <MediaListModel>() <= 0)
                                {
                                    var item = new MediaListModel
                                    {
                                        MediaID         = media.MediaID,
                                        DisplayLocation = media.Location,
                                        Duration        = media.Duration.Value
                                    };

                                    source.Add(item);
                                }
                            }
                        }
                    }
                }
            }

            return(source);
        }
Пример #16
0
        private void GetMedia(MessageViewModel message = null)
        {
            ServiceClient client = new ServiceClient("BasicHttpBinding_IService", Constants.ServerAddress);

            try
            {
                MediaListModel[] mediaList = client.GetMyMedia(Constants.MyStationID);

                if (message != null)
                {
                    client.MessageRead(message.ID);
                }

                ThreadPool.QueueUserWorkItem(delegate(object e4)
                {
                    MediaListModel[] modelArray1 = mediaList;

                    for (int j = 0; j < modelArray1.Length; j++)
                    {
                        MediaListModel model1 = modelArray1[j];
                    }
                });
            }

            catch (TimeoutException exception)
            {
                Console.WriteLine("Got {0}", exception.GetType());

                client.Abort();
            }

            catch (CommunicationException exception2)
            {
                Console.WriteLine("Got {0}", exception2.GetType());

                client.Abort();
            }

            finally
            {
                if (client != null)
                {
                    //   client.Dispose();
                }
            }
        }
Пример #17
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new ImageYearShortcut(),
                new ImageLocationShortcut(),
                new ImageSystemShortcut(),
                new ImageSizeShortcut(),
                new ImageSearchShortcut()
            }));

            _backingList.Add(new LatestImageList(mlm.Lists["LatestImages"].AllItems));
            _backingList.Add(new FavoriteImageList(mlm.Lists["FavoriteImages"].AllItems));
            _backingList.Add(new UnplayedImageList(mlm.Lists["UnplayedImages"].AllItems));
        }
Пример #18
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new MovieGenreShortcut(),
                new MovieYearShortcut(),
                new MovieAgeShortcut(),
                new MovieActorShortcut(),
                new MovieSearchShortcut()
            }));

            _backingList.Add(new LatestMovieList(mlm.Lists["LatestMovies"].AllItems));
            _backingList.Add(new ContinueMovieList(mlm.Lists["ContinuePlayMovies"].AllItems));
            _backingList.Add(new FavoriteMovieList(mlm.Lists["FavoriteMovies"].AllItems));
            _backingList.Add(new UnplayedMovieList(mlm.Lists["UnplayedMovies"].AllItems));
        }
Пример #19
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new LiveTVShortcut(),
                new EPGShortcut(),
                new SchedulesShortcut(),
                new RecordingsShortcut(),
                new TVSearchShortcut()
            }));

            _backingList.Add(new LastPlayTVList(mlm.Lists["LastPlayTV"].AllItems));
            _backingList.Add(new FavoriteTVList(mlm.Lists["FavoriteTV"].AllItems));
            _backingList.Add(new CurrentTVList(mlm.Lists["CurrentPrograms"].AllItems));
            _backingList.Add(new CurrentSchedulesList(mlm.Lists["CurrentSchedules"].AllItems));
        }
Пример #20
0
        protected override void PopulateBackingList()
        {
            MediaListModel mlm = GetMediaListModel();

            _backingList.Add(new MediaShortcutListWrapper(new List <ListItem>
            {
                new AudioGenreShortcut(),
                new AudioTrackShortcut(),
                new AudioAlbumShortcut(),
                new AudioArtistShortcut(),
                new AudioYearShortcut()
            }));

            _backingList.Add(new LatestAudioList(mlm.Lists["LatestAudio"].AllItems));
            _backingList.Add(new ContinueAlbumList(mlm.Lists["ContinuePlayAlbum"].AllItems));
            _backingList.Add(new FavoriteAudioList(mlm.Lists["FavoriteAudio"].AllItems));
            _backingList.Add(new UnplayedAlbumList(mlm.Lists["UnplayedAlbum"].AllItems));
        }
Пример #21
0
        public virtual async Task <Response> Attach(MediaListModel model)
        {
            try
            {
                // load the media object.
                MediaObject media = _db.Media.SingleOrDefault(m => m.Id == model.MediaId);
                string      cacheKey;
                switch (model.Entity)
                {
                case "Content":

                    // create the new media item for content =>
                    int     contentId = int.Parse(model.Id);
                    Content content   = await _db.Content.Where(p => p.Id == contentId).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case "FeaturedImage":
                        content.FeaturedImage = new ContentMedia(media);
                        break;

                    case "ShareImage":
                        content.ShareImage = new ContentMedia(media);
                        break;
                    }

                    cacheKey = typeof(Content).ToString() + ".Single." + contentId;
                    _cache.Remove(cacheKey);

                    break;

                case "ApplicationUser":

                    // create the new media item for content =>
                    ApplicationUser user = await _db.Users.Where(p => p.Id == model.Id).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case "Avatar":
                        user.Avatar = media;
                        break;
                    }


                    cacheKey = typeof(ApplicationUser).ToString() + ".Single." + model.Id;
                    _cache.Remove(cacheKey);

                    break;

                case "PropertyListing":

                    int             propertyId = int.Parse(model.Id);
                    PropertyListing property   = await _db.Properties.Where(p => p.Id == propertyId).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case "FeaturedImage":
                        property.FeaturedImage = media;
                        break;

                    case "InfoDownload":
                        property.InfoDownload = media;
                        break;
                    }

                    cacheKey = typeof(PropertyListing).ToString() + ".Single." + propertyId;
                    _cache.Remove(cacheKey);

                    break;

                default:
                    throw new Exception("No field set to attach the media item to.");
                }

                await _db.SaveChangesAsync();

                return(new Response(true, media, $"The media has been set for attached successfully."));
            }
            catch (Exception ex)
            {
                return(await ErrorResponseAsync <BaseMediaController>($"Error attaching a media file to an entity.", ex));
            }
        }
Пример #22
0
        public virtual async Task <Response> Clear(MediaListModel model)
        {
            try
            {
                // load the media object.
                string cacheKey;
                switch (model.Entity)
                {
                case nameof(Models.Content):

                    // create the new media item for content =>
                    int     contentId = int.Parse(model.Id);
                    Content content   = await _db.Content.Where(p => p.Id == contentId).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case nameof(Models.Content.FeaturedImage):
                        content.FeaturedImageJson = null;
                        break;

                    case nameof(Models.Content.ShareImage):
                        content.ShareImageJson = null;
                        break;
                    }

                    await _db.SaveChangesAsync();

                    cacheKey = typeof(Content).ToString() + ".Single." + contentId;
                    _cache.Remove(cacheKey);
                    return(new Response(true, MediaObject.Blank, $"The media file has been removed successfully."));

                case nameof(ApplicationUser):

                    // create the new media item for content =>
                    ApplicationUser user = await _db.Users.Where(p => p.Id == model.Id).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case nameof(ApplicationUser.Avatar):
                        user.AvatarJson = null;
                        break;
                    }


                    cacheKey = typeof(ApplicationUser).ToString() + ".Single." + model.Id;
                    _cache.Remove(cacheKey);
                    await _db.SaveChangesAsync();

                    return(new Response(true, MediaObject.Blank, $"The media file has been removed successfully."));

                case nameof(PropertyListing):

                    int             propertyId = int.Parse(model.Id);
                    PropertyListing property   = await _db.Properties.Where(p => p.Id == propertyId).FirstOrDefaultAsync();

                    switch (model.Field)
                    {
                    case nameof(PropertyListing.FeaturedImage):
                        property.FeaturedImageJson = null;
                        break;

                    case nameof(PropertyListing.InfoDownload):
                        property.InfoDownloadJson = null;
                        break;
                    }

                    await _db.SaveChangesAsync();

                    cacheKey = typeof(PropertyListing).ToString() + ".Single." + propertyId;
                    _cache.Remove(cacheKey);
                    return(new Response(true, MediaObject.Blank, $"The media file has been removed successfully."));

                default:
                    throw new Exception($"No entity supplied to remove from.");
                }
            }
            catch (Exception ex)
            {
                return(await ErrorResponseAsync <BaseMediaController>($"Error removing a media file from an entity.", ex));
            }
        }
Пример #23
0
        /// <summary>
        /// Gets the list model for the specified folder, or the root
        /// folder if to folder id is given.
        /// </summary>
        /// <param name="folderId">The optional folder id</param>
        /// <returns>The list model</returns>
        public async Task <MediaListModel> GetList(Guid?folderId = null, MediaType?filter = null, int?width = null, int?height = null)
        {
            var model = new MediaListModel
            {
                CurrentFolderId = folderId,
                ParentFolderId  = null
            };

            if (folderId.HasValue)
            {
                var folder = await _api.Media.GetFolderByIdAsync(folderId.Value);

                if (folder != null)
                {
                    model.CurrentFolderName = folder.Name;
                    model.ParentFolderId    = folder.ParentId;
                }
            }

            var holdMedia = (await _api.Media.GetAllByFolderIdAsync(folderId));

            if (filter.HasValue)
            {
                holdMedia = holdMedia
                            .Where(m => m.Type == filter.Value);
            }
            var pairMedia = holdMedia.Select(m => new { media = m, mediaItem = new MediaListModel.MediaItem
                                                        {
                                                            Id           = m.Id,
                                                            FolderId     = m.FolderId,
                                                            Type         = m.Type.ToString(),
                                                            Filename     = m.Filename,
                                                            PublicUrl    = m.PublicUrl.TrimStart('~'), //Will only enumerate the start of the string, probably a faster operation.
                                                            ContentType  = m.ContentType,
                                                            Size         = Utils.FormatByteSize(m.Size),
                                                            Width        = m.Width,
                                                            Height       = m.Height,
                                                            LastModified = m.LastModified.ToString("yyyy-MM-dd")
                                                        } }).ToArray();

            var structure = await _api.Media.GetStructureAsync();

            model.Folders = structure.GetPartial(folderId)
                            .Select(f => new MediaListModel.FolderItem
            {
                Id   = f.Id,
                Name = f.Name
            }).ToList();

            foreach (var folder in model.Folders)
            {
                folder.ItemCount = await _api.Media.CountFolderItemsAsync(folder.Id) +
                                   structure.GetPartial(folder.Id).Count;
            }
            if (width.HasValue)
            {
                foreach (var mp in pairMedia.Where(m => m.media.Type == MediaType.Image))
                {
                    if (mp.media.Versions.Any(v => v.Width == width && v.Height == height))
                    {
                        mp.mediaItem.AltVersionUrl =
                            (await _api.Media.EnsureVersionAsync(mp.media, width.Value, height).ConfigureAwait(false))
                            .TrimStart('~');
                    }
                }
            }

            model.Media    = pairMedia.Select(m => m.mediaItem).ToList();
            model.ViewMode = model.Media.Count(m => m.Type == "Image") > model.Media.Count / 2 ? MediaListModel.GalleryView : MediaListModel.ListView;

            return(model);
        }
Пример #24
0
 public virtual async Task <IActionResult> Action(MediaListModel model)
 {
     return(await List(model, "Action"));
 }
Пример #25
0
 public virtual async Task <IActionResult> Index(MediaListModel model)
 {
     return(await List(model, "Index"));
 }
Пример #26
0
        /// <summary>
        /// Gets the list model for the specified folder, or the root
        /// folder if no folder id is given.
        /// </summary>
        /// <param name="folderId">The optional folder id</param>
        /// <param name="filter">The optional content type filter</param>
        /// <param name="width">The optional width for images</param>
        /// <param name="height">The optional height for images</param>
        /// <returns>The list model</returns>
        public async Task <MediaListModel> GetList(Guid?folderId = null, MediaType?filter = null, int?width = null, int?height = null)
        {
            var model = new MediaListModel
            {
                CurrentFolderId = folderId,
                ParentFolderId  = null,
                Structure       = await _api.Media.GetStructureAsync()
            };

            model.CurrentFolderBreadcrumb = await GetFolderBreadCrumb(model.Structure, folderId);

            model.RootCount  = model.Structure.MediaCount;
            model.TotalCount = model.Structure.TotalCount;

            if (folderId.HasValue)
            {
                var partial = model.Structure.GetPartial(folderId, true);

                if (partial.FirstOrDefault()?.MediaCount == 0 && partial.FirstOrDefault()?.FolderCount == 0)
                {
                    model.CanDelete = true;
                }
            }

            if (folderId.HasValue)
            {
                var folder = await _api.Media.GetFolderByIdAsync(folderId.Value);

                if (folder != null)
                {
                    model.CurrentFolderName = folder.Name;
                    model.ParentFolderId    = folder.ParentId;
                }
            }

            var holdMedia = (await _api.Media.GetAllByFolderIdAsync(folderId));

            if (filter.HasValue)
            {
                holdMedia = holdMedia
                            .Where(m => m.Type == filter.Value);
            }
            var pairMedia = holdMedia.Select(m => new { media = m, mediaItem = new MediaListModel.MediaItem
                                                        {
                                                            Id           = m.Id,
                                                            FolderId     = m.FolderId,
                                                            Type         = m.Type.ToString(),
                                                            Filename     = m.Filename,
                                                            PublicUrl    = m.PublicUrl.TrimStart('~'), //Will only enumerate the start of the string, probably a faster operation.
                                                            ContentType  = m.ContentType,
                                                            Title        = m.Title,
                                                            AltText      = m.AltText,
                                                            Description  = m.Description,
                                                            Properties   = m.Properties.ToArray().OrderBy(p => p.Key).ToList(),
                                                            Size         = Utils.FormatByteSize(m.Size),
                                                            Width        = m.Width,
                                                            Height       = m.Height,
                                                            LastModified = m.LastModified.ToString("yyyy-MM-dd")
                                                        } }).ToArray();

            model.Folders = model.Structure.GetPartial(folderId)
                            .Select(f => new MediaListModel.FolderItem
            {
                Id        = f.Id,
                Name      = f.Name,
                ItemCount = f.MediaCount
            }).ToList();

            if (width.HasValue)
            {
                foreach (var mp in pairMedia.Where(m => m.media.Type == MediaType.Image))
                {
                    if (mp.media.Versions.Any(v => v.Width == width && v.Height == height))
                    {
                        mp.mediaItem.AltVersionUrl =
                            (await _api.Media.EnsureVersionAsync(mp.media, width.Value, height).ConfigureAwait(false))
                            .TrimStart('~');
                    }
                }
            }

            model.Media    = pairMedia.Select(m => m.mediaItem).ToList();
            model.ViewMode = model.Media.Count(m => m.Type == "Image") > model.Media.Count / 2 ? MediaListModel.GalleryView : MediaListModel.ListView;

            return(model);
        }
Пример #27
0
        public virtual async Task <IActionResult> List(MediaListModel model, string viewName = "_List_Media")
        {
            IQueryable <MediaObject> media = _db.Media.AsQueryable();

            if (model.GenericFileType.HasValue)
            {
                media = media.Where(m => m.GenericFileType == model.GenericFileType);
            }
            else
            {
                media = media.Where(m => m.GenericFileType != GenericFileType.Directory);
            }

            if (model.DirectoryId.HasValue)
            {
                media = media.Where(m => m.DirectoryId == model.DirectoryId);
            }
            else
            {
                IEnumerable <MediaDirectory> userDirs = GetDirectoriesForCurrentUser();
                IEnumerable <int>            tree     = _directoryManager.GetAllCategoriesIncludingChildren(userDirs).Select(d => d.Id);
                media = media.Where(n => n.DirectoryId.HasValue && tree.Contains(n.DirectoryId.Value));
            }

            if (model.UserId.IsSet())
            {
                media = media.Where(n => n.Directory.OwnerId == model.UserId);
            }

            if (model.Search.IsSet())
            {
                media = media.Where(m =>
                                    m.Filename.Contains(model.Search) ||
                                    m.FileType.Contains(model.Search)
                                    );
            }

            switch (model.Order)
            {
            case "Size":
                media = media.OrderBy(n => n.FileSize);
                break;

            case "Filename":
                media = media.OrderBy(n => n.Filename);
                break;

            case "Date":
                media = media.OrderBy(n => n.CreatedOn);
                break;

            case "SizeDesc":
                media = media.OrderByDescending(n => n.FileSize);
                break;

            case "FilenameDesc":
                media = media.OrderByDescending(n => n.Filename);
                break;

            case "DateDesc":
                media = media.OrderByDescending(n => n.CreatedOn);
                break;

            default:
                media = media.OrderByDescending(n => n.CreatedOn);
                break;
            }

            await model.ReloadAsync(media);

            model.TopLevelDirectories = GetDirectoriesForCurrentUser();
            return(View(viewName, model));
        }
Пример #28
0
        public ActionResult mediaType(string type)
        {
            MediaListModel model = service.GetMediaByType(type);

            return(View(model));
        }
Пример #29
0
        public ActionResult Category(string category)
        {
            MediaListModel model = service.GetMediaByCategory(category);

            return(View(model));
        }
Пример #30
0
 public virtual IActionResult Directories(MediaListModel model)
 {
     model.TopLevelDirectories = GetDirectoriesForCurrentUser();
     return(View("_List_Directories", model));
 }