diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/ApiStorage.kt b/src/main/kotlin/de/fabianonline/telegram_backup/ApiStorage.kt
index 0ce5886..ce99e44 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/ApiStorage.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/ApiStorage.kt
@@ -28,120 +28,120 @@ import java.io.FileNotFoundException
import java.io.IOException
internal class ApiStorage(prefix: String?) : TelegramApiStorage {
- private var prefix: String? = null
- private var do_save = false
- private var auth_key: AuthKey? = null
- private var dc: DataCenter? = null
- private var file_auth_key: File? = null
- private var file_dc: File? = null
+ private var prefix: String? = null
+ private var do_save = false
+ private var auth_key: AuthKey? = null
+ private var dc: DataCenter? = null
+ private var file_auth_key: File? = null
+ private var file_dc: File? = null
- init {
- this.setPrefix(prefix)
- }
+ init {
+ this.setPrefix(prefix)
+ }
- fun setPrefix(prefix: String?) {
- this.prefix = prefix
- this.do_save = this.prefix != null
- if (this.do_save) {
- val base = Config.FILE_BASE +
- File.separatorChar +
- this.prefix +
- File.separatorChar
- this.file_auth_key = File(base + Config.FILE_NAME_AUTH_KEY)
- this.file_dc = File(base + Config.FILE_NAME_DC)
- this._saveAuthKey()
- this._saveDc()
- } else {
- this.file_auth_key = null
- this.file_dc = null
- }
- }
+ fun setPrefix(prefix: String?) {
+ this.prefix = prefix
+ this.do_save = this.prefix != null
+ if (this.do_save) {
+ val base = Config.FILE_BASE +
+ File.separatorChar +
+ this.prefix +
+ File.separatorChar
+ this.file_auth_key = File(base + Config.FILE_NAME_AUTH_KEY)
+ this.file_dc = File(base + Config.FILE_NAME_DC)
+ this._saveAuthKey()
+ this._saveDc()
+ } else {
+ this.file_auth_key = null
+ this.file_dc = null
+ }
+ }
- override fun saveAuthKey(authKey: AuthKey) {
- this.auth_key = authKey
- this._saveAuthKey()
- }
+ override fun saveAuthKey(authKey: AuthKey) {
+ this.auth_key = authKey
+ this._saveAuthKey()
+ }
- private fun _saveAuthKey() {
- if (this.do_save && this.auth_key != null) {
- try {
- FileUtils.writeByteArrayToFile(this.file_auth_key, this.auth_key!!.key)
- } catch (e: IOException) {
- e.printStackTrace()
- }
+ private fun _saveAuthKey() {
+ if (this.do_save && this.auth_key != null) {
+ try {
+ FileUtils.writeByteArrayToFile(this.file_auth_key, this.auth_key!!.key)
+ } catch (e: IOException) {
+ e.printStackTrace()
+ }
- }
- }
+ }
+ }
- override fun loadAuthKey(): AuthKey? {
- if (this.auth_key != null) return this.auth_key
- if (this.file_auth_key != null) {
- try {
- return AuthKey(FileUtils.readFileToByteArray(this.file_auth_key))
- } catch (e: IOException) {
- if (e !is FileNotFoundException) e.printStackTrace()
- }
+ override fun loadAuthKey(): AuthKey? {
+ if (this.auth_key != null) return this.auth_key
+ if (this.file_auth_key != null) {
+ try {
+ return AuthKey(FileUtils.readFileToByteArray(this.file_auth_key))
+ } catch (e: IOException) {
+ if (e !is FileNotFoundException) e.printStackTrace()
+ }
- }
+ }
- return null
- }
+ return null
+ }
- override fun saveDc(dataCenter: DataCenter) {
- this.dc = dataCenter
- this._saveDc()
- }
+ override fun saveDc(dataCenter: DataCenter) {
+ this.dc = dataCenter
+ this._saveDc()
+ }
- private fun _saveDc() {
- if (this.do_save && this.dc != null) {
- try {
- FileUtils.write(this.file_dc, this.dc!!.toString())
- } catch (e: IOException) {
- e.printStackTrace()
- }
+ private fun _saveDc() {
+ if (this.do_save && this.dc != null) {
+ try {
+ FileUtils.write(this.file_dc, this.dc!!.toString())
+ } catch (e: IOException) {
+ e.printStackTrace()
+ }
- }
- }
+ }
+ }
- override fun loadDc(): DataCenter? {
- if (this.dc != null) return this.dc
- if (this.file_dc != null) {
- try {
- val infos = FileUtils.readFileToString(this.file_dc).split(":")
- return DataCenter(infos[0], Integer.parseInt(infos[1]))
- } catch (e: IOException) {
- if (e !is FileNotFoundException) e.printStackTrace()
- }
+ override fun loadDc(): DataCenter? {
+ if (this.dc != null) return this.dc
+ if (this.file_dc != null) {
+ try {
+ val infos = FileUtils.readFileToString(this.file_dc).split(":")
+ return DataCenter(infos[0], Integer.parseInt(infos[1]))
+ } catch (e: IOException) {
+ if (e !is FileNotFoundException) e.printStackTrace()
+ }
- }
- return null
- }
+ }
+ return null
+ }
- override fun deleteAuthKey() {
- if (this.do_save) {
- try {
- FileUtils.forceDelete(this.file_auth_key)
- } catch (e: IOException) {
- e.printStackTrace()
- }
+ override fun deleteAuthKey() {
+ if (this.do_save) {
+ try {
+ FileUtils.forceDelete(this.file_auth_key)
+ } catch (e: IOException) {
+ e.printStackTrace()
+ }
- }
- }
+ }
+ }
- override fun deleteDc() {
- if (this.do_save) {
- try {
- FileUtils.forceDelete(this.file_dc)
- } catch (e: IOException) {
- e.printStackTrace()
- }
+ override fun deleteDc() {
+ if (this.do_save) {
+ try {
+ FileUtils.forceDelete(this.file_dc)
+ } catch (e: IOException) {
+ e.printStackTrace()
+ }
- }
- }
+ }
+ }
- override fun saveSession(session: MTSession?) {}
+ override fun saveSession(session: MTSession?) {}
- override fun loadSession(): MTSession? {
- return null
- }
+ override fun loadSession(): MTSession? {
+ return null
+ }
}
diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineController.kt b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineController.kt
index e31192e..45600bd 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineController.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineController.kt
@@ -14,6 +14,7 @@
* 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.TelegramUpdateHandler
import de.fabianonline.telegram_backup.exporter.HTMLExporter
import com.github.badoualy.telegram.api.Kotlogram
@@ -27,327 +28,282 @@ import java.util.Vector
import java.util.HashMap
import org.slf4j.LoggerFactory
import org.slf4j.Logger
+
class CommandLineController {
- private val storage:ApiStorage
- var app:TelegramApp
-
- private fun getLine():String {
- if (System.console() != null) {
- return System.console().readLine("> ")
- } else {
- print("> ")
- return Scanner(System.`in`).nextLine()
- }
- }
-
- private fun getPassword():String {
- if (System.console() != null) {
- return String(System.console().readPassword("> "))
- } else {
- return getLine()
- }
- }
-
- init{
- logger.info("CommandLineController started. App version {}", Config.APP_APPVER)
- this.printHeader()
- if (CommandLineOptions.cmd_version)
- {
- System.exit(0)
- }
- else if (CommandLineOptions.cmd_help)
- {
- this.show_help()
- System.exit(0)
- }
- else if (CommandLineOptions.cmd_license)
- {
- CommandLineController.show_license()
- System.exit(0)
- }
- this.setupFileBase()
- if (CommandLineOptions.cmd_list_accounts)
- {
- this.list_accounts()
- System.exit(0)
- }
- logger.debug("Initializing TelegramApp")
- app = TelegramApp(Config.APP_ID, Config.APP_HASH, Config.APP_MODEL, Config.APP_SYSVER, Config.APP_APPVER, Config.APP_LANG)
- logger.trace("Checking accounts")
- val account = this.selectAccount()
- logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login)
- logger.info("Initializing ApiStorage")
- storage = ApiStorage(account)
- logger.info("Initializing TelegramUpdateHandler")
- val handler = TelegramUpdateHandler()
- logger.info("Creating Client")
- val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler)
- try
- {
- logger.info("Initializing UserManager")
- UserManager.init(client)
- val user = UserManager.getInstance()
- if (!CommandLineOptions.cmd_login && !user.loggedIn)
- {
- println("Your authorization data is invalid or missing. You will have to login with Telegram again.")
- CommandLineOptions.cmd_login = true
- }
- if (account != null && user.loggedIn)
- {
- if (account != "+" + user.user!!.getPhone())
- {
- logger.error("Account: {}, user.user!!.getPhone(): +{}", Utils.anonymize(account), Utils.anonymize(user.user!!.getPhone()))
- throw RuntimeException("Account / User mismatch")
- }
- }
- logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login)
- if (CommandLineOptions.cmd_login)
- {
- cmd_login(account)
- System.exit(0)
- }
- // If we reach this point, we can assume that there is an account and a database can be loaded / created.
- Database.init(client)
- if (CommandLineOptions.cmd_stats)
- {
- cmd_stats()
- System.exit(0)
- }
- if (CommandLineOptions.val_test != null)
- {
- if (CommandLineOptions.val_test == 1)
- {
- TestFeatures.test1()
- }
- else if (CommandLineOptions.val_test == 2)
- {
- TestFeatures.test2()
- }
- else
- {
- System.out.println("Unknown test " + CommandLineOptions.val_test)
- }
- System.exit(1)
- }
- logger.debug("CommandLineOptions.val_export: {}", CommandLineOptions.val_export)
- if (CommandLineOptions.val_export != null)
- {
- if (CommandLineOptions.val_export!!.toLowerCase().equals("html"))
- {
- (HTMLExporter()).export()
- System.exit(0)
- }
- else
- {
- show_error("Unknown export format.")
- }
- }
- if (user.loggedIn)
- {
- System.out.println("You are logged in as " + Utils.anonymize(user.userString))
- }
- else
- {
- println("You are not logged in.")
- System.exit(1)
- }
- logger.info("Initializing Download Manager")
- val d = DownloadManager(client, 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
- {
- println("Skipping media download because --no-media is set.")
- }
- }
- catch (e:Exception) {
- e.printStackTrace()
- logger.error("Exception caught!", e)
- }
- finally
- {
- if (CommandLineOptions.cmd_daemon)
- {
- handler.activate()
- println("DAEMON mode requested - keeping running.")
- }
- else
- {
- client.close()
- println()
- println("----- EXIT -----")
- System.exit(0)
- }
- }
- }
- private fun printHeader() {
- System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz")
- println()
- println("Telegram_Backup comes with ABSOLUTELY NO WARRANTY. This is free software, and you are")
- println("welcome to redistribute it under certain conditions; run it with '--license' for details.")
- println()
- }
- private fun setupFileBase() {
- logger.debug("Target dir at startup: {}", Utils.anonymize(Config.FILE_BASE))
- if (CommandLineOptions.val_target != null)
- {
- Config.FILE_BASE = CommandLineOptions.val_target!!
- }
- logger.debug("Target dir after options: {}", Utils.anonymize(Config.FILE_BASE))
- System.out.println("Base directory for files: " + Utils.anonymize(Config.FILE_BASE))
- }
- private fun selectAccount():String? {
- var account = "none"
- val accounts = Utils.getAccounts()
- if (CommandLineOptions.cmd_login)
- {
- logger.debug("Login requested, doing nothing.")
- // do nothing
- }
- else if (CommandLineOptions.val_account != null)
- {
- logger.debug("Account requested: {}", Utils.anonymize(CommandLineOptions.val_account!!))
- logger.trace("Checking accounts for match.")
- var found = false
- for (acc in accounts)
- {
- logger.trace("Checking {}", Utils.anonymize(acc))
- if (acc == CommandLineOptions.val_account)
- {
- found = true
- logger.trace("Matches.")
- break
- }
- }
- if (!found)
- {
- show_error("Couldn't find account '" + Utils.anonymize(CommandLineOptions.val_account!!) + "'. Maybe you want to use '--login' first?")
- }
- account = CommandLineOptions.val_account!!
- }
- else if (accounts.size == 0)
- {
- println("No accounts found. Starting login process...")
- CommandLineOptions.cmd_login = true
- return null
- }
- else if (accounts.size == 1)
- {
- account = accounts.firstElement()
- System.out.println("Using only available account: " + Utils.anonymize(account))
- }
- else
- {
- show_error(("You didn't specify which account to use.\n" +
- "Use '--account ' to use account .\n" +
- "Use '--list-accounts' to see all available accounts."))
- System.exit(1)
- }
- logger.debug("accounts.size: {}", accounts.size)
- logger.debug("account: {}", Utils.anonymize(account))
- return account
- }
- private fun cmd_stats() {
- println()
- println("Stats:")
- val format = "%40s: %d%n"
- System.out.format(format, "Number of accounts", Utils.getAccounts().size)
- System.out.format(format, "Number of messages", Database.getInstance().getMessageCount())
- System.out.format(format, "Number of chats", Database.getInstance().getChatCount())
- System.out.format(format, "Number of users", Database.getInstance().getUserCount())
- System.out.format(format, "Top message ID", Database.getInstance().getTopMessageID())
- println()
- println("Media Types:")
- for ((key, value) in Database.getInstance().getMessageMediaTypesWithCount())
- {
- System.out.format(format, key, value)
- }
- println()
- println("Api layers of messages:")
- for ((key, value) in Database.getInstance().getMessageApiLayerWithCount())
- {
- System.out.format(format, key, value)
- }
- }
- @Throws(RpcErrorException::class, IOException::class)
- private fun cmd_login(phoneToUse:String?) {
- val user = UserManager.getInstance()
- val phone: String
- if (phoneToUse == null)
- {
- println("Please enter your phone number in international format.")
- println("Example: +4917077651234")
- phone = getLine()
- } else {
- phone = phoneToUse
+ private val storage: ApiStorage
+ var app: TelegramApp
+
+ private fun getLine(): String {
+ if (System.console() != null) {
+ return System.console().readLine("> ")
+ } else {
+ print("> ")
+ return Scanner(System.`in`).nextLine()
+ }
+ }
+
+ private fun getPassword(): String {
+ if (System.console() != null) {
+ return String(System.console().readPassword("> "))
+ } else {
+ return getLine()
+ }
+ }
+
+ init {
+ logger.info("CommandLineController started. App version {}", Config.APP_APPVER)
+ this.printHeader()
+ if (CommandLineOptions.cmd_version) {
+ System.exit(0)
+ } else if (CommandLineOptions.cmd_help) {
+ this.show_help()
+ System.exit(0)
+ } else if (CommandLineOptions.cmd_license) {
+ CommandLineController.show_license()
+ System.exit(0)
+ }
+ this.setupFileBase()
+ if (CommandLineOptions.cmd_list_accounts) {
+ this.list_accounts()
+ System.exit(0)
+ }
+ logger.debug("Initializing TelegramApp")
+ app = TelegramApp(Config.APP_ID, Config.APP_HASH, Config.APP_MODEL, Config.APP_SYSVER, Config.APP_APPVER, Config.APP_LANG)
+ logger.trace("Checking accounts")
+ val account = this.selectAccount()
+ logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login)
+ logger.info("Initializing ApiStorage")
+ storage = ApiStorage(account)
+ logger.info("Initializing TelegramUpdateHandler")
+ val handler = TelegramUpdateHandler()
+ logger.info("Creating Client")
+ val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler)
+ try {
+ logger.info("Initializing UserManager")
+ UserManager.init(client)
+ val user = UserManager.getInstance()
+ if (!CommandLineOptions.cmd_login && !user.loggedIn) {
+ println("Your authorization data is invalid or missing. You will have to login with Telegram again.")
+ CommandLineOptions.cmd_login = true
+ }
+ if (account != null && user.loggedIn) {
+ if (account != "+" + user.user!!.getPhone()) {
+ logger.error("Account: {}, user.user!!.getPhone(): +{}", Utils.anonymize(account), Utils.anonymize(user.user!!.getPhone()))
+ throw RuntimeException("Account / User mismatch")
+ }
+ }
+ logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login)
+ if (CommandLineOptions.cmd_login) {
+ cmd_login(account)
+ System.exit(0)
+ }
+ // If we reach this point, we can assume that there is an account and a database can be loaded / created.
+ Database.init(client)
+ if (CommandLineOptions.cmd_stats) {
+ cmd_stats()
+ System.exit(0)
+ }
+ if (CommandLineOptions.val_test != null) {
+ if (CommandLineOptions.val_test == 1) {
+ TestFeatures.test1()
+ } else if (CommandLineOptions.val_test == 2) {
+ TestFeatures.test2()
+ } else {
+ System.out.println("Unknown test " + CommandLineOptions.val_test)
+ }
+ System.exit(1)
+ }
+ logger.debug("CommandLineOptions.val_export: {}", CommandLineOptions.val_export)
+ if (CommandLineOptions.val_export != null) {
+ if (CommandLineOptions.val_export!!.toLowerCase().equals("html")) {
+ (HTMLExporter()).export()
+ System.exit(0)
+ } else {
+ show_error("Unknown export format.")
+ }
+ }
+ if (user.loggedIn) {
+ System.out.println("You are logged in as " + Utils.anonymize(user.userString))
+ } else {
+ println("You are not logged in.")
+ System.exit(1)
+ }
+ logger.info("Initializing Download Manager")
+ val d = DownloadManager(client, 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 {
+ println("Skipping media download because --no-media is set.")
+ }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ logger.error("Exception caught!", e)
+ } finally {
+ if (CommandLineOptions.cmd_daemon) {
+ handler.activate()
+ println("DAEMON mode requested - keeping running.")
+ } else {
+ client.close()
+ println()
+ println("----- EXIT -----")
+ System.exit(0)
+ }
+ }
+ }
+
+ private fun printHeader() {
+ System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz")
+ println()
+ println("Telegram_Backup comes with ABSOLUTELY NO WARRANTY. This is free software, and you are")
+ println("welcome to redistribute it under certain conditions; run it with '--license' for details.")
+ println()
+ }
+
+ private fun setupFileBase() {
+ logger.debug("Target dir at startup: {}", Utils.anonymize(Config.FILE_BASE))
+ if (CommandLineOptions.val_target != null) {
+ Config.FILE_BASE = CommandLineOptions.val_target!!
+ }
+ logger.debug("Target dir after options: {}", Utils.anonymize(Config.FILE_BASE))
+ System.out.println("Base directory for files: " + Utils.anonymize(Config.FILE_BASE))
+ }
+
+ private fun selectAccount(): String? {
+ var account = "none"
+ val accounts = Utils.getAccounts()
+ if (CommandLineOptions.cmd_login) {
+ logger.debug("Login requested, doing nothing.")
+ // do nothing
+ } else if (CommandLineOptions.val_account != null) {
+ logger.debug("Account requested: {}", Utils.anonymize(CommandLineOptions.val_account!!))
+ logger.trace("Checking accounts for match.")
+ var found = false
+ for (acc in accounts) {
+ logger.trace("Checking {}", Utils.anonymize(acc))
+ if (acc == CommandLineOptions.val_account) {
+ found = true
+ logger.trace("Matches.")
+ break
+ }
+ }
+ if (!found) {
+ show_error("Couldn't find account '" + Utils.anonymize(CommandLineOptions.val_account!!) + "'. Maybe you want to use '--login' first?")
+ }
+ account = CommandLineOptions.val_account!!
+ } else if (accounts.size == 0) {
+ println("No accounts found. Starting login process...")
+ CommandLineOptions.cmd_login = true
+ return null
+ } else if (accounts.size == 1) {
+ account = accounts.firstElement()
+ System.out.println("Using only available account: " + Utils.anonymize(account))
+ } else {
+ show_error(("You didn't specify which account to use.\n" +
+ "Use '--account ' to use account .\n" +
+ "Use '--list-accounts' to see all available accounts."))
+ System.exit(1)
+ }
+ logger.debug("accounts.size: {}", accounts.size)
+ logger.debug("account: {}", Utils.anonymize(account))
+ return account
+ }
+
+ private fun cmd_stats() {
+ println()
+ println("Stats:")
+ val format = "%40s: %d%n"
+ System.out.format(format, "Number of accounts", Utils.getAccounts().size)
+ System.out.format(format, "Number of messages", Database.getInstance().getMessageCount())
+ System.out.format(format, "Number of chats", Database.getInstance().getChatCount())
+ System.out.format(format, "Number of users", Database.getInstance().getUserCount())
+ System.out.format(format, "Top message ID", Database.getInstance().getTopMessageID())
+ println()
+ println("Media Types:")
+ for ((key, value) in Database.getInstance().getMessageMediaTypesWithCount()) {
+ System.out.format(format, key, value)
+ }
+ println()
+ println("Api layers of messages:")
+ for ((key, value) in Database.getInstance().getMessageApiLayerWithCount()) {
+ System.out.format(format, key, value)
+ }
+ }
+
+ @Throws(RpcErrorException::class, IOException::class)
+ private fun cmd_login(phoneToUse: String?) {
+ val user = UserManager.getInstance()
+ val phone: String
+ if (phoneToUse == null) {
+ println("Please enter your phone number in international format.")
+ println("Example: +4917077651234")
+ phone = getLine()
+ } else {
+ phone = phoneToUse
+ }
+ user.sendCodeToPhoneNumber(phone)
+ println("Telegram sent you a code. Please enter it here.")
+ val code = getLine()
+ user.verifyCode(code)
+ if (user.isPasswordNeeded) {
+ println("We also need your account password. Please enter it now. It should not be printed, so it's okay if you see nothing while typing it.")
+ val pw = getPassword()
+ user.verifyPassword(pw)
+ }
+ storage.setPrefix("+" + user.user!!.getPhone())
+ System.out.println("Everything seems fine. Please run this tool again with '--account +" + Utils.anonymize(user.user!!.getPhone()) + " to use this account.")
+ }
+
+ private fun show_help() {
+ println("Valid options are:")
+ println(" -h, --help Shows this help.")
+ println(" -a, --account Use account .")
+ println(" -l, --login Login to an existing telegram account.")
+ println(" --debug Shows some debug information.")
+ println(" --trace Shows lots of debug information. Overrides --debug.")
+ println(" --trace-telegram Shows lots of debug messages from the library used to access Telegram.")
+ println(" -A, --list-accounts List all existing accounts ")
+ println(" --limit-messages Downloads at most the most recent messages.")
+ println(" --no-media Do not download media files.")
+ println(" -t, --target Target directory for the files.")
+ println(" -e, --export Export the database. Valid formats are:")
+ println(" html - Creates HTML files.")
+ println(" --license Displays the license of this program.")
+ println(" -d, --daemon Keep running and automatically save new messages.")
+ println(" --anonymize (Try to) Remove all sensitive information from output. Useful for requesting support.")
+ println(" --stats Print some usage statistics.")
+ println(" --with-channels Backup channels as well.")
+ println(" --with-supergroups Backup supergroups as well.")
+ }
+
+ private fun list_accounts() {
+ println("List of available accounts:")
+ val accounts = Utils.getAccounts()
+ if (accounts.size > 0) {
+ for (str in accounts) {
+ System.out.println(" " + Utils.anonymize(str))
+ }
+ println("Use '--account ' to use one of those accounts.")
+ } else {
+ println("NO ACCOUNTS FOUND")
+ println("Use '--login' to login to a telegram account.")
+ }
+ }
+
+ companion object {
+ private val logger = LoggerFactory.getLogger(CommandLineController::class.java)
+
+ public fun show_error(error: String) {
+ logger.error(error)
+ println("ERROR: " + error)
+ System.exit(1)
+ }
+
+ fun show_license() {
+ println("TODO: Print the GPL.")
+ }
}
- user.sendCodeToPhoneNumber(phone)
- println("Telegram sent you a code. Please enter it here.")
- val code = getLine()
- user.verifyCode(code)
- if (user.isPasswordNeeded)
- {
- println("We also need your account password. Please enter it now. It should not be printed, so it's okay if you see nothing while typing it.")
- val pw = getPassword()
- user.verifyPassword(pw)
- }
- storage.setPrefix("+" + user.user!!.getPhone())
- System.out.println("Everything seems fine. Please run this tool again with '--account +" + Utils.anonymize(user.user!!.getPhone()) + " to use this account.")
- }
- private fun show_help() {
- println("Valid options are:")
- println(" -h, --help Shows this help.")
- println(" -a, --account Use account .")
- println(" -l, --login Login to an existing telegram account.")
- println(" --debug Shows some debug information.")
- println(" --trace Shows lots of debug information. Overrides --debug.")
- println(" --trace-telegram Shows lots of debug messages from the library used to access Telegram.")
- println(" -A, --list-accounts List all existing accounts ")
- println(" --limit-messages Downloads at most the most recent messages.")
- println(" --no-media Do not download media files.")
- println(" -t, --target Target directory for the files.")
- println(" -e, --export Export the database. Valid formats are:")
- println(" html - Creates HTML files.")
- println(" --license Displays the license of this program.")
- println(" -d, --daemon Keep running and automatically save new messages.")
- println(" --anonymize (Try to) Remove all sensitive information from output. Useful for requesting support.")
- println(" --stats Print some usage statistics.")
- println(" --with-channels Backup channels as well.")
- println(" --with-supergroups Backup supergroups as well.")
- }
- private fun list_accounts() {
- println("List of available accounts:")
- val accounts = Utils.getAccounts()
- if (accounts.size > 0)
- {
- for (str in accounts)
- {
- System.out.println(" " + Utils.anonymize(str))
- }
- println("Use '--account ' to use one of those accounts.")
- }
- else
- {
- println("NO ACCOUNTS FOUND")
- println("Use '--login' to login to a telegram account.")
- }
- }
- companion object {
- private val logger = LoggerFactory.getLogger(CommandLineController::class.java)
-
- public fun show_error(error:String) {
- logger.error(error)
- println("ERROR: " + error)
- System.exit(1)
- }
- fun show_license() {
- println("TODO: Print the GPL.")
- }
-}
}
diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt
index 6d89e56..7646ff4 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt
@@ -20,68 +20,68 @@ import de.fabianonline.telegram_backup.DownloadProgressInterface
import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager
internal class CommandLineDownloadProgress : DownloadProgressInterface {
- private var mediaCount = 0
- private var i = 0
+ private var mediaCount = 0
+ private var i = 0
- override fun onMessageDownloadStart(count: Int, source: String?) {
- i = 0
- if (source == null) {
- System.out.println("Downloading $count messages.")
- } else {
- System.out.println("Downloading " + count + " messages from " + Utils.anonymize(source))
- }
- }
+ override fun onMessageDownloadStart(count: Int, source: String?) {
+ i = 0
+ if (source == null) {
+ System.out.println("Downloading $count messages.")
+ } else {
+ System.out.println("Downloading " + count + " messages from " + Utils.anonymize(source))
+ }
+ }
- override fun onMessageDownloaded(number: Int) {
- i += number
- print("..." + i)
- }
+ override fun onMessageDownloaded(number: Int) {
+ i += number
+ print("..." + i)
+ }
- override fun onMessageDownloadFinished() {
- println(" done.")
- }
+ override fun onMessageDownloadFinished() {
+ println(" done.")
+ }
- override fun onMediaDownloadStart(count: Int) {
- i = 0
- mediaCount = count
- println("Checking and downloading media.")
- println("Legend:")
- println("'V' - Video 'P' - Photo 'D' - Document")
- println("'S' - Sticker 'A' - Audio 'G' - Geolocation")
- println("'.' - Previously downloaded file 'e' - Empty file")
- println("' ' - Ignored media type (weblinks or contacts, for example)")
- println("'x' - File skipped because of timeout errors")
- println("" + count + " Files to check / download")
- }
+ override fun onMediaDownloadStart(count: Int) {
+ i = 0
+ mediaCount = count
+ println("Checking and downloading media.")
+ println("Legend:")
+ println("'V' - Video 'P' - Photo 'D' - Document")
+ println("'S' - Sticker 'A' - Audio 'G' - Geolocation")
+ println("'.' - Previously downloaded file 'e' - Empty file")
+ println("' ' - Ignored media type (weblinks or contacts, for example)")
+ println("'x' - File skipped because of timeout errors")
+ println("" + count + " Files to check / download")
+ }
- override fun onMediaDownloaded(file_manager: AbstractMediaFileManager) {
- show(file_manager.letter.toUpperCase())
- }
+ override fun onMediaDownloaded(file_manager: AbstractMediaFileManager) {
+ show(file_manager.letter.toUpperCase())
+ }
- override fun onMediaDownloadedEmpty() {
- show("e")
- }
+ override fun onMediaDownloadedEmpty() {
+ show("e")
+ }
- override fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager) {
- show(".")
- }
+ override fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager) {
+ show(".")
+ }
- override fun onMediaSkipped() {
- show("x")
- }
+ override fun onMediaSkipped() {
+ show("x")
+ }
- override fun onMediaDownloadFinished() {
- showNewLine()
- println("Done.")
- }
+ override fun onMediaDownloadFinished() {
+ showNewLine()
+ println("Done.")
+ }
- private fun show(letter: String) {
- print(letter)
- i++
- if (i % 100 == 0) showNewLine()
- }
+ private fun show(letter: String) {
+ print(letter)
+ i++
+ if (i % 100 == 0) showNewLine()
+ }
- private fun showNewLine() {
- println(" - $i/$mediaCount")
- }
+ private fun showNewLine() {
+ println(" - $i/$mediaCount")
+ }
}
diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineOptions.kt b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineOptions.kt
index 5c1bace..ba371a0 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineOptions.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineOptions.kt
@@ -14,85 +14,84 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see . */
package de.fabianonline.telegram_backup
+
internal object CommandLineOptions {
- public var cmd_console = false
- public var cmd_help = false
- public var cmd_login = false
- var cmd_debug = false
- var cmd_trace = false
- var cmd_trace_telegram = false
- var cmd_list_accounts = false
- var cmd_version = false
- var cmd_license = false
- var cmd_daemon = false
- var cmd_no_media = false
- var cmd_anonymize = false
- var cmd_stats = false
- var cmd_channels = false
- var cmd_supergroups = false
- var val_account:String? = null
- var val_limit_messages:Int? = null
- var val_target:String? = null
- var val_export:String? = null
- var val_test:Int? = null
- @JvmStatic fun parseOptions(args:Array) {
- var last_cmd:String? = null
- loop@ for (arg in args)
- {
- if (last_cmd != null)
- {
- when (last_cmd) {
- "--account" -> val_account = arg
- "--limit-messages" -> val_limit_messages = Integer.parseInt(arg)
- "--target" -> val_target = arg
- "--export" -> val_export = arg
- "--test" -> val_test = Integer.parseInt(arg)
- }
- last_cmd = null
- continue
- }
- when (arg) {
- "-a", "--account" -> {
- last_cmd = "--account"
- continue@loop
- }
- "-h", "--help" -> cmd_help = true
- "-l", "--login" -> cmd_login = true
- "--debug" -> cmd_debug = true
- "--trace" -> cmd_trace = true
- "--trace-telegram" -> cmd_trace_telegram = true
- "-A", "--list-accounts" -> cmd_list_accounts = true
- "--limit-messages" -> {
- last_cmd = arg
- continue@loop
- }
- "--console" -> cmd_console = true
- "-t", "--target" -> {
- last_cmd = "--target"
- continue@loop
- }
- "-V", "--version" -> cmd_version = true
- "-e", "--export" -> {
- last_cmd = "--export"
- continue@loop
- }
- "--license" -> cmd_license = true
- "-d", "--daemon" -> cmd_daemon = true
- "--no-media" -> cmd_no_media = true
- "--test" -> {
- last_cmd = "--test"
- continue@loop
- }
- "--anonymize" -> cmd_anonymize = true
- "--stats" -> cmd_stats = true
- "--with-channels" -> cmd_channels = true
- "--with-supergroups" -> cmd_supergroups = true
- else -> throw RuntimeException("Unknown command " + arg)
- }
- }
- if (last_cmd != null)
- {
- CommandLineController.show_error("Command $last_cmd had no parameter set.")
- }
- }
+ public var cmd_console = false
+ public var cmd_help = false
+ public var cmd_login = false
+ var cmd_debug = false
+ var cmd_trace = false
+ var cmd_trace_telegram = false
+ var cmd_list_accounts = false
+ var cmd_version = false
+ var cmd_license = false
+ var cmd_daemon = false
+ var cmd_no_media = false
+ var cmd_anonymize = false
+ var cmd_stats = false
+ var cmd_channels = false
+ var cmd_supergroups = false
+ var val_account: String? = null
+ var val_limit_messages: Int? = null
+ var val_target: String? = null
+ var val_export: String? = null
+ var val_test: Int? = null
+ @JvmStatic
+ fun parseOptions(args: Array) {
+ var last_cmd: String? = null
+ loop@ for (arg in args) {
+ if (last_cmd != null) {
+ when (last_cmd) {
+ "--account" -> val_account = arg
+ "--limit-messages" -> val_limit_messages = Integer.parseInt(arg)
+ "--target" -> val_target = arg
+ "--export" -> val_export = arg
+ "--test" -> val_test = Integer.parseInt(arg)
+ }
+ last_cmd = null
+ continue
+ }
+ when (arg) {
+ "-a", "--account" -> {
+ last_cmd = "--account"
+ continue@loop
+ }
+ "-h", "--help" -> cmd_help = true
+ "-l", "--login" -> cmd_login = true
+ "--debug" -> cmd_debug = true
+ "--trace" -> cmd_trace = true
+ "--trace-telegram" -> cmd_trace_telegram = true
+ "-A", "--list-accounts" -> cmd_list_accounts = true
+ "--limit-messages" -> {
+ last_cmd = arg
+ continue@loop
+ }
+ "--console" -> cmd_console = true
+ "-t", "--target" -> {
+ last_cmd = "--target"
+ continue@loop
+ }
+ "-V", "--version" -> cmd_version = true
+ "-e", "--export" -> {
+ last_cmd = "--export"
+ continue@loop
+ }
+ "--license" -> cmd_license = true
+ "-d", "--daemon" -> cmd_daemon = true
+ "--no-media" -> cmd_no_media = true
+ "--test" -> {
+ last_cmd = "--test"
+ continue@loop
+ }
+ "--anonymize" -> cmd_anonymize = true
+ "--stats" -> cmd_stats = true
+ "--with-channels" -> cmd_channels = true
+ "--with-supergroups" -> cmd_supergroups = true
+ else -> throw RuntimeException("Unknown command " + arg)
+ }
+ }
+ if (last_cmd != null) {
+ CommandLineController.show_error("Command $last_cmd had no parameter set.")
+ }
+ }
}
diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt
index 128a556..b8d6801 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt
@@ -27,67 +27,67 @@ import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.classic.Level
- fun main(args: Array) {
- CommandLineOptions.parseOptions(args)
+fun main(args: Array) {
+ CommandLineOptions.parseOptions(args)
- CommandLineRunner.setupLogging()
- CommandLineRunner.checkVersion()
+ CommandLineRunner.setupLogging()
+ CommandLineRunner.checkVersion()
- if (true || CommandLineOptions.cmd_console) {
- // Always use the console for now.
- CommandLineController()
- } else {
- GUIController()
- }
- }
+ if (true || CommandLineOptions.cmd_console) {
+ // Always use the console for now.
+ CommandLineController()
+ } else {
+ GUIController()
+ }
+}
object CommandLineRunner {
- fun setupLogging() {
- val logger = LoggerFactory.getLogger(CommandLineRunner::class.java) as Logger
- logger.trace("Setting up Loggers...")
- val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger
- val rootContext = rootLogger.getLoggerContext()
- rootContext.reset()
+ fun setupLogging() {
+ val logger = LoggerFactory.getLogger(CommandLineRunner::class.java) as Logger
+ logger.trace("Setting up Loggers...")
+ val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger
+ val rootContext = rootLogger.getLoggerContext()
+ rootContext.reset()
- val encoder = PatternLayoutEncoder()
- encoder.setContext(rootContext)
- encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %-35.-35(%logger{0}.%method): %message%n")
- encoder.start()
+ val encoder = PatternLayoutEncoder()
+ encoder.setContext(rootContext)
+ encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %-35.-35(%logger{0}.%method): %message%n")
+ encoder.start()
- val appender = ConsoleAppender()
- appender.setContext(rootContext)
- appender.setEncoder(encoder)
- appender.start()
+ val appender = ConsoleAppender()
+ appender.setContext(rootContext)
+ appender.setEncoder(encoder)
+ appender.start()
- rootLogger.addAppender(appender)
- rootLogger.setLevel(Level.OFF)
+ rootLogger.addAppender(appender)
+ rootLogger.setLevel(Level.OFF)
- if (CommandLineOptions.cmd_trace) {
- (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.TRACE)
- } else if (CommandLineOptions.cmd_debug) {
- (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.DEBUG)
- }
+ if (CommandLineOptions.cmd_trace) {
+ (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.TRACE)
+ } else if (CommandLineOptions.cmd_debug) {
+ (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.DEBUG)
+ }
- if (CommandLineOptions.cmd_trace_telegram) {
- (LoggerFactory.getLogger("com.github.badoualy") as Logger).setLevel(Level.TRACE)
- }
- }
+ if (CommandLineOptions.cmd_trace_telegram) {
+ (LoggerFactory.getLogger("com.github.badoualy") as Logger).setLevel(Level.TRACE)
+ }
+ }
- fun checkVersion(): Boolean {
- val 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
- }
+ fun checkVersion(): Boolean {
+ val 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/kotlin/de/fabianonline/telegram_backup/Config.kt b/src/main/kotlin/de/fabianonline/telegram_backup/Config.kt
index c496650..c0828d4 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/Config.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/Config.kt
@@ -22,39 +22,39 @@ import java.io.FileInputStream
import java.util.Properties
object Config {
- val APP_ID = 32860
- val APP_HASH = "16e4ff955cd0adfc058f95ca564f562d"
- val APP_MODEL = "Desktop"
- val APP_SYSVER = "1.0"
- val APP_APPVER: String
- val APP_LANG = "en"
+ val APP_ID = 32860
+ val APP_HASH = "16e4ff955cd0adfc058f95ca564f562d"
+ val APP_MODEL = "Desktop"
+ val APP_SYSVER = "1.0"
+ val APP_APPVER: String
+ val APP_LANG = "en"
- var FILE_BASE = System.getProperty("user.home") + File.separatorChar + ".telegram_backup"
- val FILE_NAME_AUTH_KEY = "auth.dat"
- val FILE_NAME_DC = "dc.dat"
- val FILE_NAME_DB = "database.sqlite"
- val FILE_NAME_DB_BACKUP = "database.version_%d.backup.sqlite"
- val FILE_FILES_BASE = "files"
- val FILE_STICKER_BASE = "stickers"
+ var FILE_BASE = System.getProperty("user.home") + File.separatorChar + ".telegram_backup"
+ val FILE_NAME_AUTH_KEY = "auth.dat"
+ val FILE_NAME_DC = "dc.dat"
+ val FILE_NAME_DB = "database.sqlite"
+ val FILE_NAME_DB_BACKUP = "database.version_%d.backup.sqlite"
+ val FILE_FILES_BASE = "files"
+ val FILE_STICKER_BASE = "stickers"
- var DELAY_AFTER_GET_MESSAGES: Long = 400
- var DELAY_AFTER_GET_FILE: Long = 100
- var GET_MESSAGES_BATCH_SIZE = 200
+ var DELAY_AFTER_GET_MESSAGES: Long = 400
+ var DELAY_AFTER_GET_FILE: Long = 100
+ var GET_MESSAGES_BATCH_SIZE = 200
- var RENAMING_MAX_TRIES = 5
- var RENAMING_DELAY: Long = 1000
+ var RENAMING_MAX_TRIES = 5
+ var RENAMING_DELAY: Long = 1000
- val SECRET_GMAPS = "AIzaSyBEtUDhCQKEH6i2Mn1GAiQ9M_tLN0vxHIs"
+ val SECRET_GMAPS = "AIzaSyBEtUDhCQKEH6i2Mn1GAiQ9M_tLN0vxHIs"
- init {
- val p = Properties()
- try {
- p.load(Config::class.java.getResourceAsStream("/build.properties"))
- APP_APPVER = p.getProperty("version")
- } catch (e: IOException) {
- throw RuntimeException(e)
- }
+ init {
+ val p = Properties()
+ try {
+ p.load(Config::class.java.getResourceAsStream("/build.properties"))
+ APP_APPVER = p.getProperty("version")
+ } catch (e: IOException) {
+ throw RuntimeException(e)
+ }
- }
+ }
}
diff --git a/src/main/kotlin/de/fabianonline/telegram_backup/Database.kt b/src/main/kotlin/de/fabianonline/telegram_backup/Database.kt
index f99774b..8869a17 100644
--- a/src/main/kotlin/de/fabianonline/telegram_backup/Database.kt
+++ b/src/main/kotlin/de/fabianonline/telegram_backup/Database.kt
@@ -48,675 +48,675 @@ import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager
import de.fabianonline.telegram_backup.mediafilemanager.FileManagerFactory
class Database private constructor(var client: TelegramClient) {
- private var conn: Connection? = null
- private var stmt: Statement? = null
- var user_manager: UserManager
-
- fun getTopMessageID(): Int {
- try {
- val rs = stmt!!.executeQuery("SELECT MAX(message_id) FROM messages WHERE source_type IN ('group', 'dialog')")
- rs.next()
- return rs.getInt(1)
- } catch (e: SQLException) {
- return 0
- }
-
- }
-
- fun getMessageCount(): Int = queryInt("SELECT COUNT(*) FROM messages")
- fun getChatCount(): Int = queryInt("SELECT COUNT(*) FROM chats")
- fun getUserCount(): Int = queryInt("SELECT COUNT(*) FROM users")
-
- val missingIDs: LinkedList
- get() {
- try {
- val missing = LinkedList()
- val max = getTopMessageID()
- val rs = stmt!!.executeQuery("SELECT message_id FROM messages WHERE source_type IN ('group', 'dialog') ORDER BY id")
- rs.next()
- var id = rs.getInt(1)
- for (i in 1..max) {
- if (i == id) {
- rs.next()
- if (rs.isClosed()) {
- id = Integer.MAX_VALUE
- } else {
- id = rs.getInt(1)
- }
- } else if (i < id) {
- missing.add(i)
- }
- }
- return missing
- } catch (e: SQLException) {
- e.printStackTrace()
- throw RuntimeException("Could not get list of ids.")
- }
-
- }
-
- fun getMessagesWithMedia(): LinkedList {
- try {
- val list = LinkedList()
- val 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 (e: Exception) {
- e.printStackTrace()
- throw RuntimeException("Exception occured. See above.")
- }
-
- }
-
- fun getMessagesFromUserCount(): Int {
- try {
- val rs = stmt!!.executeQuery("SELECT COUNT(*) FROM messages WHERE sender_id=" + user_manager.user!!.getId())
- rs.next()
- return rs.getInt(1)
- } catch (e: SQLException) {
- throw RuntimeException(e)
- }
-
- }
-
- fun getMessageTypesWithCount(): HashMap = getMessageTypesWithCount(GlobalChat())
-
- fun getMessageMediaTypesWithCount(): HashMap = getMessageMediaTypesWithCount(GlobalChat())
-
- fun getMessageApiLayerWithCount(): HashMap {
- val map = HashMap()
- try {
- val rs = stmt!!.executeQuery("SELECT COUNT(id), api_layer FROM messages GROUP BY api_layer ORDER BY api_layer")
- while (rs.next()) {
- var layer = rs.getInt(2)
- map.put("count.messages.api_layer.$layer", rs.getInt(1))
- }
- rs.close()
- return map
- } catch (e: Exception) {
- throw RuntimeException(e)
- }
- }
-
- fun getMessageAuthorsWithCount(): HashMap = getMessageAuthorsWithCount(GlobalChat())
-
- fun getMessageTimesMatrix(): Array = getMessageTimesMatrix(GlobalChat())
-
- fun getEncoding(): String {
- try {
- val rs = stmt!!.executeQuery("PRAGMA encoding")
- rs.next()
- return rs.getString(1)
- } catch (e: SQLException) {
- logger.debug("SQLException: {}", e)
- return "unknown"
- }
-
- }
-
-
- fun getListOfChatsForExport(): LinkedList {
- val list = LinkedList()
- try {
- val rs = stmt!!.executeQuery("SELECT chats.id, chats.name, COUNT(messages.id) as c " +
- "FROM chats, messages WHERE messages.source_type IN('group', 'supergroup', 'channel') AND messages.source_id=chats.id " +
- "GROUP BY chats.id ORDER BY c DESC")
- while (rs.next()) {
- list.add(Chat(rs.getInt(1), rs.getString(2), rs.getInt(3)))
- }
- rs.close()
- return list
- } catch (e: Exception) {
- e.printStackTrace()
- throw RuntimeException("Exception above!")
- }
-
- }
-
-
- fun getListOfDialogsForExport(): LinkedList