aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Library/UserViewManager.cs
blob: c2518f2b7633614c0efaae5a9df915c9de1cf737 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Localization;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
using MoreLinq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.Library
{
    public class UserViewManager : IUserViewManager
    {
        private readonly ILibraryManager _libraryManager;
        private readonly ILocalizationManager _localizationManager;
        private readonly IUserManager _userManager;

        private readonly IChannelManager _channelManager;
        private readonly ILiveTvManager _liveTvManager;
        private readonly IServerConfigurationManager _config;

        public UserViewManager(ILibraryManager libraryManager, ILocalizationManager localizationManager, IUserManager userManager, IChannelManager channelManager, ILiveTvManager liveTvManager, IServerConfigurationManager config)
        {
            _libraryManager = libraryManager;
            _localizationManager = localizationManager;
            _userManager = userManager;
            _channelManager = channelManager;
            _liveTvManager = liveTvManager;
            _config = config;
        }

        public async Task<IEnumerable<Folder>> GetUserViews(UserViewQuery query, CancellationToken cancellationToken)
        {
            var user = _userManager.GetUserById(query.UserId);

            var folders = user.RootFolder
                .GetChildren(user, true)
                .OfType<Folder>()
                .ToList();

            var plainFolderIds = user.Configuration.PlainFolderViews.Select(i => new Guid(i)).ToList();

            var standaloneFolders = folders
                .Where(i => UserView.IsExcludedFromGrouping(i) || !user.IsFolderGrouped(i.Id))
                .ToList();

            var foldersWithViewTypes = folders
                .Except(standaloneFolders)
                .OfType<ICollectionFolder>()
                .ToList();

            var list = new List<Folder>();

            if (_config.Configuration.EnableUserViews)
            {
                foreach (var folder in standaloneFolders)
                {
                    var collectionFolder = folder as ICollectionFolder;
                    var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType;

                    if (UserView.IsUserSpecific(folder))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false));
                    }
                    else if (plainFolderIds.Contains(folder.Id))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, false, string.Empty, cancellationToken).ConfigureAwait(false));
                    }
                    else if (!string.IsNullOrWhiteSpace(folderViewType))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, cancellationToken).ConfigureAwait(false));
                    }
                    else
                    {
                        list.Add(folder);
                    }
                }
            }
            else
            {
                // TODO: Deprecate this whole block
                foreach (var folder in standaloneFolders)
                {
                    var collectionFolder = folder as ICollectionFolder;
                    var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType;

                    if (UserView.IsUserSpecific(folder))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false));
                    }
                    else if (plainFolderIds.Contains(folder.Id))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, false, string.Empty, user, cancellationToken).ConfigureAwait(false));
                    }
                    else if (!string.IsNullOrWhiteSpace(folderViewType))
                    {
                        list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false));
                    }
                    else
                    {
                        list.Add(folder);
                    }
                }
            }

            var parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user)))
                .ToList();

            if (parents.Count > 0)
            {
                list.Add(await GetUserView(parents, list, CollectionType.TvShows, string.Empty, user, cancellationToken).ConfigureAwait(false));
            }

            parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Music, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user)))
                .ToList();

            if (parents.Count > 0)
            {
                list.Add(await GetUserView(parents, list, CollectionType.Music, string.Empty, user, cancellationToken).ConfigureAwait(false));
            }

            parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Movies, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user)))
               .ToList();

            if (parents.Count > 0)
            {
                list.Add(await GetUserView(parents, list, CollectionType.Movies, string.Empty, user, cancellationToken).ConfigureAwait(false));
            }

            parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Games, StringComparison.OrdinalIgnoreCase))
               .ToList();

            if (parents.Count > 0)
            {
                list.Add(await GetUserView(parents, list, CollectionType.Games, string.Empty, user, cancellationToken).ConfigureAwait(false));
            }

            if (user.Configuration.DisplayFoldersView)
            {
                var name = _localizationManager.GetLocalizedString("ViewType" + CollectionType.Folders);
                list.Add(await _libraryManager.GetNamedView(name, CollectionType.Folders, string.Empty, cancellationToken).ConfigureAwait(false));
            }

            if (query.IncludeExternalContent)
            {
                var channelResult = await _channelManager.GetChannelsInternal(new ChannelQuery
                {
                    UserId = query.UserId

                }, cancellationToken).ConfigureAwait(false);

                var channels = channelResult.Items;

                var embeddedChannels = channels
                    .Where(i => user.Configuration.DisplayChannelsInline || user.Configuration.DisplayChannelsWithinViews.Contains(i.Id.ToString("N")))
                    .ToList();

                list.AddRange(embeddedChannels);

                if (channels.Length > embeddedChannels.Count)
                {
                    list.Add(await _channelManager.GetInternalChannelFolder(cancellationToken).ConfigureAwait(false));
                }

                if (_liveTvManager.GetEnabledUsers().Select(i => i.Id.ToString("N")).Contains(query.UserId))
                {
                    list.Add(await _liveTvManager.GetInternalLiveTvFolder(CancellationToken.None).ConfigureAwait(false));
                }
            }

            var sorted = _libraryManager.Sort(list, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).ToList();

            var orders = user.Configuration.OrderedViews.ToList();

            return list
                .OrderBy(i =>
                {
                    var index = orders.IndexOf(i.Id.ToString("N"));

                    return index == -1 ? int.MaxValue : index;
                })
                .ThenBy(sorted.IndexOf)
                .ThenBy(i => i.SortName);
        }

        public Task<UserView> GetUserSubView(string name, string parentId, string type, string sortName, CancellationToken cancellationToken)
        {
            var uniqueId = parentId + "subview" + type;

            return _libraryManager.GetNamedView(name, parentId, type, sortName, uniqueId, cancellationToken);
        }

        public Task<UserView> GetUserSubView(string parentId, string type, string sortName, CancellationToken cancellationToken)
        {
            var name = _localizationManager.GetLocalizedString("ViewType" + type);

            return GetUserSubView(name, parentId, type, sortName, cancellationToken);
        }

        public async Task<UserView> GetUserView(List<ICollectionFolder> parents, List<Folder> currentViews, string viewType, string sortName, User user, CancellationToken cancellationToken)
        {
            var name = _localizationManager.GetLocalizedString("ViewType" + viewType);
            var enableUserViews = _config.Configuration.EnableUserViews;

            if (parents.Count == 1 && parents.All(i => string.Equals((enableUserViews ? i.GetViewType(user) : i.CollectionType), viewType, StringComparison.OrdinalIgnoreCase)))
            {
                if (!string.IsNullOrWhiteSpace(parents[0].Name))
                {
                    name = parents[0].Name;
                }

                var parentId = parents[0].Id;

                var enableRichView = !user.Configuration.PlainFolderViews.Contains(parentId.ToString("N"), StringComparer.OrdinalIgnoreCase);

                return await GetUserView(parentId, name, viewType, enableRichView, string.Empty, cancellationToken).ConfigureAwait(false);
            }

            return await _libraryManager.GetNamedView(user, name, viewType, sortName, cancellationToken).ConfigureAwait(false);
        }

        public Task<UserView> GetUserView(Guid parentId, string name, string viewType, bool enableRichView, string sortName, User user, CancellationToken cancellationToken)
        {
            viewType = enableRichView ? viewType : null;
            return _libraryManager.GetNamedView(user, name, parentId.ToString("N"), viewType, sortName, null, cancellationToken);
        }

        public Task<UserView> GetUserView(Guid parentId, string name, string viewType, bool enableRichView, string sortName, CancellationToken cancellationToken)
        {
            viewType = enableRichView ? viewType : null;
            return _libraryManager.GetNamedView(name, parentId.ToString("N"), viewType, sortName, null, cancellationToken);
        }

        public List<Tuple<BaseItem, List<BaseItem>>> GetLatestItems(LatestItemsQuery request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var includeTypes = request.IncludeItemTypes;

            var currentUser = user;

            Func<BaseItem, bool> filter = i =>
            {
                if (includeTypes.Length > 0)
                {
                    if (!includeTypes.Contains(i.GetType().Name, StringComparer.OrdinalIgnoreCase))
                    {
                        return false;
                    }
                }

                if (request.IsPlayed.HasValue)
                {
                    var val = request.IsPlayed.Value;
                    if (i is Video && i.IsPlayed(currentUser) != val)
                    {
                        return false;
                    }
                }

                return i.LocationType != LocationType.Virtual && !i.IsFolder;
            };

            // Avoid implicitly captured closure
            var libraryItems = string.IsNullOrEmpty(request.ParentId) && user != null ?
                GetItemsConfiguredForLatest(user, filter) :
                GetAllLibraryItems(request.UserId, _userManager, _libraryManager, request.ParentId, filter);

            libraryItems = libraryItems.OrderByDescending(i => i.DateCreated);

            if (request.IsPlayed.HasValue)
            {
                var takeLimit = (request.Limit ?? 20) * 20;
                libraryItems = libraryItems.Take(takeLimit);
            }

            // Avoid implicitly captured closure
            var items = libraryItems
                .ToList();

            var list = new List<Tuple<BaseItem, List<BaseItem>>>();

            foreach (var item in items)
            {
                // Only grab the index container for media
                var container = item.IsFolder || !request.GroupItems ? null : item.LatestItemsIndexContainer;

                if (container == null)
                {
                    list.Add(new Tuple<BaseItem, List<BaseItem>>(null, new List<BaseItem> { item }));
                }
                else
                {
                    var current = list.FirstOrDefault(i => i.Item1 != null && i.Item1.Id == container.Id);

                    if (current != null)
                    {
                        current.Item2.Add(item);
                    }
                    else
                    {
                        list.Add(new Tuple<BaseItem, List<BaseItem>>(container, new List<BaseItem> { item }));
                    }
                }

                if (list.Count >= request.Limit)
                {
                    break;
                }
            }

            return list;
        }

        protected IList<BaseItem> GetAllLibraryItems(string userId, IUserManager userManager, ILibraryManager libraryManager, string parentId, Func<BaseItem, bool> filter)
        {
            if (!string.IsNullOrEmpty(parentId))
            {
                var folder = (Folder)libraryManager.GetItemById(new Guid(parentId));

                if (!string.IsNullOrWhiteSpace(userId))
                {
                    var user = userManager.GetUserById(userId);

                    if (user == null)
                    {
                        throw new ArgumentException("User not found");
                    }

                    return folder
                        .GetRecursiveChildren(user, filter)
                        .ToList();
                }

                return folder
                    .GetRecursiveChildren(filter);
            }
            if (!string.IsNullOrWhiteSpace(userId))
            {
                var user = userManager.GetUserById(userId);

                if (user == null)
                {
                    throw new ArgumentException("User not found");
                }

                return user
                    .RootFolder
                    .GetRecursiveChildren(user, filter)
                    .ToList();
            }

            return libraryManager
                .RootFolder
                .GetRecursiveChildren(filter);
        }

        private IEnumerable<BaseItem> GetItemsConfiguredForLatest(User user, Func<BaseItem, bool> filter)
        {
            // Avoid implicitly captured closure
            var currentUser = user;

            return user.RootFolder.GetChildren(user, true)
                .OfType<Folder>()
                .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N")))
                .SelectMany(i => i.GetRecursiveChildren(currentUser, filter))
                .DistinctBy(i => i.Id);
        }
    }
}