aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/ScheduledTasks/ImageCleanupTask.cs
blob: 8dd0895c96143a7b11f653a5a37a430a51e1874f (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
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Controller.ScheduledTasks
{
    /// <summary>
    /// Class ImageCleanupTask
    /// </summary>
    public class ImageCleanupTask : BaseScheduledTask<Kernel>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageCleanupTask" /> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="logger"></param>
        public ImageCleanupTask(Kernel kernel, ITaskManager taskManager, ILogger logger)
            : base(kernel, taskManager, logger)
        {
        }

        /// <summary>
        /// Creates the triggers that define when the task will run
        /// </summary>
        /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
        protected override IEnumerable<BaseTaskTrigger> GetDefaultTriggers()
        {
            return new BaseTaskTrigger[]
                {
                    new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) }
                };
        }

        /// <summary>
        /// Returns the task to be executed
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task.</returns>
        protected override async Task ExecuteInternal(CancellationToken cancellationToken, IProgress<double> progress)
        {
            await EnsureChapterImages(cancellationToken).ConfigureAwait(false);

            // First gather all image files
            var files = GetFiles(Kernel.FFMpegManager.AudioImagesDataPath)
                .Concat(GetFiles(Kernel.FFMpegManager.VideoImagesDataPath))
                .Concat(GetFiles(Kernel.ProviderManager.ImagesDataPath))
                .ToList();

            // Now gather all items
            var items = Kernel.RootFolder.RecursiveChildren.ToList();
            items.Add(Kernel.RootFolder);

            // Determine all possible image paths
            var pathsInUse = items.SelectMany(GetPathsInUse)
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToDictionary(p => p, StringComparer.OrdinalIgnoreCase);

            var numComplete = 0;

            var tasks = files.Select(file => Task.Run(() =>
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (!pathsInUse.ContainsKey(file))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    
                    try
                    {
                        File.Delete(file);
                    }
                    catch (IOException ex)
                    {
                        Logger.ErrorException("Error deleting {0}", ex, file);
                    }
                }

                // Update progress
                lock (progress)
                {
                    numComplete++;
                    double percent = numComplete;
                    percent /= files.Count;

                    progress.Report(100 * percent);
                }
            }));

            await Task.WhenAll(tasks).ConfigureAwait(false);
        }

        /// <summary>
        /// Ensures the chapter images.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private Task EnsureChapterImages(CancellationToken cancellationToken)
        {
            var videos = Kernel.RootFolder.RecursiveChildren.OfType<Video>().Where(v => v.Chapters != null).ToList();

            var tasks = videos.Select(v => Task.Run(async () =>
            {
                await Kernel.FFMpegManager.PopulateChapterImages(v, cancellationToken, false, true);
            }));

            return Task.WhenAll(tasks);
        }

        /// <summary>
        /// Gets the paths in use.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>IEnumerable{System.String}.</returns>
        private IEnumerable<string> GetPathsInUse(BaseItem item)
        {
            IEnumerable<string> images = new List<string> { };

            if (item.Images != null)
            {
                images = images.Concat(item.Images.Values);
            }

            if (item.BackdropImagePaths != null)
            {
                images = images.Concat(item.BackdropImagePaths);
            }

            if (item.ScreenshotImagePaths != null)
            {
                images = images.Concat(item.ScreenshotImagePaths);
            }

            var video = item as Video;

            if (video != null && video.Chapters != null)
            {
                images = images.Concat(video.Chapters.Where(i => !string.IsNullOrEmpty(i.ImagePath)).Select(i => i.ImagePath));
            }

            if (item.LocalTrailers != null)
            {
                foreach (var subItem in item.LocalTrailers)
                {
                    images = images.Concat(GetPathsInUse(subItem));
                }
            }

            var movie = item as Movie;

            if (movie != null && movie.SpecialFeatures != null)
            {
                foreach (var subItem in movie.SpecialFeatures)
                {
                    images = images.Concat(GetPathsInUse(subItem));
                }
            }
            
            return images;
        }

        /// <summary>
        /// Gets the files.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>IEnumerable{System.String}.</returns>
        private IEnumerable<string> GetFiles(string path)
        {
            return Directory.EnumerateFiles(path, "*.jpg", SearchOption.AllDirectories).Concat(Directory.EnumerateFiles(path, "*.png", SearchOption.AllDirectories));
        }

        /// <summary>
        /// Gets the name of the task
        /// </summary>
        /// <value>The name.</value>
        public override string Name
        {
            get { return "Images cleanup"; }
        }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <value>The description.</value>
        public override string Description
        {
            get { return "Deletes downloaded and extracted images that are no longer being used."; }
        }

        /// <summary>
        /// Gets the category.
        /// </summary>
        /// <value>The category.</value>
        public override string Category
        {
            get
            {
                return "Maintenance";
            }
        }
    }
}