-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThumbnailsDatabase.cs
598 lines (474 loc) · 18 KB
/
ThumbnailsDatabase.cs
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
* Copyright © 2024 Travelonium AB
*
* This file is part of Arcadeia.
*
* Arcadeia is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Arcadeia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Arcadeia. If not, see <https://www.gnu.org/licenses/>.
*
*/
using Arcadeia.Configuration;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;
namespace Arcadeia
{
class ThumbnailsDatabase : IThumbnailsDatabase
{
private readonly IOptionsMonitor<Settings> _settings;
private readonly ILogger<ThumbnailsDatabase> _logger;
public readonly Dictionary<string, string> Columns = [];
private string ConnectionString => new(new SqliteConnectionStringBuilder
{
Pooling = true,
DataSource = FullPath,
Cache = SqliteCacheMode.Shared,
}.ToString());
/// <summary>
/// The directory in which where the database file is to be found or created.
/// </summary>
public string Path => _settings.CurrentValue.Thumbnails.Database.Path;
/// <summary>
/// The full path to the database file.
/// </summary>
public string FullPath => System.IO.Path.Combine(_settings.CurrentValue.Thumbnails.Database.Path, _settings.CurrentValue.Thumbnails.Database.Name);
/// <summary>
/// The maximum count of thumbnails the database is able to store.
/// </summary>
public int Count => new[]
{
_settings.CurrentValue.Thumbnails.Video,
_settings.CurrentValue.Thumbnails.Photo,
_settings.CurrentValue.Thumbnails.Audio
}
.SelectMany(x => x.Values).Where(x => !x.Sprite && x.Count > 0).Max(x => x.Count);
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailsDatabase"/> class.
/// </summary>
public ThumbnailsDatabase(IOptionsMonitor<Settings> settings, ILogger<ThumbnailsDatabase> logger)
{
_logger = logger;
_settings = settings;
// Check if the Thumbnails Database file already exists.
if (!File.Exists(FullPath))
{
try
{
// Create the hosting directory
Directory.CreateDirectory(Path);
// Create the new database file
using SqliteConnection connection = new(ConnectionString);
connection.Open();
_logger.LogInformation("Thumbnails Database Created: {}", FullPath);
}
catch (Exception e)
{
_logger.LogError("Thumbnails Database Creation Failed! Because: {}", e.Message);
}
}
// Update the database layout if needed.
UpdateDatabaseLayout();
// Retrieve and store the list of all the columns
Columns = GetColumns("Thumbnails");
}
/// <summary>
/// Finalizes an instance of the <see cref="ThumbnailsDatabase"/> class.
/// </summary>
~ThumbnailsDatabase()
{
}
#region Interface
public void Create(string id)
{
if (!RowExists("Thumbnails", "ID", id))
{
AddRow("Thumbnails", "ID", id);
}
}
public bool Exists(string id)
{
return RowExists("Thumbnails", "ID", id);
}
public void SetThumbnail(string id, int index, ref byte[] data)
{
if (!RowExists("Thumbnails", "ID", id))
{
AddRow("Thumbnails", "ID", id);
}
string column = "T" + index.ToString();
string sql = "UPDATE Thumbnails SET " + column + "= @" + column + " WHERE ID='" + id + "'";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.Parameters.Add("@" + column, SqliteType.Blob).Value = data;
command.ExecuteNonQuery();
}
public void SetThumbnail(string id, string label, ref byte[] data)
{
if (!RowExists("Thumbnails", "ID", id))
{
AddRow("Thumbnails", "ID", id);
}
string column = label.ToUpper();
string sql = "UPDATE Thumbnails SET " + column + "= @" + column + " WHERE ID='" + id + "'";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.Parameters.Add("@" + column, SqliteType.Blob).Value = data;
command.ExecuteNonQuery();
}
public byte[] GetThumbnail(string id, string label)
{
string column = label.ToUpper();
byte[] thumbnail = Array.Empty<byte>();
string sql = "SELECT " + column + " FROM Thumbnails WHERE ID='" + id + "'";
if (!Columns.ContainsKey(column)) return thumbnail;
using (SqliteConnection connection = new(ConnectionString))
{
connection.Open();
using SqliteCommand command = new(sql, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
int ordinal = reader.GetOrdinal(column);
if (!reader.IsDBNull(ordinal))
{
object blob = reader[column];
if (blob.GetType() == typeof(byte[]))
{
thumbnail = (byte[])blob;
break;
}
}
}
}
return thumbnail;
}
public byte[] GetThumbnail(string id, int index)
{
return GetThumbnail(id, "T" + index.ToString());
}
public async Task<byte[]> GetThumbnailAsync(string id, string label, CancellationToken cancellationToken)
{
string column = label.ToUpper();
byte[] thumbnail = Array.Empty<byte>();
string sql = "SELECT " + column + " FROM Thumbnails WHERE ID='" + id + "'";
if (!Columns.ContainsKey(column)) return thumbnail;
using (SqliteConnection connection = new(ConnectionString))
{
await connection.OpenAsync(cancellationToken);
using SqliteCommand command = new(sql, connection);
using var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
int ordinal = reader.GetOrdinal(column);
if (!await reader.IsDBNullAsync(ordinal, cancellationToken))
{
object blob = reader[column];
if (blob.GetType() == typeof(byte[]))
{
thumbnail = (byte[])blob;
break;
}
}
}
}
return thumbnail;
}
public async Task<byte[]> GetThumbnailAsync(string id, int index, CancellationToken cancellationToken)
{
return await GetThumbnailAsync(id, "T" + index.ToString(), cancellationToken);
}
public int DeleteThumbnails(string id)
{
return DeleteRow("Thumbnails", "ID", id);
}
public int GetThumbnailsCount(string id)
{
int count = 0;
string sql = "SELECT * FROM Thumbnails WHERE ID='" + id + "'";
using (SqliteConnection connection = new(ConnectionString))
{
connection.Open();
using SqliteCommand command = new(sql, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < Count; i++)
{
string column = "T" + i.ToString();
int ordinal = reader.GetOrdinal(column);
if (!reader.IsDBNull(ordinal))
{
count++;
}
else
{
break;
}
}
break;
}
}
return count;
}
public string[] GetNullColumns(string id)
{
var columns = new List<string>();
string sql = "SELECT * FROM Thumbnails WHERE ID='" + id + "'";
using (SqliteConnection connection = new(ConnectionString))
{
connection.Open();
using SqliteCommand command = new(sql, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
foreach (var column in Columns.Keys)
{
int ordinal = reader.GetOrdinal(column);
if (reader.IsDBNull(ordinal))
{
columns.Add(column);
}
}
break;
}
}
return columns.ToArray();
}
public void SetJournalMode(string mode)
{
string sql = "PRAGMA journal_mode=";
switch (mode.ToUpper())
{
case "DELETE":
sql += "DELETE;";
break;
case "TRUNCATE":
sql += "TRUNCATE;";
break;
case "PERSIST":
sql += "PERSIST;";
break;
case "MEMORY":
sql += "MEMORY;";
break;
case "WAL":
sql += "WAL;";
break;
case "OFF":
sql += "OFF;";
break;
default:
throw new ArgumentException(string.Format("The {0} is an invalid journal mode!", mode));
}
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.ExecuteNonQuery();
}
public void Checkpoint(string argument = "TRUNCATE")
{
string sql = string.Format("PRAGMA wal_checkpoint{0};", (argument.Length > 0) ? "(PASSIVE)" : "");
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.ExecuteNonQuery();
}
public void Vacuum()
{
string sql = "VACUUM;";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.ExecuteNonQuery();
}
#endregion
#region Database Operations
/// <summary>
/// Updates the database layout creating tables and columns as necessary.
/// </summary>
private void UpdateDatabaseLayout()
{
// Enable the WAL (Write-Ahead Logging) journaling mode
SetJournalMode("WAL");
// Create the Thumbnails table
if (!TableExists("Thumbnails"))
{
CreateThumbnailsTable();
}
// Add the ID column
if (!ColumnExists("Thumbnails", "ID"))
{
AddColumn("Thumbnails", "ID", "TEXT PRIMARY KEY NOT NULL");
}
// Add the thumbnails columns as configured
var formats = new[]
{
_settings.CurrentValue.Thumbnails.Video,
_settings.CurrentValue.Thumbnails.Photo,
_settings.CurrentValue.Thumbnails.Audio
};
foreach (var items in formats)
{
foreach (var item in items)
{
if (item.Value.Count > 0 && !item.Value.Sprite)
{
for (int i = 0; i < item.Value.Count; i++)
{
string column = item.Key.ToUpper() + i.ToString();
if (!ColumnExists("Thumbnails", column))
{
AddColumn("Thumbnails", column, "BLOB");
}
}
}
else
{
string column = item.Key.ToUpper();
if (!ColumnExists("Thumbnails", column))
{
AddColumn("Thumbnails", column, "BLOB");
}
}
}
}
}
/// <summary>
/// Checks whether or not a table exists in the Thumbnails Database.
/// </summary>
/// <param name="table">The table name.</param>
/// <returns><c>true</c> if it already exists and <c>false</c> otherwise.</returns>
private bool TableExists(string table)
{
string sql = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '" + table + "'";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
using SqliteDataReader reader = command.ExecuteReader();
return reader.HasRows;
}
/// <summary>
/// Checks whether or not a column exists in the given table of the Thumbnails Database.
/// </summary>
/// <param name="table">The table name.</param>
/// <param name="column">The column name.</param>
/// <returns><c>true</c> if it already exists and <c>false</c> otherwise.</returns>
private bool ColumnExists(string table, string column)
{
string sql = "PRAGMA table_info( " + table + " )";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
using SqliteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var name = reader["name"];
if (name != null && name.ToString()!.ToUpper().Equals(column.ToUpper()))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks whether a row with the specified value for a specific column exists.
/// </summary>
/// <param name="table">The table name.</param>
/// <param name="column">The column name.</param>
/// <param name="value">The value of the column.</param>
/// <returns><c>true</c> if the row exists and <c>false</c>< otherwise./returns>
private bool RowExists(string table, string column, string value)
{
string sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column + "='" + value + "'";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
bool result = (Convert.ToInt32(command.ExecuteScalar()) > 0);
return result;
}
/// <summary>
/// Retrieves all or the column names and their types from a given table.
/// </summary>
/// <param name="table">The table name.</param>
/// <returns></returns>
private Dictionary<string, string> GetColumns(string table)
{
Dictionary<string, string> columns = [];
string sql = "PRAGMA table_info( " + table + " )";
using (SqliteConnection connection = new(ConnectionString))
{
connection.Open();
using SqliteCommand command = new(sql, connection);
using SqliteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var name = reader["name"];
var type = reader["type"];
if (name != null && type != null)
{
columns.Add(name.ToString()!.ToUpper(), type.ToString()!.ToUpper());
}
else
{
throw new InvalidOperationException("Table column name or type is null.");
}
}
}
return columns;
}
/// <summary>
/// Creates the Thumbnails table.
/// </summary>
private void CreateThumbnailsTable()
{
string sql = "CREATE TABLE Thumbnails (ID text primary key not null)";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.ExecuteNonQuery();
}
/// <summary>
/// Adds a column of the specified type to the specified table.
/// </summary>
/// <param name="table">The table name to modify.</param>
/// <param name="column">The column name to add to the table.</param>
/// <param name="type">The type column type to add to the table.</param>
private void AddColumn(string table, string column, string type)
{
string sql = "ALTER TABLE " + table + " ADD COLUMN " + column + " " + type;
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.ExecuteNonQuery();
}
private int AddRow(string table, string column, string value)
{
string sql = "INSERT INTO " + table + " (" + column + ") VALUES (@" + column + ")";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
command.Parameters.Add("@" + column, SqliteType.Text).Value = value;
return command.ExecuteNonQuery();
}
private int DeleteRow(string table, string column, string value)
{
string sql = "DELETE FROM " + table + " WHERE " + column + "='" + value + "'";
using SqliteConnection connection = new(ConnectionString);
connection.Open();
using SqliteCommand command = new(sql, connection);
return command.ExecuteNonQuery();
}
#endregion
}
}