Пример #1
0
 public IEnumerable<BoxSet> GetCollections(User user)
 {
     var folder = GetCollectionsFolder(user.Id.ToString("N"));
     return folder == null ?
         new List<BoxSet>() :
         folder.GetChildren(user, true).OfType<BoxSet>();
 }
Пример #2
0
        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="user">The user.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <exception cref="System.ArgumentException">The path is not valid.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">The path does not exist.</exception>
        public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, User user, IServerApplicationPaths appPaths)
        {
            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            // Strip off trailing slash, but not on drives
            path = path.TrimEnd(Path.DirectorySeparatorChar);
            if (path.EndsWith(":", StringComparison.OrdinalIgnoreCase))
            {
                path += Path.DirectorySeparatorChar;
            }

            var rootFolderPath = user != null ? user.RootFolderPath : appPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            ValidateNewMediaPath(fileSystem, rootFolderPath, path, appPaths);

            var shortcutFilename = Path.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);

            while (File.Exists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
            }

            fileSystem.CreateShortcut(lnk, path);
        }
Пример #3
0
        /// <summary>
        /// Opens the dashboard page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="loggedInUser">The logged in user.</param>
        /// <param name="configurationManager">The configuration manager.</param>
        /// <param name="appHost">The app host.</param>
        /// <param name="logger">The logger.</param>
        public static void OpenDashboardPage(string page, User loggedInUser, IServerConfigurationManager configurationManager, IServerApplicationHost appHost, ILogger logger)
        {
            var url = "http://localhost:" + configurationManager.Configuration.HttpServerPortNumber + "/" +
                      appHost.WebApplicationName + "/dashboard/" + page;

            OpenUrl(url, logger);
        }
Пример #4
0
        protected override IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
        {
            var list = base.GetEligibleChildrenForRecursiveChildren(user).ToList();
            list.AddRange(LibraryManager.RootFolder.VirtualChildren);

            return list;
        }
Пример #5
0
        /// <summary>
        /// Renames the virtual folder.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="newName">The new name.</param>
        /// <param name="user">The user.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <exception cref="System.IO.DirectoryNotFoundException">The media collection does not exist</exception>
        /// <exception cref="System.ArgumentException">There is already a media collection with the name  + newPath + .</exception>
        public static void RenameVirtualFolder(string name, string newName, User user, IServerApplicationPaths appPaths)
        {
            var rootFolderPath = user != null ? user.RootFolderPath : appPaths.DefaultUserViewsPath;

            var currentPath = Path.Combine(rootFolderPath, name);
            var newPath = Path.Combine(rootFolderPath, newName);

            if (!Directory.Exists(currentPath))
            {
                throw new DirectoryNotFoundException("The media collection does not exist");
            }

            if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
            {
                throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
            }
            //Only make a two-phase move when changing capitalization
            if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
            {
                //Create an unique name
                var temporaryName = Guid.NewGuid().ToString();
                var temporaryPath = Path.Combine(rootFolderPath, temporaryName);
                Directory.Move(currentPath,temporaryPath);
                currentPath = temporaryPath;
            }

            Directory.Move(currentPath, newPath);
        }
Пример #6
0
 public DidlBuilder(DeviceProfile profile, User user, IImageProcessor imageProcessor, string serverAddress)
 {
     _profile = profile;
     _imageProcessor = imageProcessor;
     _serverAddress = serverAddress;
     _user = user;
 }
Пример #7
0
        public static IEnumerable<BaseItem> GetPlaylistItems(string playlistMediaType, IEnumerable<BaseItem> inputItems, User user)
        {
            return inputItems.SelectMany(i =>
            {
                var folder = i as Folder;

                if (folder != null)
                {
                    var items = user == null
                        ? folder.GetRecursiveChildren()
                        : folder.GetRecursiveChildren(user, true);

                    items = items
                       .Where(m => !m.IsFolder);

                    if (!folder.IsPreSorted)
                    {
                        items = LibraryManager.Sort(items, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending);
                    }

                    return items;
                }

                return new[] { i };

            }).Where(m =>  string.Equals(m.MediaType, playlistMediaType, StringComparison.OrdinalIgnoreCase));
        }
