summaryrefslogtreecommitdiffstats
path: root/ComicRackWebViewer/BCRDatabase.cs
blob: 50924cb80f8dcab50deda8438f3cf604d0193382 (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
using cYo.Projects.ComicRack.Engine.Database;
using cYo.Projects.ComicRack.Viewer;
using System;
using System.Collections.Specialized;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;

namespace BCR
{

  
  /// <summary>
  /// Description of Database.
  /// </summary>
  public sealed class Database : IDisposable
  {
    private const int COMIC_DB_VERSION = 1;
    
    private SQLiteConnection mConnection;
    private string mFolder;
    private const string DIRECTORY = "ComicRack BCR";
    
    private static Database instance = new Database();
    private int mVersion = 0;
    private GlobalSettings _globalSettings = new GlobalSettings();
    
    private Guid libraryGuid = Guid.Empty;
    private Guid bcrGuid = Guid.Empty;
    
    public GlobalSettings GlobalSettings { get { return _globalSettings; } }
    
    
    public static Database Instance 
    {
      get { return instance; }
    }
    
    public static string ConfigurationFolder { get { return DIRECTORY; } }
    
    public Database()
    {
      mFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DIRECTORY);
      if (!Directory.Exists(mFolder))
      {
    	  Directory.CreateDirectory(mFolder);
      }
      
      string s = "cYo.Projects.ComicRack.Engine.Database.ComicLibraryListItem";
      ComicListItem item = Program.Database.ComicLists.GetItems<ComicListItem>(false).FirstOrDefault((ComicListItem cli) => cli.GetType().ToString() == s);
      if (item != null)
      {
        libraryGuid = item.Id;
      }
      
      s = "[BCR Users]";
      item = Program.Database.ComicLists.GetItems<ComicListItem>(false).FirstOrDefault((ComicListItem cli) => cli.Name == s);
      if (item == null)
      {
        // Add it
        ComicListItemFolder bcrFolder = new ComicListItemFolder(s);
        ((ComicLibrary)Program.Database).ComicLists.Add(bcrFolder);
        item = Program.Database.ComicLists.GetItems<ComicListItem>(false).FirstOrDefault((ComicListItem cli) => cli.Name == s);
      }
      
      if (item != null)
      {
        bcrGuid = item.Id;
      }
    }
    
    
    public void Initialize()
    {
      try 
      {
        mConnection = new SQLiteConnection(@"Data Source=" + mFolder + "\\bcr.s3db");
        mConnection.Open();
      }
      catch (System.DllNotFoundException e)
      {
        Trace.WriteLine(String.Format("Exception: {0}", e));
        MessageBox.Show("SQLite.Interop.dll seems to be missing. Aborting.", "Badaap Comic Reader Plugin", MessageBoxButton.OK, MessageBoxImage.Error);
        return;
      }
      catch (SQLiteException e)
      {
        Trace.WriteLine(String.Format("Exception: {0}", e));
        // error while opening/creating database
        mConnection = null;

        Trace.WriteLine("Failed to create/open the BCR database:");
        Trace.WriteLine(e.ToString());
        return;
      }
      
      // Check if the database is initialized by checking if the settings table exists.
      object name = ExecuteScalar("SELECT name FROM sqlite_master WHERE type='table' AND name='settings';");
      if (name == null)
      {
        // No settings table.
        // Create the entire database.
        mVersion = 0;
      }
      else
      {
        // Read version so we know if we must do a database update.
        object version = ExecuteScalar("SELECT value FROM settings WHERE key='version';");
        mVersion = Convert.ToInt32(version);
      }
          
      if (mVersion < 1)
      {
        // Create the database
        using (SQLiteTransaction transaction = mConnection.BeginTransaction())
        {
          ExecuteNonQuery("CREATE TABLE settings(key TEXT PRIMARY KEY NOT NULL, value TEXT);");
          ExecuteNonQuery("INSERT INTO settings (key,value) VALUES ('version','" + COMIC_DB_VERSION + "');");
          ExecuteNonQuery("INSERT INTO settings (key,value) VALUES ('port','8080');");
          
          ExecuteNonQuery(@"CREATE TABLE user(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
            username TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL,
            salt TEXT NOT NULL,
            activity INTEGER NOT NULL DEFAULT (CURRENT_TIMESTAMP), 
            created INTEGER NOT NULL DEFAULT (CURRENT_TIMESTAMP), 
            fullname TEXT DEFAULT ''
            );");
    
          ExecuteNonQuery(@"CREATE TABLE user_settings(
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            open_current_comic_at_launch INTEGER DEFAULT 1,
            open_next_comic INTEGER DEFAULT 1,
            page_fit_mode INTEGER DEFAULT 1,
            zoom_on_tap INTEGER DEFAULT 1,
            toggle_paging_bar INTEGER DEFAULT 2,
            use_page_turn_drag INTEGER DEFAULT 1,
            page_turn_drag_threshold INTEGER DEFAULT 75,
            use_page_change_area INTEGER DEFAULT 1,
            page_change_area_width INTEGER DEFAULT 50,
            use_comicrack_progress INTEGER DEFAULT 0,
            home_list_id TEXT DEFAULT ''
            );");
          
          
          /*
          ExecuteNonQuery(@"CREATE TABLE user_custom_settings(
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            key TEXT NOT NULL, 
            value TEXT
            );");
          */
          
          ExecuteNonQuery(@"CREATE TABLE user_apikeys(
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            apikey TEXT NOT NULL, 
            created INTEGER NOT NULL DEFAULT (CURRENT_TIMESTAMP),
            activity INTEGER NOT NULL DEFAULT (CURRENT_TIMESTAMP)
            );");
          
         
          // TODO: set hook on the deletion of a comic book from the library
          ExecuteNonQuery(@"CREATE TABLE comic_progress(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
            comic_id TEXT NOT NULL, 
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            date_last_read TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP),
            current_page INTEGER DEFAULT 0,
            last_page_read INTEGER DEFAULT 0
            );");
         
          
         
          /*
          
          ExecuteNonQuery(@"CREATE TABLE comic_favorites(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            comic_id TEXT NOT NULL
            );");
            
          ExecuteNonQuery(@"CREATE TABLE series_favorites(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            series TEXT NOT NULL
            );");
            
            
          // type, favorite:
          // 0, comic guid
          // 1, series name
          // 2, writer/colorer etc name
          // 3, character name
          ExecuteNonQuery(@"CREATE TABLE favorites(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
            user_id INTEGER NOT NULL REFERENCES user(id) ON DELETE CASCADE,
            favorite TEXT NOT NULL,
            type INTEGER
            );");  
          */
          
          
          // Automatically create a user_settings record when a user is added.
          ExecuteNonQuery("CREATE TRIGGER AddUserSettingsTrigger AFTER INSERT ON user BEGIN INSERT INTO user_settings (user_id) VALUES (NEW.id); END;");
          // Automatically invalidate all user sessions when the user changes its username or password
          ExecuteNonQuery("CREATE TRIGGER InvalidateApiKeys AFTER UPDATE ON user WHEN (NEW.username != OLD.username) OR (NEW.password != OLD.password) OR (NEW.salt != OLD.salt)  BEGIN DELETE FROM user_apikeys WHERE user_id=NEW.id; END;");
          
          // Create default user
          UserDatabase.AddUser("user", "password");
          
         
          transaction.Commit();
        }
      }
      
    
      if (mVersion < COMIC_DB_VERSION)
      {
        ExecuteNonQuery("UPDATE settings SET value='" + COMIC_DB_VERSION + "' WHERE key='version';");
      }
      
      GlobalSettings.Initialize();
      
      Validate();
    }
  
    
    /// <summary>
    /// Check if the database contains invalid references to data in the ComicRack database.
    /// Remove those references.
    /// </summary>
    private void Validate()
    {
      // Check if the lists referenced by users still exist.
      // Check if the comics referenced by users still exist.
      // TODO: provide user feedback in startup screen of BCR ?
    }
    
    
    public long GetLastInsertRowId()
    {
      return mConnection.LastInsertRowId;
    }
    
    /// <summary>
    /// Simple wrapper
    /// </summary>
    /// <param name="sql">The SQL statement to execute.</param>
    /// <returns>number of affected rows</returns>
    public int ExecuteNonQuery(string sql)
    {
      using (SQLiteCommand command = mConnection.CreateCommand()) 
      {
        command.CommandText = sql;
        return command.ExecuteNonQuery();
      }
    }
    
    /// <summary>
    /// Simple wrapper
    /// </summary>
    /// <param name="sql">The SQL statement to execute.</param>
    /// <returns>First column of first row of the query result.</returns>
    public object ExecuteScalar(string sql)
    {
      using (SQLiteCommand command = mConnection.CreateCommand()) 
      {
        command.CommandText = sql;
        return command.ExecuteScalar();
      }
    }
    
    
    /// <summary>
    /// Simple wrapper
    /// </summary>
    /// <param name="sql">The SQL statement to execute.</param>
    /// <returns>SQLiteDataReader with the query result.</returns>
    public SQLiteDataReader ExecuteReader(string sql)
    {
      using (SQLiteCommand command = mConnection.CreateCommand()) 
      {
        command.CommandText = sql;
        return command.ExecuteReader();
      }
    }
    
    /// <summary>
    /// Executes a query and returns the first row.
    /// </summary>
    /// <param name="sql">The SQL statement to execute.</param>
    /// <returns>The first row of the query result.</returns>
    public NameValueCollection QuerySingle(string sql)
    {
      using (SQLiteCommand command = mConnection.CreateCommand()) 
      {
        command.CommandText = sql;
        using (SQLiteDataReader reader = command.ExecuteReader())
        {
          if (reader.Read())
          {
            return reader.GetValues();
          }
        }
      }
      
      return null;
    }
    

    public void Dispose()
    {
      if (mConnection != null)
      {
        mConnection.Dispose();
        mConnection = null;
      }
    }

    ~Database()
    {
      Dispose();
    }

  }
}