aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Data/SqliteFileOrganizationRepository.cs
blob: a7168232997066654f28c651ff630bc4826e1ca4 (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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.FileOrganization;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using SQLitePCL.pretty;

namespace Emby.Server.Implementations.Data
{
    public class SqliteFileOrganizationRepository : BaseSqliteRepository, IFileOrganizationRepository, IDisposable
    {
        private readonly CultureInfo _usCulture = new CultureInfo("en-US");

        public SqliteFileOrganizationRepository(ILogger logger, IServerApplicationPaths appPaths) : base(logger)
        {
            DbFilePath = Path.Combine(appPaths.DataPath, "fileorganization.db");
        }

        /// <summary>
        /// Opens the connection to the database
        /// </summary>
        /// <returns>Task.</returns>
        public void Initialize()
        {
            using (var connection = CreateConnection())
            {
                connection.ExecuteAll(string.Join(";", new[]
                {
                                "pragma default_temp_store = memory",
                                "pragma default_synchronous=Normal",
                                "pragma temp_store = memory",
                                "pragma synchronous=Normal",
                }));

                string[] queries = {

                                "create table if not exists FileOrganizerResults (ResultId GUID PRIMARY KEY, OriginalPath TEXT, TargetPath TEXT, FileLength INT, OrganizationDate datetime, Status TEXT, OrganizationType TEXT, StatusMessage TEXT, ExtractedName TEXT, ExtractedYear int null, ExtractedSeasonNumber int null, ExtractedEpisodeNumber int null, ExtractedEndingEpisodeNumber, DuplicatePaths TEXT int null)",
                                "create index if not exists idx_FileOrganizerResults on FileOrganizerResults(ResultId)"
                               };

                connection.RunQueries(queries);
            }
        }

        public async Task SaveResult(FileOrganizationResult result, CancellationToken cancellationToken)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (var connection = CreateConnection())
            {
                connection.RunInTransaction(db =>
                {
                    var paramList = new List<object>();
                    var commandText = "replace into FileOrganizerResults (ResultId, OriginalPath, TargetPath, FileLength, OrganizationDate, Status, OrganizationType, StatusMessage, ExtractedName, ExtractedYear, ExtractedSeasonNumber, ExtractedEpisodeNumber, ExtractedEndingEpisodeNumber, DuplicatePaths) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                    paramList.Add(result.Id.ToGuidParamValue());
                    paramList.Add(result.OriginalPath);
                    paramList.Add(result.TargetPath);
                    paramList.Add(result.FileSize);
                    paramList.Add(result.Date.ToDateTimeParamValue());
                    paramList.Add(result.Status.ToString());
                    paramList.Add(result.Type.ToString());
                    paramList.Add(result.StatusMessage);
                    paramList.Add(result.ExtractedName);
                    paramList.Add(result.ExtractedSeasonNumber);
                    paramList.Add(result.ExtractedEpisodeNumber);
                    paramList.Add(result.ExtractedEndingEpisodeNumber);
                    paramList.Add(string.Join("|", result.DuplicatePaths.ToArray()));


                    db.Execute(commandText, paramList.ToArray());
                });
            }
        }

        public async Task Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }

            using (var connection = CreateConnection())
            {
                connection.RunInTransaction(db =>
                {
                    var paramList = new List<object>();
                    var commandText = "delete from FileOrganizerResults where ResultId = ?";

                    paramList.Add(id.ToGuidParamValue());

                    db.Execute(commandText, paramList.ToArray());
                });
            }
        }

        public async Task DeleteAll()
        {
            using (var connection = CreateConnection())
            {
                connection.RunInTransaction(db =>
                {
                    var commandText = "delete from FileOrganizerResults";

                    db.Execute(commandText);
                });
            }
        }

        public QueryResult<FileOrganizationResult> GetResults(FileOrganizationResultQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            using (var connection = CreateConnection(true))
            {
                var commandText = "SELECT ResultId, OriginalPath, TargetPath, FileLength, OrganizationDate, Status, OrganizationType, StatusMessage, ExtractedName, ExtractedYear, ExtractedSeasonNumber, ExtractedEpisodeNumber, ExtractedEndingEpisodeNumber, DuplicatePaths from FileOrganizerResults";

                if (query.StartIndex.HasValue && query.StartIndex.Value > 0)
                {
                    commandText += string.Format(" WHERE ResultId NOT IN (SELECT ResultId FROM FileOrganizerResults ORDER BY OrganizationDate desc LIMIT {0})",
                        query.StartIndex.Value.ToString(_usCulture));
                }

                commandText += " ORDER BY OrganizationDate desc";

                if (query.Limit.HasValue)
                {
                    commandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
                }

                var list = new List<FileOrganizationResult>();
                var count = connection.Query("select count (ResultId) from FileOrganizerResults").SelectScalarInt().First();

                foreach (var row in connection.Query(commandText))
                {
                    list.Add(GetResult(row));
                }

                return new QueryResult<FileOrganizationResult>()
                {
                    Items = list.ToArray(),
                    TotalRecordCount = count
                };
            }
        }

        public FileOrganizationResult GetResult(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }

            using (var connection = CreateConnection(true))
            {
                var paramList = new List<object>();

                paramList.Add(id.ToGuidParamValue());

                foreach (var row in connection.Query("select ResultId, OriginalPath, TargetPath, FileLength, OrganizationDate, Status, OrganizationType, StatusMessage, ExtractedName, ExtractedYear, ExtractedSeasonNumber, ExtractedEpisodeNumber, ExtractedEndingEpisodeNumber, DuplicatePaths from FileOrganizerResults where ResultId=?", paramList.ToArray()))
                {
                    return GetResult(row);
                }

                return null;
            }
        }

        public FileOrganizationResult GetResult(IReadOnlyList<IResultSetValue> reader)
        {
            var index = 0;

            var result = new FileOrganizationResult
            {
                Id = reader[0].ReadGuid().ToString("N")
            };

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.OriginalPath = reader[index].ToString();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.TargetPath = reader[index].ToString();
            }

            index++;
            result.FileSize = reader[index].ToInt64();

            index++;
            result.Date = reader[index].ReadDateTime();

            index++;
            result.Status = (FileSortingStatus)Enum.Parse(typeof(FileSortingStatus), reader[index].ToString(), true);

            index++;
            result.Type = (FileOrganizerType)Enum.Parse(typeof(FileOrganizerType), reader[index].ToString(), true);

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.StatusMessage = reader[index].ToString();
            }

            result.OriginalFileName = Path.GetFileName(result.OriginalPath);

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.ExtractedName = reader[index].ToString();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.ExtractedYear = reader[index].ToInt();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.ExtractedSeasonNumber = reader[index].ToInt();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.ExtractedEpisodeNumber = reader[index].ToInt();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.ExtractedEndingEpisodeNumber = reader[index].ToInt();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                result.DuplicatePaths = reader[index].ToString().Split('|').Where(i => !string.IsNullOrEmpty(i)).ToList();
            }

            return result;
        }
    }
}