Пример #8
0
        public IEnumerable<Audio> GetInstantMixFromGenres(IEnumerable<string> genres, User user)
        {
            var genreList = genres.ToList();

            var inputItems = _libraryManager.GetItems(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { typeof(Audio).Name },

                Genres = genreList.ToArray(),

                User = user

            }).Items;

            var genresDictionary = genreList.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);

            return inputItems
                .Cast<Audio>()
                .Select(i => new Tuple<Audio, int>(i, i.Genres.Count(genresDictionary.ContainsKey)))
                .Where(i => i.Item2 > 0)
                .OrderByDescending(i => i.Item2)
                .ThenBy(i => Guid.NewGuid())
                .Select(i => i.Item1)
                .Take(100)
                .OrderBy(i => Guid.NewGuid());
        }
Пример #9
0
        public IDictionary <List <BaseItem>, List <BaseItem> > GetItemsByActor(User user, List <string> actorNames)
        {
            var actors = new List <BaseItem>();

            foreach (var actor in actorNames)
            {
                var actorName  = StringNormalization.ValidateSpeechQueryString(actor);
                var actorQuery = LibraryManager.GetItemsResult(new InternalItemsQuery()
                {
                    IncludeItemTypes = new[] { "Person" },
                    SearchTerm       = actorName,
                    Recursive        = true
                });

                if (actorQuery.TotalRecordCount <= 0)
                {
                    continue;
                }

                actors.Add(actorQuery.Items[0]);
            }

            var query = LibraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { "Series", "Movie" },
                Recursive        = true,
                PersonIds        = actors.Select(a => a.InternalId).ToArray()
            });

            return(new Dictionary <List <BaseItem>, List <BaseItem> >()
            {
                { actors, query.Items.ToList() }
            });
        }
Пример #10
0
        public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable<Series> series)
        {
            // Avoid implicitly captured closure
            var currentUser = user;

            return FilterSeries(request, series)
                .AsParallel()
                .Select(i => GetNextUp(i, currentUser))
                .Where(i => i.Item1 != null)
                .OrderByDescending(i =>
                {
                    var episode = i.Item1;

                    var seriesUserData = _userDataManager.GetUserData(user.Id, episode.Series.GetUserDataKey());

                    if (seriesUserData.IsFavorite)
                    {
                        return 2;
                    }

                    if (seriesUserData.Likes.HasValue)
                    {
                        return seriesUserData.Likes.Value ? 1 : -1;
                    }

                    return 0;
                })
                .ThenByDescending(i => i.Item2)
                .ThenByDescending(i => i.Item1.PremiereDate ?? DateTime.MinValue)
                .Select(i => i.Item1);
        }
Пример #11
0
        public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable<Series> series)
        {
            // Avoid implicitly captured closure
            var currentUser = user;

            return FilterSeries(request, series)
                .AsParallel()
                .Select(i => GetNextUp(i, currentUser))
                // Include if an episode was found, and either the series is not unwatched or the specific series was requested
                .Where(i => i.Item1 != null && (!i.Item3 || !string.IsNullOrWhiteSpace(request.SeriesId)))
                .OrderByDescending(i =>
                {
                    var episode = i.Item1;

                    var seriesUserData = _userDataManager.GetUserData(user.Id, episode.Series.GetUserDataKey());

                    if (seriesUserData.IsFavorite)
                    {
                        return 2;
                    }

                    if (seriesUserData.Likes.HasValue)
                    {
                        return seriesUserData.Likes.Value ? 1 : -1;
                    }

                    return 0;
                })
                .ThenByDescending(i => i.Item2)
                .ThenByDescending(i => i.Item1.PremiereDate ?? DateTime.MinValue)
                .Select(i => i.Item1);
        }
Пример #12
0
        public static string GetUserDistinctValue(User user)
        {
            var channels = user.Policy.EnabledChannels
                .OrderBy(i => i)
                .ToList();

            return string.Join("|", channels.ToArray());
        }
