summaryrefslogtreecommitdiff
path: root/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/DatabaseHelper.java
blob: ead1e69e0ca0c82563548ae8d3ceca1fa5a07dfe (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
package org.fox.ttcomics2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.provider.BaseColumns;

import org.fox.ttcomics2.archive.CbrComicArchive;
import org.fox.ttcomics2.archive.CbzComicArchive;
import org.fox.ttcomics2.archive.ComicArchive;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class DatabaseHelper extends SQLiteOpenHelper {
	
	public static final String DATABASE_NAME = "ComicsCache.db";
	public static final int DATABASE_VERSION = 2;
	private Context m_context;
	private static DatabaseHelper m_instance;

	public static synchronized DatabaseHelper getInstance(Context context) {

		if (m_instance == null) {
			m_instance = new DatabaseHelper(context.getApplicationContext());
		}

		return m_instance;
	}

	public interface DirectoryScanListener {
		void onProgressUpdate(int progress, int max);
		void onPostExecute(int result);
	}

	private DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		m_context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS comics_cache;");
		
		db.execSQL("CREATE TABLE IF NOT EXISTS comics_cache (" +
				BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
				"filename TEXT, " +
				"path TEXT, " +                //v2
				"checksum TEXT, " +            //v2
				"size INTEGER, " +
				"position INTEGER, " +
				"max_position INTEGER" +
				");");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (oldVersion == 1 && newVersion == 2) {
			
			db.execSQL("ALTER TABLE comics_cache ADD COLUMN path TEXT;");
			db.execSQL("ALTER TABLE comics_cache ADD COLUMN checksum TEXT;");
			
			Cursor c = db.query("comics_cache", null,
					null, null, null, null, null);
			
			if (c.moveToFirst()) {
				while (!c.isAfterLast()) {
					int id = c.getInt(c.getColumnIndex(BaseColumns._ID));
					String fileName = c.getString(c.getColumnIndex("filename"));
	
					File file = new File(fileName);
					
					SQLiteStatement stmt = db.compileStatement("UPDATE comics_cache SET filename = ?, path = ? WHERE " + BaseColumns._ID + " = ?");
					stmt.bindString(1, file.getName());
					stmt.bindString(2, file.getParentFile().getAbsolutePath());
					stmt.bindLong(3, id);
					stmt.execute();
	
					c.moveToNext();
				}
			}
			
			c.close();
		}		
	}

	public Cursor findComicByFileName(String fileName) {
		File file = new File(fileName);

		if (getWritableDatabase() == null)
			return null;

		Cursor c = getWritableDatabase().query("comics_cache", null,
				"filename = ? AND path = ?",
				new String[]{file.getName(), file.getParentFile().getAbsolutePath()}, null, null, null);

		if (c.moveToFirst()) {
			return c;
		} else {
			c.close();

			SQLiteStatement stmt = getWritableDatabase().compileStatement("INSERT INTO comics_cache " +
					"(filename, path, position, max_position, size, checksum) VALUES (?, ?, 0, 0, -1, '')");
			stmt.bindString(1, file.getName());
			stmt.bindString(2, file.getParentFile().getAbsolutePath());
			stmt.execute();

			c = getWritableDatabase().query("comics_cache", null,
					"filename = ? AND path = ?",
					new String[] { file.getName(), file.getParentFile().getAbsolutePath() }, null, null, null);

			if (c.moveToFirst()) {
				return c;
			} else {
				c.close();
			}
		}

		return null;
	}

	public void setSize(String fileName, int size) {
		Cursor c = findComicByFileName(fileName);

		if (c != null) {
			c.close();

			File file = new File(fileName);

			SQLiteStatement stmt = getWritableDatabase().compileStatement("UPDATE comics_cache SET size = ? WHERE filename = ? AND path = ?");
			stmt.bindLong(1, size);
			stmt.bindString(2, file.getName());
			stmt.bindString(3, file.getParentFile().getAbsolutePath());
			stmt.execute();
			stmt.close();
		}
	}

	public void setLastPosition(String fileName, int position) {
		int lastPosition = getLastPosition(fileName);

		Cursor c = findComicByFileName(fileName);

		if (c != null) {
			c.close();

			File file = new File(fileName);

			SQLiteStatement stmt = getWritableDatabase().compileStatement("UPDATE comics_cache SET position = ?, max_position = ? WHERE filename = ? AND path = ?");
			stmt.bindLong(1, position);
			stmt.bindLong(2, Math.max(position, lastPosition));
			stmt.bindString(3, file.getName());
			stmt.bindString(4, file.getParentFile().getAbsolutePath());
			stmt.execute();
			stmt.close();
		}

	}

	public void setLastMaxPosition(String fileName, int position) {

		Cursor c = findComicByFileName(fileName);

		if (c != null) {
			c.close();

			File file = new File(fileName);

			SQLiteStatement stmt = getWritableDatabase().compileStatement("UPDATE comics_cache SET max_position = ? WHERE filename = ? AND path = ?");
			stmt.bindLong(1, position);
			stmt.bindString(2, file.getName());
			stmt.bindString(3, file.getParentFile().getAbsolutePath());
			stmt.execute();
			stmt.close();
		}
	}

	public int getLastPosition(String fileName) {
		int position = 0;

		File file = new File(fileName);

		Cursor c = getWritableDatabase().query("comics_cache", new String[]{"position"},
				"filename = ? AND path = ?",
				new String[]{file.getName(), file.getParentFile().getAbsolutePath()}, null, null, null);

		if (c.moveToFirst()) {
			position = c.getInt(c.getColumnIndex("position"));
		}

		c.close();

		return position;

	}

	public int getCachedItemCount(String baseDir) {
		Cursor c = getWritableDatabase().query("comics_cache", new String[] { "COUNT(*)" },
				"path = ?",
				new String[] { baseDir }, null, null, null);

		c.moveToFirst();
		int count = c.getInt(0);
		c.close();

		//Log.d(TAG, "getCachedItemCount:" + baseDir + "=" + count);

		return count;
	}

	public int getMaxPosition(String fileName) {
		int position = 0;

		File file = new File(fileName);

		Cursor c = getWritableDatabase().query("comics_cache", new String[]{"max_position"},
				"filename = ? AND path = ?",
				new String[]{file.getName(), file.getParentFile().getAbsolutePath()}, null, null, null);

		if (c.moveToFirst()) {
			position = c.getInt(c.getColumnIndex("max_position"));
		}

		c.close();

		return position;
	}

	public int getSize(String fileName) {
		int size = -1;

		File file = new File(fileName);

		Cursor c = getWritableDatabase().query("comics_cache", new String[] { "size" },
				"filename = ? AND path = ?",
				new String[] { file.getName(), file.getParentFile().getAbsolutePath() }, null, null, null);

		if (c.moveToFirst()) {
			size = c.getInt(c.getColumnIndex("size"));
		}

		c.close();

		//Log.d(TAG, "getSize:" + fileName + "=" + size);

		return size;
	}

	public void cleanupSqliteCache(String baseDir) {
		Cursor c = getWritableDatabase().query("comics_cache", null,
				null, null, null, null, null);

		if (c.moveToFirst()) {
			while (!c.isAfterLast()) {
				int id = c.getInt(c.getColumnIndex(BaseColumns._ID));
				String fileName = c.getString(c.getColumnIndex("path")) + "/" + c.getString(c.getColumnIndex("filename"));

				File file = new File(fileName);

				if (!file.exists()) {
					SQLiteStatement stmt = getWritableDatabase().compileStatement("DELETE FROM comics_cache WHERE " + BaseColumns._ID + " = ?");
					stmt.bindLong(1, id);
					stmt.execute();
				}

				c.moveToNext();
			}
		}

		c.close();
	}

	public void rescanDirectory(String comicsDir, final DirectoryScanListener listener) {

		@SuppressLint("StaticFieldLeak") AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {

			@Override
			protected void onProgressUpdate(Integer... progress) {
				listener.onProgressUpdate(progress[0], progress[1]);
			}

			@Override
			protected void onPostExecute(Integer result) {
				listener.onPostExecute(result);
			}

			@Override
			protected Integer doInBackground(String... params) {
				try {

					String comicsDir = params[0];
					File dir = new File(comicsDir);

					int fileIndex = 0;

					if (dir.isDirectory()) {
						File archives[] = dir.listFiles();

						java.util.Arrays.sort(archives);

						for (File archive : archives) {
							String filePath = archive.getAbsolutePath();

							if (archive.isDirectory()) {
								setSize(filePath, ComicListFragment.SIZE_DIR);

							} else if (archive.getName().toLowerCase().matches(".*\\.(cbz|zip|cbr|rar)")) {
								try {
									ComicArchive cba = null;

									if (archive.getName().toLowerCase().matches(".*\\.(cbz|zip)")) {
										cba = new CbzComicArchive(filePath);
									} else if (archive.getName().toLowerCase().matches(".*\\.(cbr|rar)")) {
										cba = new CbrComicArchive(filePath);
									}

									if (cba != null && cba.getCount() > 0) {
										// Get cover

										try {
											File thumbnailFile = new File(CommonActivity.getCacheFileName(m_context, filePath));

											if (!thumbnailFile.exists()) {
												InputStream is = cba.getItem(0);

												if (is != null) {
													FileOutputStream fos = new FileOutputStream(thumbnailFile);

													byte[] buffer = new byte[1024];
													int len;
													while ((len = is.read(buffer)) != -1) {
														fos.write(buffer, 0, len);
													}

													fos.close();
													is.close();
												}
											} else if (thumbnailFile.exists()) {
												thumbnailFile.setLastModified(new Date().getTime());
											}

										} catch (IOException e) {
											e.printStackTrace();
										}

										int size = cba.getCount();

										setSize(filePath, size);
									}
								} catch (IOException e) {
									e.printStackTrace();
								} catch (SQLException e) {
									e.printStackTrace();
								}
							}

							++fileIndex;

							publishProgress(Integer.valueOf(fileIndex), Integer.valueOf(archives.length));
						}
					}

					cleanupSqliteCache(comicsDir);

					return fileIndex;

				} catch (Exception e) {
					e.printStackTrace();
				}

				return 0;
			}
		};

		task.execute(comicsDir);
	}
}