Search in sources :

Example 1 with SQLiteDatabase

use of org.telegram.SQLite.SQLiteDatabase in project Telegram-FOSS by Telegram-FOSS-Team.

the class MediaDataController method loadMediaDatabase.

private void loadMediaDatabase(long uid, int count, int max_id, int min_id, int type, int classGuid, boolean isChannel, int fromCache, int requestIndex) {
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            boolean topReached = false;
            TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages();
            try {
                ArrayList<Long> usersToLoad = new ArrayList<>();
                ArrayList<Long> chatsToLoad = new ArrayList<>();
                int countToLoad = count + 1;
                SQLiteCursor cursor;
                SQLiteDatabase database = getMessagesStorage().getDatabase();
                boolean isEnd = false;
                boolean reverseMessages = false;
                if (!DialogObject.isEncryptedDialog(uid)) {
                    if (min_id == 0) {
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT start FROM media_holes_v2 WHERE uid = %d AND type = %d AND start IN (0, 1)", uid, type));
                        if (cursor.next()) {
                            isEnd = cursor.intValue(0) == 1;
                        } else {
                            cursor.dispose();
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM media_v4 WHERE uid = %d AND type = %d AND mid > 0", uid, type));
                            if (cursor.next()) {
                                int mid = cursor.intValue(0);
                                if (mid != 0) {
                                    SQLitePreparedStatement state = database.executeFast("REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");
                                    state.requery();
                                    state.bindLong(1, uid);
                                    state.bindInteger(2, type);
                                    state.bindInteger(3, 0);
                                    state.bindInteger(4, mid);
                                    state.step();
                                    state.dispose();
                                }
                            }
                        }
                        cursor.dispose();
                    }
                    int holeMessageId = 0;
                    if (max_id != 0) {
                        int startHole = 0;
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT start, end FROM media_holes_v2 WHERE uid = %d AND type = %d AND start <= %d ORDER BY end DESC LIMIT 1", uid, type, max_id));
                        if (cursor.next()) {
                            startHole = cursor.intValue(0);
                            holeMessageId = cursor.intValue(1);
                        }
                        cursor.dispose();
                        if (holeMessageId > 1) {
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid > 0 AND mid < %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, max_id, holeMessageId, type, countToLoad));
                            isEnd = false;
                        } else {
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid > 0 AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, max_id, type, countToLoad));
                        }
                    } else if (min_id != 0) {
                        int startHole = 0;
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT start, end FROM media_holes_v2 WHERE uid = %d AND type = %d AND end >= %d ORDER BY end ASC LIMIT 1", uid, type, min_id));
                        if (cursor.next()) {
                            startHole = cursor.intValue(0);
                            holeMessageId = cursor.intValue(1);
                        }
                        cursor.dispose();
                        reverseMessages = true;
                        if (startHole > 1) {
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid > 0 AND mid >= %d AND mid <= %d AND type = %d ORDER BY date ASC, mid ASC LIMIT %d", uid, min_id, startHole, type, countToLoad));
                        } else {
                            isEnd = true;
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid > 0 AND mid >= %d AND type = %d ORDER BY date ASC, mid ASC LIMIT %d", uid, min_id, type, countToLoad));
                        }
                    } else {
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(end) FROM media_holes_v2 WHERE uid = %d AND type = %d", uid, type));
                        if (cursor.next()) {
                            holeMessageId = cursor.intValue(0);
                        }
                        cursor.dispose();
                        if (holeMessageId > 1) {
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, holeMessageId, type, countToLoad));
                        } else {
                            cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v4 WHERE uid = %d AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, type, countToLoad));
                        }
                    }
                } else {
                    isEnd = true;
                    if (max_id != 0) {
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v4 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, max_id, type, countToLoad));
                    } else if (min_id != 0) {
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v4 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid < %d AND type = %d ORDER BY m.mid DESC LIMIT %d", uid, min_id, type, countToLoad));
                    } else {
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v4 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid WHERE m.uid = %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, type, countToLoad));
                    }
                }
                while (cursor.next()) {
                    NativeByteBuffer data = cursor.byteBufferValue(0);
                    if (data != null) {
                        TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                        message.readAttachPath(data, getUserConfig().clientUserId);
                        data.reuse();
                        message.id = cursor.intValue(1);
                        message.dialog_id = uid;
                        if (DialogObject.isEncryptedDialog(uid)) {
                            message.random_id = cursor.longValue(2);
                        }
                        if (reverseMessages) {
                            res.messages.add(0, message);
                        } else {
                            res.messages.add(message);
                        }
                        MessagesStorage.addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
                    }
                }
                cursor.dispose();
                if (!usersToLoad.isEmpty()) {
                    getMessagesStorage().getUsersInternal(TextUtils.join(",", usersToLoad), res.users);
                }
                if (!chatsToLoad.isEmpty()) {
                    getMessagesStorage().getChatsInternal(TextUtils.join(",", chatsToLoad), res.chats);
                }
                if (res.messages.size() > count && min_id == 0) {
                    res.messages.remove(res.messages.size() - 1);
                } else {
                    if (min_id != 0) {
                        topReached = false;
                    } else {
                        topReached = isEnd;
                    }
                }
            } catch (Exception e) {
                res.messages.clear();
                res.chats.clear();
                res.users.clear();
                FileLog.e(e);
            } finally {
                Runnable task = this;
                AndroidUtilities.runOnUIThread(() -> getMessagesStorage().completeTaskForGuid(task, classGuid));
                processLoadedMedia(res, uid, count, max_id, min_id, type, fromCache, classGuid, isChannel, topReached, requestIndex);
            }
        }
    };
    MessagesStorage messagesStorage = getMessagesStorage();
    messagesStorage.getStorageQueue().postRunnable(runnable);
    messagesStorage.bindTaskToGuid(runnable, classGuid);
}
Also used : ArrayList(java.util.ArrayList) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) TLRPC(org.telegram.tgnet.TLRPC) Paint(android.graphics.Paint) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) SQLiteDatabase(org.telegram.SQLite.SQLiteDatabase)