Пример #13
0
        public static string GetViewType(this ICollectionFolder folder, User user)
        {
            if (user.Configuration.PlainFolderViews.Contains(folder.Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
            {
                return null;
            }

            return folder.CollectionType;
        }
Пример #14
0
 public DidlBuilder(DeviceProfile profile, User user, IImageProcessor imageProcessor, string serverAddress, IUserDataManager userDataManager, ILocalizationManager localization)
 {
     _profile = profile;
     _imageProcessor = imageProcessor;
     _serverAddress = serverAddress;
     _userDataManager = userDataManager;
     _localization = localization;
     _user = user;
 }
Пример #15
0
 public override bool IsVisible(User user)
 {
     if (user.Configuration.BlockedChannels.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
     {
         return false;
     }
     
     return base.IsVisible(user);
 }
        public override bool IsVisible(User user)
        {
            if (!GetChildren(user, true).Any())
            {
                return false;
            }

            return base.IsVisible(user);
        }
Пример #17
0
        public IEnumerable<Audio> GetInstantMixFromSong(Audio item, User user)
        {
            var list = new List<Audio>
            {
                item
            };

            return list.Concat(GetInstantMixFromGenres(item.Genres, user));
        }
Пример #18
0
        /// <summary>
        /// Converts a BaseItem to a DTOBaseItem
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="fields">The fields.</param>
        /// <param name="user">The user.</param>
        /// <param name="owner">The owner.</param>
        /// <returns>Task{DtoBaseItem}.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
        {
            var options = new DtoOptions
            {
                Fields = fields
            };

            return GetBaseItemDto(item, options, user, owner);
        }
Пример #19
0
        private IEnumerable<Folder> GetMediaFolders(User user)
        {
            var excludeFolderIds = user.Configuration.ExcludeFoldersFromGrouping.Select(i => new Guid(i)).ToList();

            return user.RootFolder
                .GetChildren(user, true, true)
                .OfType<Folder>()
                .Where(i => !excludeFolderIds.Contains(i.Id) && !IsExcludedFromGrouping(i));
        }
Пример #20
0
        public override bool IsVisible(User user)
        {
            if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }

            return base.IsVisible(user) && HasChildren();
        }
Пример #21
0
        public static IEnumerable<BaseItem> GetPlaylistItems(string playlistMediaType, IEnumerable<BaseItem> inputItems, User user)
        {
            if (user != null)
            {
                inputItems = inputItems.Where(i => i.IsVisible(user));
            }

            return inputItems.SelectMany(i => GetPlaylistItems(i, user))
                .Where(m => string.Equals(m.MediaType, playlistMediaType, StringComparison.OrdinalIgnoreCase));
        }
Пример #22
0
        public override IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
        {
            var result = GetItems(new InternalItemsQuery
            {
                User = user

            }).Result;

            return result.Items;
        }
Пример #23
0
        /// <summary>
        /// Converts a BaseItem to a DTOBaseItem
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="fields">The fields.</param>
        /// <param name="user">The user.</param>
        /// <returns>Task{DtoBaseItem}.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public async Task<BaseItemDto> GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (fields == null)
            {
                throw new ArgumentNullException("fields");
            }

            var dto = new BaseItemDto();

            var tasks = new List<Task>();

            if (fields.Contains(ItemFields.Studios))
            {
                tasks.Add(AttachStudios(dto, item));
            }

            if (fields.Contains(ItemFields.People))
            {
                tasks.Add(AttachPeople(dto, item));
            }

            if (user != null)
            {
                tasks.Add(AttachUserSpecificInfo(dto, item, user, fields));
            }

            if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
            {
                try
                {
                    await AttachPrimaryImageAspectRatio(dto, item, _logger).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
                    _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
                }
            }

            AttachBasicFields(dto, item, fields);

            // Make sure all the tasks we kicked off have completed.
            if (tasks.Count > 0)
            {
                await Task.WhenAll(tasks).ConfigureAwait(false);
            }

            return dto;
        }
Пример #24
0
        public QueryResult <BaseItem> GetItemsResult(long id, string[] types, User user)
        {
            var result = LibraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                Parent           = LibraryManager.GetItemById(id),
                IncludeItemTypes = types,
                Recursive        = true
            });

            return(result);
        }
Пример #25
0
        public override IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
        {
            var result = GetUserItems(new UserItemsQuery
            {
                User = user,
                Recursive = true

            }).Result;

            return result.Items;
        }
Пример #26
0
        public override IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
        {
            var items = GetPlayableItems(user);

            if (filter != null)
            {
                items = items.Where(filter);
            }

            return items;
        }
Пример #27
0
        public IEnumerable<Audio> GetInstantMixFromPlaylist(Playlist item, User user)
        {
            var genres = item
               .GetRecursiveChildren(user, i => i is Audio)
               .Cast<Audio>()
               .SelectMany(i => i.Genres)
               .Concat(item.Genres)
               .DistinctNames();

            return GetInstantMixFromGenres(genres, user);
        }
Пример #28
0
        public ControlHandler(ILogger logger, ILibraryManager libraryManager, DeviceProfile profile, string serverAddress, IImageProcessor imageProcessor, IUserDataManager userDataManager, User user, int systemUpdateId, IServerConfigurationManager config)
            : base(config, logger)
        {
            _libraryManager = libraryManager;
            _userDataManager = userDataManager;
            _user = user;
            _systemUpdateId = systemUpdateId;
            _profile = profile;

            _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, userDataManager);
        }
