aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Devices/SqliteDeviceRepository.cs
blob: a15eb3558b45c2a56e4c891436a2cbfc33492b6d (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Emby.Server.Implementations.Data;
using MediaBrowser.Controller;
using MediaBrowser.Model.Logging;
using SQLitePCL.pretty;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
using MediaBrowser.Controller.Configuration;

namespace Emby.Server.Implementations.Devices
{
    public class SqliteDeviceRepository : BaseSqliteRepository, IDeviceRepository
    {
        private readonly CultureInfo _usCulture = new CultureInfo("en-US");
        protected IFileSystem FileSystem { get; private set; }
        private readonly object _syncLock = new object();
        private readonly IJsonSerializer _json;
        private IServerApplicationPaths _appPaths;

        public SqliteDeviceRepository(ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IJsonSerializer json)
            : base(logger)
        {
            var appPaths = config.ApplicationPaths;

            DbFilePath = Path.Combine(appPaths.DataPath, "devices.db");
            FileSystem = fileSystem;
            _json = json;
            _appPaths = appPaths;
        }

        public void Initialize()
        {
            try
            {
                InitializeInternal();
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error loading database file. Will reset and retry.", ex);

                FileSystem.DeleteFile(DbFilePath);

                InitializeInternal();
            }
        }

        private void InitializeInternal()
        {
            using (var connection = CreateConnection())
            {
                RunDefaultInitialization(connection);

                string[] queries = {
                    "create table if not exists Devices (Id TEXT PRIMARY KEY, Name TEXT, ReportedName TEXT, CustomName TEXT, CameraUploadPath TEXT, LastUserName TEXT, AppName TEXT, AppVersion TEXT, LastUserId TEXT, DateLastModified DATETIME, Capabilities TEXT)",
                    "create index if not exists idx_id on Devices(Id)"
                               };

                connection.RunQueries(queries);

                MigrateDevices();
            }
        }

        private void MigrateDevices()
        {
            List<string> files;
            try
            {
                files = FileSystem
                       .GetFilePaths(GetDevicesPath(), true)
                       .Where(i => string.Equals(Path.GetFileName(i), "device.json", StringComparison.OrdinalIgnoreCase))
                       .ToList();
            }
            catch (IOException)
            {
                return;
            }

            foreach (var file in files)
            {
                try
                {
                    var device = _json.DeserializeFromFile<DeviceInfo>(file);

                    device.Name = string.IsNullOrWhiteSpace(device.CustomName) ? device.ReportedName : device.CustomName;

                    SaveDevice(device);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException("Error reading {0}", ex, file);
                }
                finally
                {
                    try
                    {
                        FileSystem.DeleteFile(file);
                    }
                    catch (IOException)
                    {
                        try
                        {
                            FileSystem.MoveFile(file, Path.ChangeExtension(file, ".old"));
                        }
                        catch (IOException)
                        {
                        }
                    }
                }
            }
        }

        private const string BaseSelectText = "select Id, Name, ReportedName, CustomName, CameraUploadPath, LastUserName, AppName, AppVersion, LastUserId, DateLastModified, Capabilities from Devices";

        public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
        {
            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    connection.RunInTransaction(db =>
                    {
                        using (var statement = db.PrepareStatement("update devices set Capabilities=@Capabilities where Id=@Id"))
                        {
                            statement.TryBind("@Id", deviceId);

                            if (capabilities == null)
                            {
                                statement.TryBindNull("@Capabilities");
                            }
                            else
                            {
                                statement.TryBind("@Capabilities", _json.SerializeToString(capabilities));
                            }

                            statement.MoveNext();
                        }
                    }, TransactionMode);
                }
            }
        }

        public void SaveDevice(DeviceInfo entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    connection.RunInTransaction(db =>
                    {
                        using (var statement = db.PrepareStatement("replace into Devices (Id, Name, ReportedName, CustomName, CameraUploadPath, LastUserName, AppName, AppVersion, LastUserId, DateLastModified, Capabilities) values (@Id, @Name, @ReportedName, @CustomName, @CameraUploadPath, @LastUserName, @AppName, @AppVersion, @LastUserId, @DateLastModified, @Capabilities)"))
                        {
                            statement.TryBind("@Id", entry.Id);
                            statement.TryBind("@Name", entry.Name);
                            statement.TryBind("@ReportedName", entry.ReportedName);
                            statement.TryBind("@CustomName", entry.CustomName);
                            statement.TryBind("@CameraUploadPath", entry.CameraUploadPath);
                            statement.TryBind("@LastUserName", entry.LastUserName);
                            statement.TryBind("@AppName", entry.AppName);
                            statement.TryBind("@AppVersion", entry.AppVersion);
                            statement.TryBind("@DateLastModified", entry.DateLastModified);

                            if (entry.Capabilities == null)
                            {
                                statement.TryBindNull("@Capabilities");
                            }
                            else
                            {
                                statement.TryBind("@Capabilities", _json.SerializeToString(entry.Capabilities));
                            }

                            statement.MoveNext();
                        }
                    }, TransactionMode);
                }
            }
        }

        public DeviceInfo GetDevice(string id)
        {
            using (WriteLock.Read())
            {
                using (var connection = CreateConnection(true))
                {
                    var statementTexts = new List<string>();
                    statementTexts.Add(BaseSelectText + " where Id=@Id");

                    return connection.RunInTransaction(db =>
                    {
                        var statements = PrepareAllSafe(db, statementTexts).ToList();

                        using (var statement = statements[0])
                        {
                            statement.TryBind("@Id", id);

                            foreach (var row in statement.ExecuteQuery())
                            {
                                return GetEntry(row);
                            }
                        }

                        return null;

                    }, ReadTransactionMode);
                }
            }
        }

        public List<DeviceInfo> GetDevices()
        {
            using (WriteLock.Read())
            {
                using (var connection = CreateConnection(true))
                {
                    var statementTexts = new List<string>();
                    statementTexts.Add(BaseSelectText + " order by DateLastModified desc");

                    return connection.RunInTransaction(db =>
                    {
                        var list = new List<DeviceInfo>();

                        var statements = PrepareAllSafe(db, statementTexts).ToList();

                        using (var statement = statements[0])
                        {
                            foreach (var row in statement.ExecuteQuery())
                            {
                                list.Add(GetEntry(row));
                            }
                        }

                        return list;

                    }, ReadTransactionMode);
                }
            }
        }

        public ClientCapabilities GetCapabilities(string id)
        {
            using (WriteLock.Read())
            {
                using (var connection = CreateConnection(true))
                {
                    var statementTexts = new List<string>();
                    statementTexts.Add("Select Capabilities from Devices where Id=@Id");

                    return connection.RunInTransaction(db =>
                    {
                        var statements = PrepareAllSafe(db, statementTexts).ToList();

                        using (var statement = statements[0])
                        {
                            statement.TryBind("@Id", id);

                            foreach (var row in statement.ExecuteQuery())
                            {
                                if (row[0].SQLiteType != SQLiteType.Null)
                                {
                                    return _json.DeserializeFromString<ClientCapabilities>(row.GetString(0));
                                }
                            }
                        }

                        return null;

                    }, ReadTransactionMode);
                }
            }
        }

        private DeviceInfo GetEntry(IReadOnlyList<IResultSetValue> reader)
        {
            var index = 0;

            var info = new DeviceInfo
            {
                Id = reader.GetString(index)
            };

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.Name = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.ReportedName = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.CustomName = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.CameraUploadPath = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.LastUserName = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.AppName = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.AppVersion = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.LastUserId = reader.GetString(index);
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.DateLastModified = reader[index].ReadDateTime();
            }

            index++;
            if (reader[index].SQLiteType != SQLiteType.Null)
            {
                info.Capabilities = _json.DeserializeFromString<ClientCapabilities>(reader.GetString(index));
            }

            return info;
        }

        private string GetDevicesPath()
        {
            return Path.Combine(_appPaths.DataPath, "devices");
        }

        private string GetDevicePath(string id)
        {
            return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N"));
        }

        public ContentUploadHistory GetCameraUploadHistory(string deviceId)
        {
            var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");

            lock (_syncLock)
            {
                try
                {
                    return _json.DeserializeFromFile<ContentUploadHistory>(path);
                }
                catch (IOException)
                {
                    return new ContentUploadHistory
                    {
                        DeviceId = deviceId
                    };
                }
            }
        }

        public void AddCameraUpload(string deviceId, LocalFileInfo file)
        {
            var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
            FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path));

            lock (_syncLock)
            {
                ContentUploadHistory history;

                try
                {
                    history = _json.DeserializeFromFile<ContentUploadHistory>(path);
                }
                catch (IOException)
                {
                    history = new ContentUploadHistory
                    {
                        DeviceId = deviceId
                    };
                }

                history.DeviceId = deviceId;

                var list = history.FilesUploaded.ToList();
                list.Add(file);
                history.FilesUploaded = list.ToArray(list.Count);

                _json.SerializeToFile(history, path);
            }
        }

        public void DeleteDevice(string id)
        {
            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    connection.RunInTransaction(db =>
                    {
                        using (var statement = db.PrepareStatement("delete from devices where Id=@Id"))
                        {
                            statement.TryBind("@Id", id);

                            statement.MoveNext();
                        }
                    }, TransactionMode);
                }
            }

            var path = GetDevicePath(id);

            lock (_syncLock)
            {
                try
                {
                    FileSystem.DeleteDirectory(path, true);
                }
                catch (IOException)
                {
                }
            }
        }
    }
}