Example 2 with SQLiteDatabase

use of org.telegram.SQLite.SQLiteDatabase in project Telegram-FOSS by Telegram-FOSS-Team.

the class MediaDataController method processLoadedRecentDocuments.

protected void processLoadedRecentDocuments(int type, ArrayList<TLRPC.Document> documents, boolean gif, int date, boolean replace) {
    if (documents != null) {
        getMessagesStorage().getStorageQueue().postRunnable(() -> {
            try {
                SQLiteDatabase database = getMessagesStorage().getDatabase();
                int maxCount;
                if (gif) {
                    maxCount = getMessagesController().maxRecentGifsCount;
                } else {
                    if (type == TYPE_GREETINGS) {
                        maxCount = 200;
                    } else if (type == TYPE_FAVE) {
                        maxCount = getMessagesController().maxFaveStickersCount;
                    } else {
                        maxCount = getMessagesController().maxRecentStickersCount;
                    }
                }
                database.beginTransaction();
                SQLitePreparedStatement state = database.executeFast("REPLACE INTO web_recent_v3 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                int count = documents.size();
                int cacheType;
                if (gif) {
                    cacheType = 2;
                } else if (type == TYPE_IMAGE) {
                    cacheType = 3;
                } else if (type == TYPE_MASK) {
                    cacheType = 4;
                } else if (type == TYPE_GREETINGS) {
                    cacheType = 6;
                } else {
                    cacheType = 5;
                }
                if (replace) {
                    database.executeFast("DELETE FROM web_recent_v3 WHERE type = " + cacheType).stepThis().dispose();
                }
                for (int a = 0; a < count; a++) {
                    if (a == maxCount) {
                        break;
                    }
                    TLRPC.Document document = documents.get(a);
                    state.requery();
                    state.bindString(1, "" + document.id);
                    state.bindInteger(2, cacheType);
                    state.bindString(3, "");
                    state.bindString(4, "");
                    state.bindString(5, "");
                    state.bindInteger(6, 0);
                    state.bindInteger(7, 0);
                    state.bindInteger(8, 0);
                    state.bindInteger(9, date != 0 ? date : count - a);
                    NativeByteBuffer data = new NativeByteBuffer(document.getObjectSize());
                    document.serializeToStream(data);
                    state.bindByteBuffer(10, data);
                    state.step();
                    data.reuse();
                }
                state.dispose();
                database.commitTransaction();
                if (documents.size() >= maxCount) {
                    database.beginTransaction();
                    for (int a = maxCount; a < documents.size(); a++) {
                        database.executeFast("DELETE FROM web_recent_v3 WHERE id = '" + documents.get(a).id + "' AND type = " + cacheType).stepThis().dispose();
                    }
                    database.commitTransaction();
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
        });
    }
    if (date == 0) {
        AndroidUtilities.runOnUIThread(() -> {
            SharedPreferences.Editor editor = MessagesController.getEmojiSettings(currentAccount).edit();
            if (gif) {
                loadingRecentGifs = false;
                recentGifsLoaded = true;
                editor.putLong("lastGifLoadTime", System.currentTimeMillis()).commit();
            } else {
                loadingRecentStickers[type] = false;
                recentStickersLoaded[type] = true;
                if (type == TYPE_IMAGE) {
                    editor.putLong("lastStickersLoadTime", System.currentTimeMillis()).commit();
                } else if (type == TYPE_MASK) {
                    editor.putLong("lastStickersLoadTimeMask", System.currentTimeMillis()).commit();
                } else if (type == TYPE_GREETINGS) {
                    editor.putLong("lastStickersLoadTimeGreet", System.currentTimeMillis()).commit();
                } else {
                    editor.putLong("lastStickersLoadTimeFavs", System.currentTimeMillis()).commit();
                }
            }
            if (documents != null) {
                if (gif) {
                    recentGifs = documents;
                } else {
                    recentStickers[type] = documents;
                }
                if (type == TYPE_GREETINGS) {
                    preloadNextGreetingsSticker();
                }
                getNotificationCenter().postNotificationName(NotificationCenter.recentDocumentsDidLoad, gif, type);
            } else {
            }
        });
    }
}
Also used : SQLiteDatabase(org.telegram.SQLite.SQLiteDatabase) SharedPreferences(android.content.SharedPreferences) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) Paint(android.graphics.Paint) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement)

Example 3 with SQLiteDatabase

use of org.telegram.SQLite.SQLiteDatabase in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method openDatabase.

public void openDatabase(int openTries) {
    File filesDir = ApplicationLoader.getFilesDirFixed();
    if (currentAccount != 0) {
        filesDir = new File(filesDir, "account" + currentAccount + "/");
        filesDir.mkdirs();
    }
    cacheFile = new File(filesDir, "cache4.db");
    walCacheFile = new File(filesDir, "cache4.db-wal");
    shmCacheFile = new File(filesDir, "cache4.db-shm");
    boolean createTable = false;
    if (!cacheFile.exists()) {
        createTable = true;
    }
    try {
        database = new SQLiteDatabase(cacheFile.getPath());
        database.executeFast("PRAGMA secure_delete = ON").stepThis().dispose();
        database.executeFast("PRAGMA temp_store = MEMORY").stepThis().dispose();
        database.executeFast("PRAGMA journal_mode = WAL").stepThis().dispose();
        database.executeFast("PRAGMA journal_size_limit = 10485760").stepThis().dispose();
        if (createTable) {
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d("create new database");
            }
            database.executeFast("CREATE TABLE messages_holes(uid INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, start));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_messages_holes ON messages_holes(uid, end);").stepThis().dispose();
            database.executeFast("CREATE TABLE media_holes_v2(uid INTEGER, type INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, type, start));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_media_holes_v2 ON media_holes_v2(uid, type, end);").stepThis().dispose();
            database.executeFast("CREATE TABLE scheduled_messages_v2(mid INTEGER, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, reply_to_message_id INTEGER, PRIMARY KEY(mid, uid))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, send_state, date);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages_v2 ON scheduled_messages_v2(uid, date);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, reply_to_message_id);").stepThis().dispose();
            database.executeFast("CREATE TABLE messages_v2(mid INTEGER, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER, is_channel INTEGER, reply_to_message_id INTEGER, PRIMARY KEY(mid, uid))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_v2 ON messages_v2(uid, mid, read_state, out);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages_v2 ON messages_v2(uid, date, mid);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages_v2 ON messages_v2(mid, out);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages_v2 ON messages_v2(uid, out, read_state, ttl, date, send_state);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages_v2 ON messages_v2(mid, send_state, date);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_v2 ON messages_v2(uid, mention, read_state);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS is_channel_idx_messages_v2 ON messages_v2(mid, is_channel);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_messages_v2 ON messages_v2(mid, reply_to_message_id);").stepThis().dispose();
            database.executeFast("CREATE TABLE download_queue(uid INTEGER, type INTEGER, date INTEGER, data BLOB, parent TEXT, PRIMARY KEY (uid, type));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS type_date_idx_download_queue ON download_queue(type, date);").stepThis().dispose();
            database.executeFast("CREATE TABLE user_contacts_v7(key TEXT PRIMARY KEY, uid INTEGER, fname TEXT, sname TEXT, imported INTEGER)").stepThis().dispose();
            database.executeFast("CREATE TABLE user_phones_v7(key TEXT, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (key, phone))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v7(sphone, deleted);").stepThis().dispose();
            database.executeFast("CREATE TABLE dialogs(did INTEGER PRIMARY KEY, date INTEGER, unread_count INTEGER, last_mid INTEGER, inbox_max INTEGER, outbox_max INTEGER, last_mid_i INTEGER, unread_count_i INTEGER, pts INTEGER, date_i INTEGER, pinned INTEGER, flags INTEGER, folder_id INTEGER, data BLOB, unread_reactions INTEGER)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_dialogs ON dialogs(date);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_idx_dialogs ON dialogs(last_mid);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_idx_dialogs ON dialogs(unread_count);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_i_idx_dialogs ON dialogs(last_mid_i);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_i_idx_dialogs ON dialogs(unread_count_i);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS folder_id_idx_dialogs ON dialogs(folder_id);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS flags_idx_dialogs ON dialogs(flags);").stepThis().dispose();
            database.executeFast("CREATE TABLE dialog_filter(id INTEGER PRIMARY KEY, ord INTEGER, unread_count INTEGER, flags INTEGER, title TEXT)").stepThis().dispose();
            database.executeFast("CREATE TABLE dialog_filter_ep(id INTEGER, peer INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose();
            database.executeFast("CREATE TABLE dialog_filter_pin_v2(id INTEGER, peer INTEGER, pin INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose();
            database.executeFast("CREATE TABLE randoms_v2(random_id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (random_id, mid, uid))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms_v2 ON randoms_v2(mid, uid);").stepThis().dispose();
            database.executeFast("CREATE TABLE enc_tasks_v4(mid INTEGER, uid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, uid, media))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v4 ON enc_tasks_v4(date);").stepThis().dispose();
            database.executeFast("CREATE TABLE messages_seq(mid INTEGER PRIMARY KEY, seq_in INTEGER, seq_out INTEGER);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS seq_idx_messages_seq ON messages_seq(seq_in, seq_out);").stepThis().dispose();
            database.executeFast("CREATE TABLE params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose();
            database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose();
            database.executeFast("CREATE TABLE media_v4(mid INTEGER, uid INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid, type))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_v4 ON media_v4(uid, mid, type, date);").stepThis().dispose();
            database.executeFast("CREATE TABLE bot_keyboard(uid INTEGER PRIMARY KEY, mid INTEGER, info BLOB)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid_v2 ON bot_keyboard(mid, uid);").stepThis().dispose();
            database.executeFast("CREATE TABLE chat_settings_v2(uid INTEGER PRIMARY KEY, info BLOB, pinned INTEGER, online INTEGER, inviter INTEGER, links INTEGER)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS chat_settings_pinned_idx ON chat_settings_v2(uid, pinned) WHERE pinned != 0;").stepThis().dispose();
            database.executeFast("CREATE TABLE user_settings(uid INTEGER PRIMARY KEY, info BLOB, pinned INTEGER)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS user_settings_pinned_idx ON user_settings(uid, pinned) WHERE pinned != 0;").stepThis().dispose();
            database.executeFast("CREATE TABLE chat_pinned_v2(uid INTEGER, mid INTEGER, data BLOB, PRIMARY KEY (uid, mid));").stepThis().dispose();
            database.executeFast("CREATE TABLE chat_pinned_count(uid INTEGER PRIMARY KEY, count INTEGER, end INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE chat_hints(did INTEGER, type INTEGER, rating REAL, date INTEGER, PRIMARY KEY(did, type))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS chat_hints_rating_idx ON chat_hints(rating);").stepThis().dispose();
            database.executeFast("CREATE TABLE botcache(id TEXT PRIMARY KEY, date INTEGER, data BLOB)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS botcache_date_idx ON botcache(date);").stepThis().dispose();
            database.executeFast("CREATE TABLE users_data(uid INTEGER PRIMARY KEY, about TEXT)").stepThis().dispose();
            database.executeFast("CREATE TABLE users(uid INTEGER PRIMARY KEY, name TEXT, status INTEGER, data BLOB)").stepThis().dispose();
            database.executeFast("CREATE TABLE chats(uid INTEGER PRIMARY KEY, name TEXT, data BLOB)").stepThis().dispose();
            database.executeFast("CREATE TABLE enc_chats(uid INTEGER PRIMARY KEY, user INTEGER, name TEXT, data BLOB, g BLOB, authkey BLOB, ttl INTEGER, layer INTEGER, seq_in INTEGER, seq_out INTEGER, use_count INTEGER, exchange_id INTEGER, key_date INTEGER, fprint INTEGER, fauthkey BLOB, khash BLOB, in_seq_no INTEGER, admin_id INTEGER, mtproto_seq INTEGER)").stepThis().dispose();
            database.executeFast("CREATE TABLE channel_users_v2(did INTEGER, uid INTEGER, date INTEGER, data BLOB, PRIMARY KEY(did, uid))").stepThis().dispose();
            database.executeFast("CREATE TABLE channel_admins_v3(did INTEGER, uid INTEGER, data BLOB, PRIMARY KEY(did, uid))").stepThis().dispose();
            database.executeFast("CREATE TABLE contacts(uid INTEGER PRIMARY KEY, mutual INTEGER)").stepThis().dispose();
            database.executeFast("CREATE TABLE user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose();
            database.executeFast("CREATE TABLE dialog_settings(did INTEGER PRIMARY KEY, flags INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE web_recent_v3(id TEXT, type INTEGER, image_url TEXT, thumb_url TEXT, local_url TEXT, width INTEGER, height INTEGER, size INTEGER, date INTEGER, document BLOB, PRIMARY KEY (id, type));").stepThis().dispose();
            database.executeFast("CREATE TABLE stickers_v2(id INTEGER PRIMARY KEY, data BLOB, date INTEGER, hash INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE stickers_featured(id INTEGER PRIMARY KEY, data BLOB, unread BLOB, date INTEGER, hash INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE stickers_dice(emoji TEXT PRIMARY KEY, data BLOB, date INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE webpage_pending_v2(id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (id, mid, uid));").stepThis().dispose();
            database.executeFast("CREATE TABLE sent_files_v2(uid TEXT, type INTEGER, data BLOB, parent TEXT, PRIMARY KEY (uid, type))").stepThis().dispose();
            database.executeFast("CREATE TABLE search_recent(did INTEGER PRIMARY KEY, date INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE media_counts_v2(uid INTEGER, type INTEGER, count INTEGER, old INTEGER, PRIMARY KEY(uid, type))").stepThis().dispose();
            database.executeFast("CREATE TABLE keyvalue(id TEXT PRIMARY KEY, value TEXT)").stepThis().dispose();
            database.executeFast("CREATE TABLE bot_info_v2(uid INTEGER, dialogId INTEGER, info BLOB, PRIMARY KEY(uid, dialogId))").stepThis().dispose();
            database.executeFast("CREATE TABLE pending_tasks(id INTEGER PRIMARY KEY, data BLOB);").stepThis().dispose();
            database.executeFast("CREATE TABLE requested_holes(uid INTEGER, seq_out_start INTEGER, seq_out_end INTEGER, PRIMARY KEY (uid, seq_out_start, seq_out_end));").stepThis().dispose();
            database.executeFast("CREATE TABLE sharing_locations(uid INTEGER PRIMARY KEY, mid INTEGER, date INTEGER, period INTEGER, message BLOB, proximity INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE shortcut_widget(id INTEGER, did INTEGER, ord INTEGER, PRIMARY KEY (id, did));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS shortcut_widget_did ON shortcut_widget(did);").stepThis().dispose();
            database.executeFast("CREATE TABLE emoji_keywords_v2(lang TEXT, keyword TEXT, emoji TEXT, PRIMARY KEY(lang, keyword, emoji));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS emoji_keywords_v2_keyword ON emoji_keywords_v2(keyword);").stepThis().dispose();
            database.executeFast("CREATE TABLE emoji_keywords_info_v2(lang TEXT PRIMARY KEY, alias TEXT, version INTEGER, date INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE wallpapers2(uid INTEGER PRIMARY KEY, data BLOB, num INTEGER)").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS wallpapers_num ON wallpapers2(num);").stepThis().dispose();
            database.executeFast("CREATE TABLE unread_push_messages(uid INTEGER, mid INTEGER, random INTEGER, date INTEGER, data BLOB, fm TEXT, name TEXT, uname TEXT, flags INTEGER, PRIMARY KEY(uid, mid))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_date ON unread_push_messages(date);").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_random ON unread_push_messages(random);").stepThis().dispose();
            database.executeFast("CREATE TABLE polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS polls_id_v2 ON polls_v2(id);").stepThis().dispose();
            database.executeFast("CREATE TABLE reactions(data BLOB, hash INTEGER, date INTEGER);").stepThis().dispose();
            database.executeFast("CREATE TABLE reaction_mentions(message_id INTEGER, state INTEGER, dialog_id INTEGER, PRIMARY KEY(message_id, dialog_id))").stepThis().dispose();
            database.executeFast("CREATE INDEX IF NOT EXISTS reaction_mentions_did ON reaction_mentions(dialog_id);").stepThis().dispose();
            // version
            database.executeFast("PRAGMA user_version = " + LAST_DB_VERSION).stepThis().dispose();
        } else {
            int version = database.executeInt("PRAGMA user_version");
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d("current db version = " + version);
            }
            if (version == 0) {
                throw new Exception("malformed");
            }
            try {
                SQLiteCursor cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1");
                if (cursor.next()) {
                    lastSeqValue = cursor.intValue(0);
                    lastPtsValue = cursor.intValue(1);
                    lastDateValue = cursor.intValue(2);
                    lastQtsValue = cursor.intValue(3);
                    lastSecretVersion = cursor.intValue(4);
                    secretG = cursor.intValue(5);
                    if (cursor.isNull(6)) {
                        secretPBytes = null;
                    } else {
                        secretPBytes = cursor.byteArrayValue(6);
                        if (secretPBytes != null && secretPBytes.length == 1) {
                            secretPBytes = null;
                        }
                    }
                }
                cursor.dispose();
            } catch (Exception e) {
                if (e.getMessage() != null && e.getMessage().contains("malformed")) {
                    throw new RuntimeException("malformed");
                }
                FileLog.e(e);
                try {
                    database.executeFast("CREATE TABLE IF NOT EXISTS params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose();
                    database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose();
                } catch (Exception e2) {
                    FileLog.e(e2);
                }
            }
            if (version < LAST_DB_VERSION) {
                try {
                    updateDbToLastVersion(version);
                } catch (Exception e) {
                    if (BuildVars.DEBUG_PRIVATE_VERSION) {
                        throw e;
                    }
                    FileLog.e(e);
                    throw new RuntimeException("malformed");
                }
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
        if (BuildVars.DEBUG_PRIVATE_VERSION) {
            throw new RuntimeException(e);
        }
        if (openTries < 3 && e.getMessage() != null && e.getMessage().contains("malformed")) {
            if (openTries == 2) {
                cleanupInternal(true);
                for (int a = 0; a < 2; a++) {
                    getUserConfig().setDialogsLoadOffset(a, 0, 0, 0, 0, 0, 0);
                    getUserConfig().setTotalDialogsCount(a, 0);
                }
                getUserConfig().saveConfig(false);
            } else {
                cleanupInternal(false);
            }
            openDatabase(openTries == 1 ? 2 : 3);
        }
    }
    AndroidUtilities.runOnUIThread(() -> {
        if (databaseMigrationInProgress) {
            databaseMigrationInProgress = false;
            NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.onDatabaseMigration, false);
        }
    });
    loadDialogFilters();
    loadUnreadMessages();
    loadPendingTasks();
    try {
        openSync.countDown();
    } catch (Throwable ignore) {
    }
}
Also used : SQLiteDatabase(org.telegram.SQLite.SQLiteDatabase) File(java.io.File) SQLiteException(org.telegram.SQLite.SQLiteException) SQLiteCursor(org.telegram.SQLite.SQLiteCursor)

Example 4 with SQLiteDatabase

use of org.telegram.SQLite.SQLiteDatabase in project Telegram-FOSS by Telegram-FOSS-Team.

the class CacheControlActivity method clearDatabase.

private void clearDatabase() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    builder.setTitle(LocaleController.getString("LocalDatabaseClearTextTitle", R.string.LocalDatabaseClearTextTitle));
    builder.setMessage(LocaleController.getString("LocalDatabaseClearText", R.string.LocalDatabaseClearText));
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear), (dialogInterface, i) -> {
        if (getParentActivity() == null) {
            return;
        }
        final AlertDialog progressDialog = new AlertDialog(getParentActivity(), 3);
        progressDialog.setCanCacnel(false);
        progressDialog.showDelayed(500);
        MessagesController.getInstance(currentAccount).clearQueryTime();
        MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
            try {
                SQLiteDatabase database = MessagesStorage.getInstance(currentAccount).getDatabase();
                ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                database.executeFast("DELETE FROM reaction_mentions").stepThis().dispose();
                database.executeFast("DELETE FROM reaction_mentions").stepThis().dispose();
                SQLiteCursor cursor = database.queryFinalized("SELECT did FROM dialogs WHERE 1");
                StringBuilder ids = new StringBuilder();
                while (cursor.next()) {
                    long did = cursor.longValue(0);
                    if (!DialogObject.isEncryptedDialog(did)) {
                        dialogsToCleanup.add(did);
                    }
                }
                cursor.dispose();
                SQLitePreparedStatement state5 = database.executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                SQLitePreparedStatement state6 = database.executeFast("REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");
                database.beginTransaction();
                for (int a = 0; a < dialogsToCleanup.size(); a++) {
                    Long did = dialogsToCleanup.get(a);
                    int messagesCount = 0;
                    cursor = database.queryFinalized("SELECT COUNT(mid) FROM messages_v2 WHERE uid = " + did);
                    if (cursor.next()) {
                        messagesCount = cursor.intValue(0);
                    }
                    cursor.dispose();
                    if (messagesCount <= 2) {
                        continue;
                    }
                    cursor = database.queryFinalized("SELECT last_mid_i, last_mid FROM dialogs WHERE did = " + did);
                    int messageId = -1;
                    if (cursor.next()) {
                        long last_mid_i = cursor.longValue(0);
                        long last_mid = cursor.longValue(1);
                        SQLiteCursor cursor2 = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")");
                        try {
                            while (cursor2.next()) {
                                NativeByteBuffer data = cursor2.byteBufferValue(0);
                                if (data != null) {
                                    TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                                    if (message != null) {
                                        messageId = message.id;
                                        message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId);
                                    }
                                    data.reuse();
                                }
                            }
                        } catch (Exception e) {
                            FileLog.e(e);
                        }
                        cursor2.dispose();
                        database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did + " AND mid != " + last_mid_i + " AND mid != " + last_mid).stepThis().dispose();
                        database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose();
                        database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose();
                        database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose();
                        database.executeFast("DELETE FROM media_v4 WHERE uid = " + did).stepThis().dispose();
                        database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose();
                        MediaDataController.getInstance(currentAccount).clearBotKeyboard(did, null);
                        if (messageId != -1) {
                            MessagesStorage.createFirstHoles(did, state5, state6, messageId);
                        }
                    }
                    cursor.dispose();
                }
                state5.dispose();
                state6.dispose();
                database.commitTransaction();
                database.executeFast("PRAGMA journal_size_limit = 0").stepThis().dispose();
                database.executeFast("VACUUM").stepThis().dispose();
                database.executeFast("PRAGMA journal_size_limit = -1").stepThis().dispose();
            } catch (Exception e) {
                FileLog.e(e);
            } finally {
                AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                    if (listAdapter != null) {
                        databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize();
                        listAdapter.notifyDataSetChanged();
                    }
                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didClearDatabase);
                });
            }
        });
    });
    AlertDialog alertDialog = builder.create();
    showDialog(alertDialog);
    TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
    if (button != null) {
        button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ArrayList(java.util.ArrayList) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) SQLiteDatabase(org.telegram.SQLite.SQLiteDatabase) TextView(android.widget.TextView)