Пример #29
0
        public override IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
        {
            var items = GetPlayableItems(user).Result;

            if (query != null)
            {
                items = items.Where(i => UserViewBuilder.FilterItem(i, query));
            }

            return items;
        }
Пример #30
0
        public IEnumerable<Audio> GetInstantMixFromAlbum(MusicAlbum item, User user)
        {
            var genres = item
               .RecursiveChildren
               .OfType<Audio>()
               .SelectMany(i => i.Genres)
               .Concat(item.Genres)
               .Distinct(StringComparer.OrdinalIgnoreCase);

            return GetInstantMixFromGenres(genres, user);
        }
Пример #31
0
        public IEnumerable<Audio> GetInstantMixFromArtist(MusicArtist artist, User user)
        {
            var genres = user.RootFolder
                .GetRecursiveChildren(user, i => i is Audio)
                .Cast<Audio>()
                .Where(i => i.HasAnyArtist(artist.Name))
                .SelectMany(i => i.Genres)
                .Concat(artist.Genres)
                .Distinct(StringComparer.OrdinalIgnoreCase);

            return GetInstantMixFromGenres(genres, user);
        }
Пример #32
0
        public override IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
        {
            var result = GetItems(new InternalItemsQuery
            {
                User = user,
                Recursive = true,
                Filter = filter

            }).Result;

            return result.Items;
        }
Пример #33
0
        public List <BaseItem> GetEpisodes(int seasonNumber, BaseItem series, User user)
        {
            var result = LibraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                Parent            = series,
                IncludeItemTypes  = new[] { "Episode" },
                ParentIndexNumber = seasonNumber,
                Recursive         = true
            });

            ServerController.Instance.Log.Info($"Episodes Found: {result.TotalRecordCount}");
            return(result.Items.ToList());
        }
