diff --git a/build.gradle b/build.gradle
index 2f5a241..156c039 100644
--- a/build.gradle
+++ b/build.gradle
@@ -11,7 +11,7 @@ repositories {
}
dependencies {
- compile('com.github.badoualy:kotlogram:666a81ef9d6707f117a3fecc2d21c91d51c7d075') {
+ compile('com.github.badoualy:kotlogram:0.0.6') {
exclude module: 'slf4j-simple'
}
compile 'org.xerial:sqlite-jdbc:3.16.1'
diff --git a/src/main/java/de/fabianonline/telegram_backup/ApiStorage.java b/src/main/java/de/fabianonline/telegram_backup/ApiStorage.java
deleted file mode 100644
index e0c59ea..0000000
--- a/src/main/java/de/fabianonline/telegram_backup/ApiStorage.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/* Telegram_Backup
- * Copyright (C) 2016 Fabian Schlenz
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program 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 General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see . */
-
-package de.fabianonline.telegram_backup;
-
-import com.github.badoualy.telegram.api.TelegramApiStorage;
-import com.github.badoualy.telegram.mtproto.model.DataCenter;
-import com.github.badoualy.telegram.mtproto.auth.AuthKey;
-import com.github.badoualy.telegram.mtproto.model.MTSession;
-
-import org.apache.commons.io.FileUtils;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-class ApiStorage implements TelegramApiStorage {
- private String prefix = null;
- private boolean do_save = false;
- private AuthKey auth_key = null;
- private DataCenter dc = null;
- private File file_auth_key = null;
- private File file_dc = null;
-
- public ApiStorage(String prefix) {
- this.setPrefix(prefix);
- }
-
- public void setPrefix(String prefix) {
- this.prefix = prefix;
- this.do_save = (this.prefix!=null);
- if (this.do_save) {
- String base = Config.FILE_BASE +
- File.separatorChar +
- this.prefix +
- File.separatorChar;
- this.file_auth_key = new File(base + Config.FILE_NAME_AUTH_KEY);
- this.file_dc = new File(base + Config.FILE_NAME_DC);
- this._saveAuthKey();
- this._saveDc();
- } else {
- this.file_auth_key = null;
- this.file_dc = null;
- }
- }
-
- public void saveAuthKey(AuthKey authKey) {
- this.auth_key = authKey;
- this._saveAuthKey();
- }
-
- private void _saveAuthKey() {
- if (this.do_save && this.auth_key!=null) {
- try {
- FileUtils.writeByteArrayToFile(this.file_auth_key, this.auth_key.getKey());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public AuthKey loadAuthKey() {
- if (this.auth_key != null) return this.auth_key;
- if (this.file_auth_key != null) {
- try {
- return new AuthKey(FileUtils.readFileToByteArray(this.file_auth_key));
- } catch (IOException e) {
- if (!(e instanceof FileNotFoundException)) e.printStackTrace();
- }
- }
-
- return null;
- }
-
- public void saveDc(DataCenter dc) {
- this.dc = dc;
- this._saveDc();
- }
-
- private void _saveDc() {
- if (this.do_save && this.dc != null) {
- try {
- FileUtils.write(this.file_dc, this.dc.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public DataCenter loadDc() {
- if (this.dc != null) return this.dc;
- if (this.file_dc != null) {
- try {
- String[] infos = FileUtils.readFileToString(this.file_dc).split(":");
- return new DataCenter(infos[0], Integer.parseInt(infos[1]));
- } catch (IOException e) {
- if (!(e instanceof FileNotFoundException)) e.printStackTrace();
- }
- }
- return null;
- }
-
- public void deleteAuthKey() {
- if (this.do_save) {
- try {
- FileUtils.forceDelete(this.file_auth_key);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void deleteDc() {
- if (this.do_save) {
- try {
- FileUtils.forceDelete(this.file_dc);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void saveSession(MTSession session) {
- }
-
- public MTSession loadSession() { return null; }
-}
diff --git a/src/main/java/de/fabianonline/telegram_backup/CommandLineController.java b/src/main/java/de/fabianonline/telegram_backup/CommandLineController.java
index f89a88b..7a2a298 100644
--- a/src/main/java/de/fabianonline/telegram_backup/CommandLineController.java
+++ b/src/main/java/de/fabianonline/telegram_backup/CommandLineController.java
@@ -16,10 +16,6 @@
package de.fabianonline.telegram_backup;
-import de.fabianonline.telegram_backup.TelegramUpdateHandler;
-import de.fabianonline.telegram_backup.exporter.HTMLExporter;
-import de.fabianonline.telegram_backup.models.Message;
-
import com.github.badoualy.telegram.api.Kotlogram;
import com.github.badoualy.telegram.api.TelegramApp;
import com.github.badoualy.telegram.api.TelegramClient;
@@ -38,7 +34,6 @@ import org.slf4j.Logger;
public class CommandLineController {
private static Logger logger = LoggerFactory.getLogger(CommandLineController.class);
- private ApiStorage storage;
public TelegramApp app;
public CommandLineController() {
@@ -70,103 +65,29 @@ public class CommandLineController {
logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login);
- logger.info("Initializing ApiStorage");
- storage = new ApiStorage(account);
- logger.info("Initializing TelegramUpdateHandler");
- TelegramUpdateHandler handler = new TelegramUpdateHandler();
logger.info("Creating Client");
- TelegramClient client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler);
+ TelegramClient client = null; //Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler);
try {
logger.info("Initializing UserManager");
- UserManager.init(client);
+ UserManager.init(account);
Database.init(client);
- UserManager user = UserManager.getInstance();
-
- if (!CommandLineOptions.cmd_login && !user.isLoggedIn()) {
- System.out.println("Your authorization data is invalid or missing. You will have to login with Telegram again.");
- CommandLineOptions.cmd_login = true;
- }
- if (account!=null && user.isLoggedIn()) {
- if (!account.equals("+" + user.getUser().getPhone())) {
- logger.error("Account: {}, user.getUser().getPhone(): +{}", Utils.anonymize(account), Utils.anonymize(user.getUser().getPhone()));
- throw new RuntimeException("Account / User mismatch");
- }
- }
+ // do stuff
+ Database.getInstance().jsonify();
- if (CommandLineOptions.cmd_stats) {
- cmd_stats();
- System.exit(0);
- }
-
- logger.debug("CommandLineOptions.val_export: {}", CommandLineOptions.val_export);
- if (CommandLineOptions.val_export != null) {
- if (CommandLineOptions.val_export.toLowerCase().equals("html")) {
- (new HTMLExporter()).export();
- System.exit(0);
- } else {
- show_error("Unknown export format.");
- }
- }
-
- logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login);
- if (CommandLineOptions.cmd_login) {
- cmd_login(account);
- System.exit(0);
- }
-
- if (user.isLoggedIn()) {
- System.out.println("You are logged in as " + Utils.anonymize(user.getUserString()));
- } else {
- System.out.println("You are not logged in.");
- System.exit(1);
- }
-
- logger.info("Initializing Download Manager");
-
- if (CommandLineOptions.val_test != null) {
- if (CommandLineOptions.val_test == 1) {
- TestFeatures.test1();
- } else if (CommandLineOptions.val_test == 2) {
- TestFeatures.test2(user, client);
- } else if (CommandLineOptions.val_test == 3) {
- logger.debug(Message.get(39925).getMessage());
- } else {
- System.out.println("Unknown test " + CommandLineOptions.val_test);
- }
- System.exit(1);
- }
-
- DownloadManager d = new DownloadManager(client, new CommandLineDownloadProgress());
- logger.debug("Calling DownloadManager.downloadMessages with limit {}", CommandLineOptions.val_limit_messages);
- d.downloadMessages(CommandLineOptions.val_limit_messages);
-
- logger.debug("CommandLineOptions.cmd_no_media: {}", CommandLineOptions.cmd_no_media);
- if (!CommandLineOptions.cmd_no_media) {
- logger.debug("Calling DownloadManager.downloadMedia");
- d.downloadMedia();
- } else {
- System.out.println("Skipping media download because --no-media is set.");
- }
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception caught!", e);
} finally {
- if (CommandLineOptions.cmd_daemon) {
- handler.activate();
- System.out.println("DAEMON mode requested - keeping running.");
- } else {
- client.close();
- System.out.println();
- System.out.println("----- EXIT -----");
- System.exit(0);
- }
+ System.out.println();
+ System.out.println("----- EXIT -----");
+ System.exit(0);
}
}
private void printHeader() {
- System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz");
+ System.out.println("Telegram_Backup 51convert version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz");
System.out.println();
System.out.println("Telegram_Backup comes with ABSOLUTELY NO WARRANTY. This is free software, and you are");
System.out.println("welcome to redistribute it under certain conditions; run it with '--license' for details.");
@@ -221,18 +142,6 @@ public class CommandLineController {
return account;
}
- private void cmd_stats() {
- HashMap map = new HashMap();
- map.put("count.accounts", Utils.getAccounts().size());
- map.put("count.messages", Database.getInstance().getMessageCount());
- map.put("messages.top_id", Database.getInstance().getTopMessageID());
- for(Map.Entry pair : Database.getInstance().getMessageMediaTypesWithCount().entrySet()) {
- map.put(pair.getKey(), pair.getValue());
- }
-
- System.out.println(map.toString());
- }
-
private void cmd_login(String phone) throws RpcErrorException, IOException {
UserManager user = UserManager.getInstance();
if (phone==null) {
@@ -251,7 +160,6 @@ public class CommandLineController {
String pw = getPassword();
user.verifyPassword(pw);
}
- storage.setPrefix("+" + user.getUser().getPhone());
System.out.println("Everything seems fine. Please run this tool again with '--account +" + Utils.anonymize(user.getUser().getPhone()) + " to use this account.");
}
@@ -275,22 +183,6 @@ public class CommandLineController {
private void show_help() {
System.out.println("Valid options are:");
- System.out.println(" -h, --help Shows this help.");
- System.out.println(" -a, --account Use account .");
- System.out.println(" -l, --login Login to an existing telegram account.");
- System.out.println(" --debug Shows some debug information.");
- System.out.println(" --trace Shows lots of debug information. Overrides --debug.");
- System.out.println(" --trace-telegram Shows lots of debug messages from the library used to access Telegram.");
- System.out.println(" -A, --list-accounts List all existing accounts ");
- System.out.println(" --limit-messages Downloads at most the most recent messages.");
- System.out.println(" --no-media Do not download media files.");
- System.out.println(" -t, --target Target directory for the files.");
- System.out.println(" -e, --export Export the database. Valid formats are:");
- System.out.println(" html - Creates HTML files.");
- System.out.println(" --license Displays the license of this program.");
- System.out.println(" -d, --daemon Keep running and automatically save new messages.");
- System.out.println(" --anonymize (Try to) Remove all sensitive information from output. Useful for requesting support.");
- System.out.println(" --stats Print some usage statistics.");
}
private void list_accounts() {
diff --git a/src/main/java/de/fabianonline/telegram_backup/CommandLineDownloadProgress.java b/src/main/java/de/fabianonline/telegram_backup/CommandLineDownloadProgress.java
deleted file mode 100644
index d56a4c8..0000000
--- a/src/main/java/de/fabianonline/telegram_backup/CommandLineDownloadProgress.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Telegram_Backup
- * Copyright (C) 2016 Fabian Schlenz
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program 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 General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see . */
-
-package de.fabianonline.telegram_backup;
-
-import de.fabianonline.telegram_backup.DownloadProgressInterface;
-import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager;
-
-class CommandLineDownloadProgress implements DownloadProgressInterface {
- private int mediaCount = 0;
- private int i = 0;
-
- public void onMessageDownloadStart(int count) { i=0; System.out.println("Downloading " + count + " messages."); }
- public void onMessageDownloaded(int number) { i+=number; System.out.print("..." + i); }
- public void onMessageDownloadFinished() { System.out.println(" done."); }
-
- public void onMediaDownloadStart(int count) {
- i = 0;
- mediaCount = count;
- System.out.println("Checking and downloading media.");
- System.out.println("Legend:");
- System.out.println("'V' - Video 'P' - Photo 'D' - Document");
- System.out.println("'S' - Sticker 'A' - Audio 'G' - Geolocation");
- System.out.println("'.' - Previously downloaded file 'e' - Empty file");
- System.out.println("' ' - Ignored media type (weblinks or contacts, for example)");
- System.out.println("'x' - File skipped because of timeout errors");
- System.out.println("" + count + " Files to check / download");
- }
-
- public void onMediaDownloaded(AbstractMediaFileManager fm) {
- show(fm.getLetter().toUpperCase());
- }
-
- public void onMediaDownloadedEmpty() { show("e"); }
- public void onMediaAlreadyPresent(AbstractMediaFileManager fm) {
- show(".");
- }
- public void onMediaSkipped() { show("x"); }
-
- public void onMediaDownloadFinished() { showNewLine(); System.out.println("Done."); }
-
- private void show(String letter) { System.out.print(letter); i++; if (i % 100 == 0) showNewLine();}
- private void showNewLine() { System.out.println(" - " + i + "/" + mediaCount); }
-}
-
diff --git a/src/main/java/de/fabianonline/telegram_backup/CommandLineRunner.java b/src/main/java/de/fabianonline/telegram_backup/CommandLineRunner.java
index 7058f5c..b745911 100644
--- a/src/main/java/de/fabianonline/telegram_backup/CommandLineRunner.java
+++ b/src/main/java/de/fabianonline/telegram_backup/CommandLineRunner.java
@@ -75,18 +75,6 @@ public class CommandLineRunner {
}
public static boolean checkVersion() {
- Version v = Utils.getNewestVersion();
- if (v!=null && v.isNewer) {
- System.out.println("A newer version is vailable!");
- System.out.println("You are using: " + Config.APP_APPVER);
- System.out.println("Available: " + v.version);
- System.out.println("Get it here: " + v.url);
- System.out.println();
- System.out.println("Changes in this version:");
- System.out.println(v.body);
- System.out.println();
- return false;
- }
return true;
}
}
diff --git a/src/main/java/de/fabianonline/telegram_backup/Database.java b/src/main/java/de/fabianonline/telegram_backup/Database.java
index cdb3923..961ea98 100644
--- a/src/main/java/de/fabianonline/telegram_backup/Database.java
+++ b/src/main/java/de/fabianonline/telegram_backup/Database.java
@@ -22,6 +22,7 @@ import com.github.badoualy.telegram.api.TelegramClient;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.google.gson.Gson;
+import com.github.badoualy.telegram.api.Kotlogram;
import java.sql.Connection;
import java.sql.DriverManager;
@@ -45,9 +46,6 @@ import java.nio.file.StandardCopyOption;
import java.nio.file.FileAlreadyExistsException;
import java.text.SimpleDateFormat;
-import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager;
-import de.fabianonline.telegram_backup.mediafilemanager.FileManagerFactory;
-
public class Database {
private Connection conn;
private Statement stmt;
@@ -77,10 +75,6 @@ public class Database {
CommandLineController.show_error("Could not connect to SQLITE database.");
}
- // Run updates
- DatabaseUpdates updates = new DatabaseUpdates(conn, this);
- updates.doUpdates();
-
System.out.println("Database is ready.");
}
@@ -93,537 +87,6 @@ public class Database {
return instance;
}
- public void backupDatabase(int currentVersion) {
- String filename = String.format(Config.FILE_NAME_DB_BACKUP, currentVersion);
- System.out.println(" Creating a backup of your database as " + filename);
- try {
- String src = user_manager.getFileBase() + Config.FILE_NAME_DB;
- String dst = user_manager.getFileBase() + filename;
- logger.debug("Copying {} to {}", src, dst);
- Files.copy(
- new File(src).toPath(),
- new File(dst).toPath());
- } catch (FileAlreadyExistsException e) {
- logger.warn("Backup already exists:", e);
- } catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("Could not create backup.");
- }
- }
-
- public int getTopMessageID() {
- try {
- ResultSet rs = stmt.executeQuery("SELECT MAX(id) FROM messages");
- rs.next();
- return rs.getInt(1);
- } catch (SQLException e) {
- return 0;
- }
- }
-
- public void logRun(int start_id, int end_id, int count) {
- try {
- PreparedStatement ps = conn.prepareStatement("INSERT INTO runs "+
- "(time, start_id, end_id, count_missing) "+
- "VALUES "+
- "(DateTime('now'), ?, ?, ? )");
- ps.setInt(1, start_id);
- ps.setInt(2, end_id);
- ps.setInt(3, count);
- ps.execute();
- } catch (SQLException e) {}
- }
-
- public int getMessageCount() {
- try {
- ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM messages");
- rs.next();
- return rs.getInt(1);
- } catch (SQLException e) {
- throw new RuntimeException("Could not get count of messages.");
- }
- }
-
- public LinkedList getMissingIDs() {
- try {
- LinkedList missing = new LinkedList();
- int max = getTopMessageID();
- ResultSet rs = stmt.executeQuery("SELECT id FROM messages ORDER BY id");
- rs.next();
- int id=rs.getInt(1);
- for (int i=1; i<=max; i++) {
- if (i==id) {
- rs.next();
- if (rs.isClosed()) {
- id = Integer.MAX_VALUE;
- } else {
- id=rs.getInt(1);
- }
- } else if (i all, Integer api_layer, Gson gson) {
- try {
- //"(id, dialog_id, from_id, from_type, text, time, has_media, data, sticker, type) " +
- //"VALUES " +
- //"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
- String columns =
- "(id, message_type, dialog_id, chat_id, sender_id, fwd_from_id, text, time, has_media, media_type, media_file, media_size, data, api_layer, json) "+
- "VALUES " +
- "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
- //1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
- PreparedStatement ps = conn.prepareStatement("INSERT OR REPLACE INTO messages " + columns);
- PreparedStatement ps_insert_or_ignore = conn.prepareStatement("INSERT OR IGNORE INTO messages " + columns);
-
- for (TLAbsMessage abs : all) {
- if (abs instanceof TLMessage) {
- TLMessage msg = (TLMessage) abs;
- ps.setInt(1, msg.getId());
- ps.setString(2, "message");
- TLAbsPeer peer = msg.getToId();
- if (peer instanceof TLPeerChat) {
- ps.setNull(3, Types.INTEGER);
- ps.setInt(4, ((TLPeerChat)peer).getChatId());
- } else if (peer instanceof TLPeerUser) {
- int id = ((TLPeerUser)peer).getUserId();
- if (id==this.user_manager.getUser().getId()) {
- id = msg.getFromId();
- }
- ps.setInt(3, id);
- ps.setNull(4, Types.INTEGER);
- } else {
- throw new RuntimeException("Unexpected Peer type: " + peer.getClass().getName());
- }
- ps.setInt(5, msg.getFromId());
-
- if (msg.getFwdFrom() != null && msg.getFwdFrom().getFromId() != null) {
- ps.setInt(6, msg.getFwdFrom().getFromId());
- } else {
- ps.setNull(6, Types.INTEGER);
- }
-
- String text = msg.getMessage();
- if ((text==null || text.equals("")) && msg.getMedia()!=null) {
- if (msg.getMedia() instanceof TLMessageMediaDocument) {
- text = ((TLMessageMediaDocument)msg.getMedia()).getCaption();
- } else if (msg.getMedia() instanceof TLMessageMediaPhoto) {
- text = ((TLMessageMediaPhoto)msg.getMedia()).getCaption();
- }
- }
- ps.setString(7, text);
- ps.setString(8, ""+msg.getDate());
- AbstractMediaFileManager f = FileManagerFactory.getFileManager(msg, user_manager, client);
- if (f==null) {
- ps.setNull(9, Types.BOOLEAN);
- ps.setNull(10, Types.VARCHAR);
- ps.setNull(11, Types.VARCHAR);
- ps.setNull(12, Types.INTEGER);
- } else {
- ps.setBoolean(9, true);
- ps.setString(10, f.getName());
- ps.setString(11, f.getTargetFilename());
- ps.setInt(12, f.getSize());
- }
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- msg.serializeBody(stream);
- ps.setBytes(13, stream.toByteArray());
- ps.setInt(14, api_layer);
- ps.setString(15, gson.toJson(msg));
- ps.addBatch();
- } else if (abs instanceof TLMessageService) {
- ps_insert_or_ignore.setInt(1, abs.getId());
- ps_insert_or_ignore.setString(2, "service_message");
- ps_insert_or_ignore.setNull(3, Types.INTEGER);
- ps_insert_or_ignore.setNull(4, Types.INTEGER);
- ps_insert_or_ignore.setNull(5, Types.INTEGER);
- ps_insert_or_ignore.setNull(6, Types.INTEGER);
- ps_insert_or_ignore.setNull(7, Types.VARCHAR);
- ps_insert_or_ignore.setNull(8, Types.INTEGER);
- ps_insert_or_ignore.setNull(9, Types.BOOLEAN);
- ps_insert_or_ignore.setNull(10, Types.VARCHAR);
- ps_insert_or_ignore.setNull(11, Types.VARCHAR);
- ps_insert_or_ignore.setNull(12, Types.INTEGER);
- ps_insert_or_ignore.setNull(13, Types.BLOB);
- ps_insert_or_ignore.setInt(14, api_layer);
- ps_insert_or_ignore.setString(15, gson.toJson((TLMessageService)abs));
- ps_insert_or_ignore.addBatch();
- } else if (abs instanceof TLMessageEmpty) {
- ps_insert_or_ignore.setInt(1, abs.getId());
- ps_insert_or_ignore.setString(2, "empty_message");
- ps_insert_or_ignore.setNull(3, Types.INTEGER);
- ps_insert_or_ignore.setNull(4, Types.INTEGER);
- ps_insert_or_ignore.setNull(5, Types.INTEGER);
- ps_insert_or_ignore.setNull(6, Types.INTEGER);
- ps_insert_or_ignore.setNull(7, Types.VARCHAR);
- ps_insert_or_ignore.setNull(8, Types.INTEGER);
- ps_insert_or_ignore.setNull(9, Types.BOOLEAN);
- ps_insert_or_ignore.setNull(10, Types.VARCHAR);
- ps_insert_or_ignore.setNull(11, Types.VARCHAR);
- ps_insert_or_ignore.setNull(12, Types.INTEGER);
- ps_insert_or_ignore.setNull(13, Types.BLOB);
- ps_insert_or_ignore.setInt(14, api_layer);
- ps_insert_or_ignore.setString(15, gson.toJson((TLMessageEmpty)abs));
- ps_insert_or_ignore.addBatch();
- } else {
- throw new RuntimeException("Unexpected Message type: " + abs.getClass().getName());
- }
- }
- conn.setAutoCommit(false);
- ps.executeBatch();
- ps.clearBatch();
- ps_insert_or_ignore.executeBatch();
- ps_insert_or_ignore.clearBatch();
- conn.commit();
- conn.setAutoCommit(true);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception shown above happened.");
- }
- }
-
- public synchronized void saveChats(TLVector all, Gson gson) {
- try {
- PreparedStatement ps_insert_or_replace = conn.prepareStatement(
- "INSERT OR REPLACE INTO chats " +
- "(id, name, type, json) "+
- "VALUES " +
- "(?, ?, ?, ?)");
- PreparedStatement ps_insert_or_ignore = conn.prepareStatement(
- "INSERT OR IGNORE INTO chats " +
- "(id, name, type, json) "+
- "VALUES " +
- "(?, ?, ?, ?)");
-
- for(TLAbsChat abs : all) {
- ps_insert_or_replace.setInt(1, abs.getId());
- ps_insert_or_ignore.setInt(1, abs.getId());
- if (abs instanceof TLChatEmpty) {
- ps_insert_or_ignore.setNull(2, Types.VARCHAR);
- ps_insert_or_ignore.setString(3, "empty_chat");
- ps_insert_or_ignore.setString(4, gson.toJson((TLChatEmpty)abs));
- ps_insert_or_ignore.addBatch();
- } else if (abs instanceof TLChatForbidden) {
- ps_insert_or_replace.setString(2, ((TLChatForbidden)abs).getTitle());
- ps_insert_or_replace.setString(3, "chat");
- ps_insert_or_replace.setString(4, gson.toJson((TLChatForbidden)abs));
- ps_insert_or_replace.addBatch();
- } else if (abs instanceof TLChannelForbidden) {
- ps_insert_or_replace.setString(2, ((TLChannelForbidden)abs).getTitle());
- ps_insert_or_replace.setString(3, "channel");
- ps_insert_or_replace.setString(4, gson.toJson((TLChannelForbidden)abs));
- ps_insert_or_replace.addBatch();
- } else if (abs instanceof TLChat) {
- ps_insert_or_replace.setString(2, ((TLChat) abs).getTitle());
- ps_insert_or_replace.setString(3, "chat");
- ps_insert_or_replace.setString(4, gson.toJson((TLChat) abs));
- ps_insert_or_replace.addBatch();
- } else if (abs instanceof TLChannel) {
- ps_insert_or_replace.setString(2, ((TLChannel)abs).getTitle());
- ps_insert_or_replace.setString(3, "channel");
- ps_insert_or_replace.setString(4, gson.toJson((TLChannel)abs));
- ps_insert_or_replace.addBatch();
- } else {
- throw new RuntimeException("Unexpected " + abs.getClass().getName());
- }
- }
- conn.setAutoCommit(false);
- ps_insert_or_ignore.executeBatch();
- ps_insert_or_ignore.clearBatch();
- ps_insert_or_replace.executeBatch();
- ps_insert_or_replace.clearBatch();
- conn.commit();
- conn.setAutoCommit(true);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception shown above happened.");
- }
- }
-
- public synchronized void saveUsers(TLVector all, Gson gson) {
- try {
- PreparedStatement ps_insert_or_replace = conn.prepareStatement(
- "INSERT OR REPLACE INTO users " +
- "(id, first_name, last_name, username, type, phone, json) " +
- "VALUES " +
- "(?, ?, ?, ?, ?, ?, ?)");
- PreparedStatement ps_insert_or_ignore = conn.prepareStatement(
- "INSERT OR IGNORE INTO users " +
- "(id, first_name, last_name, username, type, phone, json) " +
- "VALUES " +
- "(?, ?, ?, ?, ?, ?, ?)");
- for (TLAbsUser abs : all) {
- if (abs instanceof TLUser) {
- TLUser user = (TLUser)abs;
- ps_insert_or_replace.setInt(1, user.getId());
- ps_insert_or_replace.setString(2, user.getFirstName());
- ps_insert_or_replace.setString(3, user.getLastName());
- ps_insert_or_replace.setString(4, user.getUsername());
- ps_insert_or_replace.setString(5, "user");
- ps_insert_or_replace.setString(6, user.getPhone());
- ps_insert_or_replace.setString(7, gson.toJson(user));
- ps_insert_or_replace.addBatch();
- } else if (abs instanceof TLUserEmpty) {
- ps_insert_or_ignore.setInt(1, abs.getId());
- ps_insert_or_ignore.setNull(2, Types.VARCHAR);
- ps_insert_or_ignore.setNull(3, Types.VARCHAR);
- ps_insert_or_ignore.setNull(4, Types.VARCHAR);
- ps_insert_or_ignore.setString(5, "empty_user");
- ps_insert_or_ignore.setNull(6, Types.VARCHAR);
- ps_insert_or_replace.setString(7, gson.toJson((TLUserEmpty)abs));
- ps_insert_or_ignore.addBatch();
- } else {
- throw new RuntimeException("Unexpected " + abs.getClass().getName());
- }
- }
- conn.setAutoCommit(false);
- ps_insert_or_ignore.executeBatch();
- ps_insert_or_ignore.clearBatch();
- ps_insert_or_replace.executeBatch();
- ps_insert_or_replace.clearBatch();
- conn.commit();
- conn.setAutoCommit(true);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception shown above happened.");
- }
- }
-
- public LinkedList getMessagesWithMedia() {
- try {
- LinkedList list = new LinkedList();
- ResultSet rs = stmt.executeQuery("SELECT data FROM messages WHERE has_media=1");
- while (rs.next()) {
- list.add(bytesToTLMessage(rs.getBytes(1)));
- }
- rs.close();
- return list;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception occured. See above.");
- }
- }
-
- public String queryString(String query) {
- String result = null;
- try {
- ResultSet rs = stmt.executeQuery(query);
- rs.next();
- result = rs.getString(1);
- rs.close();
- } catch (Exception e) {
- logger.warn("Exception happened in queryString:", e);
- }
- return result;
- }
-
- public int getMessagesFromUserCount() {
- try {
- ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM messages WHERE sender_id=" + user_manager.getUser().getId());
- rs.next();
- return rs.getInt(1);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public LinkedList getIdsFromQuery(String query) {
- try {
- LinkedList list = new LinkedList();
- ResultSet rs = stmt.executeQuery(query);
- while(rs.next()) { list.add(rs.getInt(1)); }
- rs.close();
- return list;
- } catch (SQLException e) { throw new RuntimeException(e); }
- }
-
- public HashMap getMessageTypesWithCount() {
- return getMessageTypesWithCount(new GlobalChat());
- }
-
- public HashMap getMessageTypesWithCount(AbstractChat c) {
- HashMap map = new HashMap();
- try {
- ResultSet rs = stmt.executeQuery("SELECT message_type, COUNT(id) FROM messages WHERE " + c.getQuery() + " GROUP BY message_type");
- while (rs.next()) {
- map.put("count.messages.type." + rs.getString(1), rs.getInt(2));
- }
- return map;
- } catch (Exception e) { throw new RuntimeException(e); }
- }
-
- public HashMap getMessageMediaTypesWithCount() {
- return getMessageMediaTypesWithCount(new GlobalChat());
- }
-
- public HashMap getMessageMediaTypesWithCount(AbstractChat c) {
- HashMap map = new HashMap();
- try {
- int count = 0;
- ResultSet rs = stmt.executeQuery("SELECT media_type, COUNT(id) FROM messages WHERE " + c.getQuery() + " GROUP BY media_type");
- while (rs.next()) {
- String s = rs.getString(1);
- if (s==null) {
- s="null";
- } else {
- count += rs.getInt(2);
- }
- map.put("count.messages.media_type." + s, rs.getInt(2));
- }
- map.put("count.messages.media_type.any", count);
- return map;
- } catch (Exception e) { throw new RuntimeException(e); }
- }
-
- public HashMap getMessageAuthorsWithCount() {
- return getMessageAuthorsWithCount(new GlobalChat());
- }
-
- public HashMap getMessageAuthorsWithCount(AbstractChat c) {
- HashMap map = new HashMap();
- HashMap user_map = new HashMap();
- int count_others = 0;
- try {
- ResultSet rs = stmt.executeQuery("SELECT users.id, users.first_name, users.last_name, users.username, COUNT(messages.id) "+
- "FROM messages, users WHERE users.id=messages.sender_id AND " + c.getQuery() + " GROUP BY sender_id");
- while (rs.next()) {
- User u = new User(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4));
- if (u.isMe) {
- map.put("authors.count.me", rs.getInt(5));
- } else {
- user_map.put(u, rs.getInt(5));
- count_others += rs.getInt(5);
- }
- }
- map.put("authors.count.others", count_others);
- map.put("authors.all", user_map.entrySet());
- return map;
- } catch (Exception e) { throw new RuntimeException(e); }
- }
-
- public int[][] getMessageTimesMatrix() {
- return getMessageTimesMatrix(new GlobalChat());
- }
-
- public int[][] getMessageTimesMatrix(AbstractChat c) {
- int result[][] = new int[7][24];
- try {
- ResultSet rs = stmt.executeQuery("SELECT STRFTIME('%w', time, 'unixepoch') as DAY, " +
- "STRFTIME('%H', time, 'unixepoch') AS hour, " +
- "COUNT(id) FROM messages WHERE " + c.getQuery() + " GROUP BY hour, day " +
- "ORDER BY hour, day");
- while (rs.next()) {
- result[rs.getInt(1) == 0 ? 6 : rs.getInt(1)-1][rs.getInt(2)] = rs.getInt(3);
- }
- return result;
- } catch (Exception e) { throw new RuntimeException(e); }
- }
-
- public String getEncoding() {
- try {
- ResultSet rs = stmt.executeQuery("PRAGMA encoding");
- rs.next();
- return rs.getString(1);
- } catch (SQLException e) {
- logger.debug("SQLException: {}", e);
- return "unknown";
- }
- }
-
-
- public LinkedList getListOfChatsForExport() {
- LinkedList list = new LinkedList();
- try {
- ResultSet rs = stmt.executeQuery("SELECT chats.id, chats.name, COUNT(messages.id) as c "+
- "FROM chats, messages WHERE messages.chat_id IS NOT NULL AND messages.chat_id=chats.id "+
- "GROUP BY chats.id ORDER BY c DESC");
- while (rs.next()) {
- list.add(new Chat(rs.getInt(1), rs.getString(2), rs.getInt(3)));
- }
- rs.close();
- return list;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception above!");
- }
- }
-
-
- public LinkedList