Example 5 with SQLiteDatabase

use of org.telegram.SQLite.SQLiteDatabase in project Telegram-FOSS by Telegram-FOSS-Team.

the class MediaDataController method putSetToCache.

private void putSetToCache(TLRPC.TL_messages_stickerSet set) {
    getMessagesStorage().getStorageQueue().postRunnable(() -> {
        try {
            SQLiteDatabase database = getMessagesStorage().getDatabase();
            SQLitePreparedStatement state = database.executeFast("REPLACE INTO web_recent_v3 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            state.requery();
            state.bindString(1, "s_" + set.set.id);
            state.bindInteger(2, 6);
            state.bindString(3, "");
            state.bindString(4, "");
            state.bindString(5, "");
            state.bindInteger(6, 0);
            state.bindInteger(7, 0);
            state.bindInteger(8, 0);
            state.bindInteger(9, 0);
            NativeByteBuffer data = new NativeByteBuffer(set.getObjectSize());
            set.serializeToStream(data);
            state.bindByteBuffer(10, data);
            state.step();
            data.reuse();
            state.dispose();
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : SQLiteDatabase(org.telegram.SQLite.SQLiteDatabase) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement)

Aggregations

SQLiteDatabase (org.telegram.SQLite.SQLiteDatabase)5 SQLiteException (org.telegram.SQLite.SQLiteException)4 SQLitePreparedStatement (org.telegram.SQLite.SQLitePreparedStatement)4 NativeByteBuffer (org.telegram.tgnet.NativeByteBuffer)4 SQLiteCursor (org.telegram.SQLite.SQLiteCursor)3 TLRPC (org.telegram.tgnet.TLRPC)3 Paint (android.graphics.Paint)2 ArrayList (java.util.ArrayList)2 SharedPreferences (android.content.SharedPreferences)1 TextView (android.widget.TextView)1 File (java.io.File)1 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)1