Пример #34
0
        public object Get(GetUserReport request)
        {
            DateTime end_date;

            if (string.IsNullOrEmpty(request.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + request.end_date);
                end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            List <Dictionary <string, object> > report = Repository.GetUserReport(request.days, end_date);

            foreach (var user_info in report)
            {
                string user_id   = (string)user_info["user_id"];
                string user_name = "Not Known";
                Guid   user_guid = new Guid(user_id);
                MediaBrowser.Controller.Entities.User user = _userManager.GetUserById(user_guid);
                if (user != null)
                {
                    user_name = user.Name;
                }
                user_info.Add("user_name", user_name);

                DateTime last_seen = (DateTime)user_info["latest_date"];
                TimeSpan time_ago  = DateTime.Now.Subtract(last_seen);

                string last_seen_string = GetLastSeenString(time_ago);
                if (last_seen_string == "")
                {
                    last_seen_string = "just now";
                }
                user_info.Add("last_seen", last_seen_string);

                int      seconds    = (int)user_info["total_time"];
                TimeSpan total_time = new TimeSpan(10000000L * (long)seconds);

                string time_played = GetLastSeenString(total_time);
                if (time_played == "")
                {
                    time_played = "< 1 minute";
                }
                user_info.Add("total_play_time", time_played);
            }

            return(report);
        }
Пример #35
0
        public object Get(GetBreakdownReport request)
        {
            AuthorizationInfo user_info = _ac.GetAuthorizationInfo(Request);
            UserPolicy        policy    = _userManager.GetUserPolicy(user_info.User);

            if (!policy.IsAdministrator)
            {
                return(new List <Dictionary <string, object> >());
            }

            DateTime end_date;

            if (string.IsNullOrEmpty(request.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + request.end_date);
                end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            List <Dictionary <string, object> > report = repository.GetBreakdownReport(request.user_id, request.days, end_date, request.BreakdownType);

            if (request.BreakdownType == "UserId")
            {
                foreach (var row in report)
                {
                    string user_id = row["label"] as string;
                    MediaBrowser.Controller.Entities.User user = null;
                    if (!string.IsNullOrEmpty(user_id))
                    {
                        Guid user_guid = new Guid(user_id);
                        user = _userManager.GetUserById(user_guid);
                    }

                    if (user != null)
                    {
                        row["label"] = user.Name;
                    }
                    else
                    {
                        row["label"] = "unknown";
                    }
                }
            }

            return(report);
        }
Пример #36
0
        public IEnumerable <BaseItem> GetLatestTv(User user, DateTime duration)
        {
            // Duration can be request from the user, but will default to anything add in the last 25 days.
            var results = LibraryManager.GetItemIds(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { "Episode" },
                User             = user,
                MinDateCreated   = duration,
                IsPlayed         = false,
                EnableAutoSort   = true,
                OrderBy          = new[] { ItemSortBy.DateCreated }.Select(i => new ValueTuple <string, SortOrder>(i, SortOrder.Descending)).ToArray()
            });

            return(results.Select(id => LibraryManager.GetItemById(id).Parent.Parent).Distinct().ToList());
        }
Пример #37
0
        public Dictionary <BaseItem, List <BaseItem> > GetCollectionItems(User user, string collectionName)
        {
            var result        = QuerySpeechResultItem(collectionName, new[] { "BoxSet", "Collection" });
            var users         = UserManager.Users;
            var administrator = users.FirstOrDefault(u => u.Policy.IsAdministrator);
            var collection    = LibraryManager.QueryItems(new InternalItemsQuery(administrator)
            {
                CollectionIds  = new[] { result.InternalId },
                EnableAutoSort = true,
                OrderBy        = new[] { ItemSortBy.PremiereDate }.Select(i => new ValueTuple <string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
            });

            return(new Dictionary <BaseItem, List <BaseItem> >()
            {
                { result, collection.Items.ToList() }
            });
        }
Пример #38
0
        public BaseItem GetNextUpEpisode(string seriesName, User user)
        {
            try
            {
                var id     = QuerySpeechResultItem(seriesName, new[] { "Series" }).InternalId;
                var nextUp = TvSeriesManager.GetNextUp(new NextUpQuery()
                {
                    SeriesId = id,
                    UserId   = user.InternalId
                }, user, new DtoOptions());

                return(nextUp.Items.FirstOrDefault());
            }
            catch
            {
                return(null); //Return null and handle no next up episodes in Alexa Response
            }
        }
Пример #39
0
        public object Get(GetBreakdownReport request)
        {
            DateTime end_date;

            if (string.IsNullOrEmpty(request.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + request.end_date);
                end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            List <Dictionary <string, object> > report = Repository.GetBreakdownReport(request.days, end_date, request.BreakdownType);

            if (request.BreakdownType == "UserId")
            {
                foreach (var row in report)
                {
                    string user_id   = row["label"] as string;
                    Guid   user_guid = new Guid(user_id);
                    MediaBrowser.Controller.Entities.User user = _userManager.GetUserById(user_guid);

                    if (user != null)
                    {
                        row["label"] = user.Name;
                    }
                    else
                    {
                        row["label"] = "unknown";
                    }
                }
            }

            return(report);
        }
Пример #40
0
        public object Get(GetUserPlaylist request)
        {
            AuthorizationInfo user_info = _ac.GetAuthorizationInfo(Request);
            UserPolicy        policy    = _userManager.GetUserPolicy(user_info.User);

            if (!policy.IsAdministrator)
            {
                return(new List <Dictionary <string, object> >());
            }

            DateTime end_date;

            if (string.IsNullOrEmpty(request.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + request.end_date);
                end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            List <Dictionary <string, object> > report = repository.GetUserPlayListReport(request.days, end_date, request.user_id, request.filter_name, request.aggregate_data, null);

            foreach (var row in report)
            {
                string user_id = row["user"] as string;
                MediaBrowser.Controller.Entities.User user = null;
                if (!string.IsNullOrEmpty(user_id))
                {
                    Guid user_guid = new Guid(user_id);
                    user = _userManager.GetUserById(user_guid);
                }

                if (user != null)
                {
                    row["user"] = user.Name;
                }
                else
                {
                    row["user"] = "******";
                }
            }

            /*
             * Dictionary<string, object> row_data = new Dictionary<string, object>();
             * row_data.Add("date", "2018-01-10");
             * row_data.Add("name", "The Last Moon Man");
             * row_data.Add("type", "Movie");
             * row_data.Add("duration", 2567);
             * report.Add(row_data);
             *
             * row_data = new Dictionary<string, object>();
             * row_data.Add("date", "2018-01-10");
             * row_data.Add("name", "Hight Up There");
             * row_data.Add("type", "Movie");
             * row_data.Add("duration", 3654);
             * report.Add(row_data);
             */

            return(report);
        }
Пример #41
0
        public object Get(GetUserReport request)
        {
            AuthorizationInfo auth_user_info = _ac.GetAuthorizationInfo(Request);
            UserPolicy        policy         = _userManager.GetUserPolicy(auth_user_info.User);

            if (!policy.IsAdministrator)
            {
                return(new List <Dictionary <string, object> >());
            }

            DateTime end_date;

            if (string.IsNullOrEmpty(request.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + request.end_date);
                end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            List <Dictionary <string, object> > report = repository.GetUserReport(request.days, end_date);

            foreach (var user_info in report)
            {
                string user_id   = (string)user_info["user_id"];
                string user_name = "Not Known";
                bool   has_image = false;
                MediaBrowser.Controller.Entities.User user = null;
                if (!string.IsNullOrEmpty(user_id))
                {
                    Guid user_guid = new Guid(user_id);
                    user = _userManager.GetUserById(user_guid);
                }

                if (user != null)
                {
                    user_name = user.Name;
                    has_image = user.HasImage(MediaBrowser.Model.Entities.ImageType.Primary);
                }
                user_info.Add("user_name", user_name);
                user_info.Add("has_image", has_image);

                DateTime last_seen = (DateTime)user_info["latest_date"];
                TimeSpan time_ago  = DateTime.Now.Subtract(last_seen);

                string last_seen_string = GetLastSeenString(time_ago);
                if (last_seen_string == "")
                {
                    last_seen_string = "just now";
                }
                user_info.Add("last_seen", last_seen_string);

                int      seconds    = (int)user_info["total_time"];
                TimeSpan total_time = new TimeSpan(10000000L * (long)seconds);

                string time_played = GetLastSeenString(total_time);
                if (time_played == "")
                {
                    time_played = "< 1 minute";
                }
                user_info.Add("total_play_time", time_played);
            }

            return(report);
        }
Пример #42
0
 public override int GetChildCount(User user)
 {
     return(GetChildren(user, true).Count);
 }
Пример #43
0
        public object Get(GetUsageStats activity)
        {
            string[] filter_tokens = new string[0];
            if (activity.filter != null)
            {
                filter_tokens = activity.filter.Split(',');
            }

            DateTime end_date;

            if (string.IsNullOrEmpty(activity.end_date))
            {
                end_date = DateTime.Now;
            }
            else
            {
                _logger.Info("End_Date: " + activity.end_date);
                end_date = DateTime.ParseExact(activity.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            Dictionary <String, Dictionary <string, int> > results = Repository.GetUsageForDays(activity.days, end_date, filter_tokens, activity.data_type);

            // add empty user for labels
            results.Add("labels_user", new Dictionary <string, int>());

            List <Dictionary <string, object> > user_usage_data = new List <Dictionary <string, object> >();

            foreach (string user_id in results.Keys)
            {
                Dictionary <string, int> user_usage = results[user_id];

                // fill in missing dates for time period
                SortedDictionary <string, int> userUsageByDate = new SortedDictionary <string, int>();
                DateTime from_date = end_date.AddDays((activity.days * -1) + 1);
                while (from_date <= end_date)
                {
                    string date_string = from_date.ToString("yyyy-MM-dd");
                    if (user_usage.ContainsKey(date_string) == false)
                    {
                        userUsageByDate.Add(date_string, 0);
                    }
                    else
                    {
                        userUsageByDate.Add(date_string, user_usage[date_string]);
                    }

                    from_date = from_date.AddDays(1);
                }

                string user_name = "Not Known";
                if (user_id == "labels_user")
                {
                    user_name = "labels_user";
                }
                else
                {
                    Guid user_guid = new Guid(user_id);
                    MediaBrowser.Controller.Entities.User user = _userManager.GetUserById(user_guid);
                    if (user != null)
                    {
                        user_name = user.Name;
                    }
                }

                Dictionary <string, object> user_data = new Dictionary <string, object>();
                user_data.Add("user_id", user_id);
                user_data.Add("user_name", user_name);
                user_data.Add("user_usage", userUsageByDate);

                user_usage_data.Add(user_data);
            }

            var sorted_data = user_usage_data.OrderBy(dict => (dict["user_name"] as string).ToLower());

            return(sorted_data);
        }
Пример #44
0
        protected override IEnumerable <BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
        {
            var list = base.GetEligibleChildrenForRecursiveChildren(user).ToList();

            list.AddRange(LibraryManager.RootFolder.VirtualChildren);

            return(list);
        }