aboutsummaryrefslogtreecommitdiff
path: root/Emby.Naming/Video/VideoListResolver.cs
blob: ed7d511a395912ba2726da82921d89aaec425a79 (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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Common;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;

namespace Emby.Naming.Video
{
    /// <summary>
    /// Resolves alternative versions and extras from list of video files.
    /// </summary>
    public static class VideoListResolver
    {
        /// <summary>
        /// Resolves alternative versions and extras from list of video files.
        /// </summary>
        /// <param name="files">List of related video files.</param>
        /// <param name="namingOptions">The naming options.</param>
        /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param>
        /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns>
        public static IEnumerable<VideoInfo> Resolve(IEnumerable<FileSystemMetadata> files, NamingOptions namingOptions, bool supportMultiVersion = true)
        {
            var videoInfos = files
                .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, namingOptions))
                .OfType<VideoFileInfo>()
                .ToList();

            // Filter out all extras, otherwise they could cause stacks to not be resolved
            // See the unit test TestStackedWithTrailer
            var nonExtras = videoInfos
                .Where(i => i.ExtraType == null)
                .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });

            var stackResult = new StackResolver(namingOptions)
                .Resolve(nonExtras).ToList();

            var remainingFiles = videoInfos
                .Where(i => !stackResult.Any(s => i.Path != null && s.ContainsFile(i.Path, i.IsDirectory)))
                .ToList();

            var list = new List<VideoInfo>();

            foreach (var stack in stackResult)
            {
                var info = new VideoInfo(stack.Name)
                {
                    Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions))
                        .OfType<VideoFileInfo>()
                        .ToList()
                };

                info.Year = info.Files[0].Year;

                var extras = ExtractExtras(remainingFiles, stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0].AsSpan()), namingOptions.VideoFlagDelimiters);

                if (extras.Count > 0)
                {
                    info.Extras = extras;
                }

                list.Add(info);
            }

            var standaloneMedia = remainingFiles
                .Where(i => i.ExtraType == null)
                .ToList();

            foreach (var media in standaloneMedia)
            {
                var info = new VideoInfo(media.Name) { Files = new[] { media } };

                info.Year = info.Files[0].Year;

                remainingFiles.Remove(media);
                var extras = ExtractExtras(remainingFiles, media.FileNameWithoutExtension, namingOptions.VideoFlagDelimiters);

                info.Extras = extras;

                list.Add(info);
            }

            if (supportMultiVersion)
            {
                list = GetVideosGroupedByVersion(list, namingOptions);
            }

            // If there's only one resolved video, use the folder name as well to find extras
            if (list.Count == 1)
            {
                var info = list[0];
                var videoPath = list[0].Files[0].Path;
                var parentPath = Path.GetDirectoryName(videoPath.AsSpan());

                if (!parentPath.IsEmpty)
                {
                    var folderName = Path.GetFileName(parentPath);
                    if (!folderName.IsEmpty)
                    {
                        var extras = ExtractExtras(remainingFiles, folderName, namingOptions.VideoFlagDelimiters);
                        extras.AddRange(info.Extras);
                        info.Extras = extras;
                    }
                }

                // Add the extras that are just based on file name as well
                var extrasByFileName = remainingFiles
                    .Where(i => i.ExtraRule != null && i.ExtraRule.RuleType == ExtraRuleType.Filename)
                    .ToList();

                remainingFiles = remainingFiles
                    .Except(extrasByFileName)
                    .ToList();

                extrasByFileName.AddRange(info.Extras);
                info.Extras = extrasByFileName;
            }

            // If there's only one video, accept all trailers
            // Be lenient because people use all kinds of mishmash conventions with trailers.
            if (list.Count == 1)
            {
                var trailers = remainingFiles
                    .Where(i => i.ExtraType == ExtraType.Trailer)
                    .ToList();

                trailers.AddRange(list[0].Extras);
                list[0].Extras = trailers;

                remainingFiles = remainingFiles
                    .Except(trailers)
                    .ToList();
            }

            // Whatever files are left, just add them
            list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name)
            {
                Files = new[] { i },
                Year = i.Year
            }));

            return list;
        }

        private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, NamingOptions namingOptions)
        {
            if (videos.Count == 0)
            {
                return videos;
            }

            var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan()));

            if (folderName.Length <= 1 || !HaveSameYear(videos))
            {
                return videos;
            }

            // Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if]
            for (var i = 0; i < videos.Count; i++)
            {
                var video = videos[i];
                if (!IsEligibleForMultiVersion(folderName, video.Files[0].Path, namingOptions))
                {
                    return videos;
                }
            }

            // The list is created and overwritten in the caller, so we are allowed to do in-place sorting
            videos.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));

            var list = new List<VideoInfo>
            {
                videos[0]
            };

            var alternateVersionsLen = videos.Count - 1;
            var alternateVersions = new VideoFileInfo[alternateVersionsLen];
            var extras = new List<VideoFileInfo>(list[0].Extras);
            for (int i = 0; i < alternateVersionsLen; i++)
            {
                var video = videos[i + 1];
                alternateVersions[i] = video.Files[0];
                extras.AddRange(video.Extras);
            }

            list[0].AlternateVersions = alternateVersions;
            list[0].Name = folderName.ToString();
            list[0].Extras = extras;

            return list;
        }

        private static bool HaveSameYear(IReadOnlyList<VideoInfo> videos)
        {
            if (videos.Count == 1)
            {
                return true;
            }

            var firstYear = videos[0].Year ?? -1;
            for (var i = 1; i < videos.Count; i++)
            {
                if ((videos[i].Year ?? -1) != firstYear)
                {
                    return false;
                }
            }

            return true;
        }

        private static bool IsEligibleForMultiVersion(ReadOnlySpan<char> folderName, string testFilePath, NamingOptions namingOptions)
        {
            var testFilename = Path.GetFileNameWithoutExtension(testFilePath.AsSpan());
            if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // Remove the folder name before cleaning as we don't care about cleaning that part
            if (folderName.Length <= testFilename.Length)
            {
                testFilename = testFilename[folderName.Length..].Trim();
            }

            // There are no span overloads for regex unfortunately
            var tmpTestFilename = testFilename.ToString();
            if (CleanStringParser.TryClean(tmpTestFilename, namingOptions.CleanStringRegexes, out var cleanName))
            {
                tmpTestFilename = cleanName.Trim().ToString();
            }

            // The CleanStringParser should have removed common keywords etc.
            return string.IsNullOrEmpty(tmpTestFilename)
                   || testFilename[0] == '-'
                   || Regex.IsMatch(tmpTestFilename, @"^\[([^]]*)\]", RegexOptions.Compiled);
        }

        private static ReadOnlySpan<char> TrimFilenameDelimiters(ReadOnlySpan<char> name, ReadOnlySpan<char> videoFlagDelimiters)
        {
            return name.IsEmpty ? name : name.TrimEnd().TrimEnd(videoFlagDelimiters).TrimEnd();
        }

        private static bool StartsWith(ReadOnlySpan<char> fileName, ReadOnlySpan<char> baseName, ReadOnlySpan<char> trimmedBaseName)
        {
            if (baseName.IsEmpty)
            {
                return false;
            }

            return fileName.StartsWith(baseName, StringComparison.OrdinalIgnoreCase)
                   || (!trimmedBaseName.IsEmpty && fileName.StartsWith(trimmedBaseName, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Finds similar filenames to that of [baseName] and removes any matches from [remainingFiles].
        /// </summary>
        /// <param name="remainingFiles">The list of remaining filenames.</param>
        /// <param name="baseName">The base name to use for the comparison.</param>
        /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
        /// <returns>A list of video extras for [baseName].</returns>
        private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> baseName, ReadOnlySpan<char> videoFlagDelimiters)
        {
            return ExtractExtras(remainingFiles, baseName, ReadOnlySpan<char>.Empty, videoFlagDelimiters);
        }

        /// <summary>
        /// Finds similar filenames to that of [firstBaseName] and [secondBaseName] and removes any matches from [remainingFiles].
        /// </summary>
        /// <param name="remainingFiles">The list of remaining filenames.</param>
        /// <param name="firstBaseName">The first base name to use for the comparison.</param>
        /// <param name="secondBaseName">The second base name to use for the comparison.</param>
        /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
        /// <returns>A list of video extras for [firstBaseName] and [secondBaseName].</returns>
        private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> firstBaseName, ReadOnlySpan<char> secondBaseName, ReadOnlySpan<char> videoFlagDelimiters)
        {
            var trimmedFirstBaseName = TrimFilenameDelimiters(firstBaseName, videoFlagDelimiters);
            var trimmedSecondBaseName = TrimFilenameDelimiters(secondBaseName, videoFlagDelimiters);

            var result = new List<VideoFileInfo>();
            for (var pos = remainingFiles.Count - 1; pos >= 0; pos--)
            {
                var file = remainingFiles[pos];
                if (file.ExtraType == null)
                {
                    continue;
                }

                var filename = file.FileNameWithoutExtension;
                if (StartsWith(filename, firstBaseName, trimmedFirstBaseName)
                    || StartsWith(filename, secondBaseName, trimmedSecondBaseName))
                {
                    result.Add(file);
                    remainingFiles.RemoveAt(pos);
                }
            }

            return result;
        }
    }
}