summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrakeWPF/Helpers/QueueRecoveryHelper.cs
blob: 072baafc7d379bfc219122e003cb42efac5e7892 (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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="QueueRecoveryHelper.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   Defines the QueueRecoveryHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrakeWPF.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Windows;

    using HandBrake.Interop.Utilities;

    using HandBrakeWPF.Services.Interfaces;
    using HandBrakeWPF.Services.Queue.Model;
    using HandBrakeWPF.Utilities;

    using Newtonsoft.Json;

    using IQueueService = HandBrakeWPF.Services.Queue.Interfaces.IQueueService;

    public class QueueRecoveryHelper
    {
        public static string QueueFileName = "hb_queue";

        /// <summary>
        /// Check if the queue recovery file contains records.
        /// If it does, it means the last queue did not complete before HandBrake closed.
        /// So, return a boolean if true. 
        /// </summary>
        /// <param name="filterQueueFiles">
        /// The filter Queue Files.
        /// </param>
        /// <returns>
        /// True if there is a queue to recover.
        /// </returns>
        public static List<string> CheckQueueRecovery(List<string> filterQueueFiles)
        {
            try
            {
                string tempPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());
                DirectoryInfo info = new DirectoryInfo(tempPath);
                IEnumerable<FileInfo> foundFiles = info.GetFiles("*.json").Where(f => f.Name.StartsWith(QueueFileName));
                var queueFiles = GetFilesExcludingActiveProcesses(foundFiles, filterQueueFiles);

                if (!queueFiles.Any())
                {
                    return queueFiles;
                }        

                List<string> removeFiles = new List<string>();
                List<string> acceptedFiles = new List<string>();


                foreach (string file in queueFiles)
                {
                    try
                    {
                        using (StreamReader stream = new StreamReader(file))
                        {
                            List<QueueTask> list = list = JsonConvert.DeserializeObject<List<QueueTask>>(stream.ReadToEnd());
                            if (list != null && list.Count == 0)
                            {
                                removeFiles.Add(file);
                            }

                            if (list != null && list.Count != 0)
                            {
                                List<QueueTask> tasks = list.Where(l => l.Status != QueueItemStatus.Completed).ToList();
                                if (tasks.Count != 0)
                                {
                                    acceptedFiles.Add(Path.GetFileName(file));
                                }
                                else
                                {
                                    removeFiles.Add(file);
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc);
                    }
                }

                CleanupFiles(removeFiles, false);

                return acceptedFiles;
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc);
                return new List<string>(); // Keep quiet about the error.
            }
        }

        /// <summary>
        /// Recover a queue from file.
        /// </summary>
        /// <param name="encodeQueue">
        /// The encode Queue.
        /// </param>
        /// <param name="errorService">
        /// The error Service.
        /// </param>
        /// <param name="silentRecovery">
        /// The silent Recovery.
        /// </param>
        /// <param name="queueFilter">
        /// The queue Filter.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool RecoverQueue(IQueueService encodeQueue, IErrorService errorService, bool silentRecovery, List<string> queueFilter)
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());
            List<string> queueFiles = CheckQueueRecovery(queueFilter);
            MessageBoxResult result = MessageBoxResult.None;
            if (!silentRecovery)
            {
                if (queueFiles.Count == 1)
                {
                    result =
                        errorService.ShowMessageBox(
                            Properties.Resources.Queue_RecoverQueueQuestionSingular,
                            Properties.Resources.Queue_RecoveryPossible,
                            MessageBoxButton.YesNo,
                            MessageBoxImage.Question);
                }
                else if (queueFiles.Count > 1)
                {
                    result =
                        errorService.ShowMessageBox(
                            Properties.Resources.Queue_RecoverQueueQuestionPlural,
                            Properties.Resources.Queue_RecoveryPossible,
                            MessageBoxButton.YesNo,
                            MessageBoxImage.Question);
                }
            }
            else
            {
                result = MessageBoxResult.Yes;
            }

            if (result == MessageBoxResult.Yes)
            {
                bool isRecovered = false;
                foreach (string file in queueFiles)
                {
                    // Recover the Queue
                    encodeQueue.RestoreQueue(Path.Combine(appDataPath, file));
                    isRecovered = true;

                    // Cleanup
                    CleanupFiles(new List<string> { file }, false);                   
                }

                return isRecovered;
            }

            CleanupFiles(queueFiles, true);
            return false;
        }

        public static bool ArchivesExist()
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());
            DirectoryInfo info = new DirectoryInfo(appDataPath);
            IEnumerable<FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName));

            return foundFiles.Any();
        }

        private static List<string> GetFilesExcludingActiveProcesses(IEnumerable<FileInfo> foundFiles, List<string> filterQueueFiles)
        {
            List<string> queueFiles = new List<string>();

            // Remove any files where we have an active instnace.
            foreach (FileInfo file in foundFiles)
            {
                string fileProcessId = file.Name.Replace(QueueFileName, string.Empty).Replace(".json", string.Empty);
                int processId;
                if (!string.IsNullOrEmpty(fileProcessId) && int.TryParse(fileProcessId, out processId))
                {
                    if (!GeneralUtilities.IsPidACurrentHandBrakeInstance(processId))
                    {
                        if (filterQueueFiles != null && filterQueueFiles.Count > 0)
                        {
                            if (filterQueueFiles.Contains(processId.ToString()))
                            {
                                queueFiles.Add(file.FullName);
                            }
                        }
                        else
                        {
                            queueFiles.Add(file.FullName);
                        }                       
                    }
                }
            }

            return queueFiles;
        }

        private static void CleanupFiles(List<string> removeFiles, bool archive)
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());

            // Cleanup old/unused queue files for now.
            foreach (string file in removeFiles)
            {
                Match m = Regex.Match(file, @"([0-9]+).json");
                if (m.Success)
                {
                    int processId = int.Parse(m.Groups[1].ToString());
                    if (GeneralUtilities.IsPidACurrentHandBrakeInstance(processId))
                    {
                        continue;
                    }
                }

                string fullPath = Path.Combine(appDataPath, file);

                if (archive)
                {
                    File.Move(fullPath, fullPath + ".archive");
                }
                else
                {
                    File.Delete(fullPath);
                }      
            }

            TidyArchiveFiles();
        }

        /// <summary>
        /// Tidy up archive files older than 7 days.
        /// Gives the user an opportunity to recover a queue file they accidentally chose not to import. 
        /// </summary>
        private static void TidyArchiveFiles()
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());
            DirectoryInfo info = new DirectoryInfo(appDataPath);
            IEnumerable<FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName));

            DateTime lastWeek = DateTime.Now.AddDays(-7);

            foreach (FileInfo file in foundFiles)
            {
                if (file.CreationTime < lastWeek)
                {
                    string fullPath = Path.Combine(appDataPath, file.Name);
                    File.Delete(fullPath);
                }
            }
        }

        public static void ResetArchives()
        {
            string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly());
            DirectoryInfo info = new DirectoryInfo(appDataPath);
            IEnumerable<FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName));
            foreach (FileInfo file in foundFiles)
            {
                string fullPath = Path.Combine(appDataPath, file.Name);
                File.Move(fullPath, fullPath.Replace(".archive", string.Empty));
            }
        }
    }
}