1
0
mirror of https://github.com/fabianonline/telegram_backup.git synced 2024-11-22 16:56:16 +00:00

Kotlin: Reformatted code.

This commit is contained in:
Fabian Schlenz 2017-12-12 22:04:20 +01:00
parent 7067f98943
commit bb180f95be
25 changed files with 2750 additions and 2795 deletions

View File

@ -14,6 +14,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */ * along with this program. If not, see <http://www.gnu.org/licenses/>. */
package de.fabianonline.telegram_backup package de.fabianonline.telegram_backup
import de.fabianonline.telegram_backup.TelegramUpdateHandler import de.fabianonline.telegram_backup.TelegramUpdateHandler
import de.fabianonline.telegram_backup.exporter.HTMLExporter import de.fabianonline.telegram_backup.exporter.HTMLExporter
import com.github.badoualy.telegram.api.Kotlogram import com.github.badoualy.telegram.api.Kotlogram
@ -27,11 +28,12 @@ import java.util.Vector
import java.util.HashMap import java.util.HashMap
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import org.slf4j.Logger import org.slf4j.Logger
class CommandLineController {
private val storage:ApiStorage
var app:TelegramApp
private fun getLine():String { class CommandLineController {
private val storage: ApiStorage
var app: TelegramApp
private fun getLine(): String {
if (System.console() != null) { if (System.console() != null) {
return System.console().readLine("> ") return System.console().readLine("> ")
} else { } else {
@ -40,7 +42,7 @@ class CommandLineController {
} }
} }
private fun getPassword():String { private fun getPassword(): String {
if (System.console() != null) { if (System.console() != null) {
return String(System.console().readPassword("> ")) return String(System.console().readPassword("> "))
} else { } else {
@ -48,26 +50,20 @@ class CommandLineController {
} }
} }
init{ init {
logger.info("CommandLineController started. App version {}", Config.APP_APPVER) logger.info("CommandLineController started. App version {}", Config.APP_APPVER)
this.printHeader() this.printHeader()
if (CommandLineOptions.cmd_version) if (CommandLineOptions.cmd_version) {
{
System.exit(0) System.exit(0)
} } else if (CommandLineOptions.cmd_help) {
else if (CommandLineOptions.cmd_help)
{
this.show_help() this.show_help()
System.exit(0) System.exit(0)
} } else if (CommandLineOptions.cmd_license) {
else if (CommandLineOptions.cmd_license)
{
CommandLineController.show_license() CommandLineController.show_license()
System.exit(0) System.exit(0)
} }
this.setupFileBase() this.setupFileBase()
if (CommandLineOptions.cmd_list_accounts) if (CommandLineOptions.cmd_list_accounts) {
{
this.list_accounts() this.list_accounts()
System.exit(0) System.exit(0)
} }
@ -82,72 +78,53 @@ class CommandLineController {
val handler = TelegramUpdateHandler() val handler = TelegramUpdateHandler()
logger.info("Creating Client") logger.info("Creating Client")
val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler) val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler)
try try {
{
logger.info("Initializing UserManager") logger.info("Initializing UserManager")
UserManager.init(client) UserManager.init(client)
val user = UserManager.getInstance() val user = UserManager.getInstance()
if (!CommandLineOptions.cmd_login && !user.loggedIn) if (!CommandLineOptions.cmd_login && !user.loggedIn) {
{
println("Your authorization data is invalid or missing. You will have to login with Telegram again.") println("Your authorization data is invalid or missing. You will have to login with Telegram again.")
CommandLineOptions.cmd_login = true CommandLineOptions.cmd_login = true
} }
if (account != null && user.loggedIn) if (account != null && user.loggedIn) {
{ if (account != "+" + user.user!!.getPhone()) {
if (account != "+" + user.user!!.getPhone())
{
logger.error("Account: {}, user.user!!.getPhone(): +{}", Utils.anonymize(account), Utils.anonymize(user.user!!.getPhone())) logger.error("Account: {}, user.user!!.getPhone(): +{}", Utils.anonymize(account), Utils.anonymize(user.user!!.getPhone()))
throw RuntimeException("Account / User mismatch") throw RuntimeException("Account / User mismatch")
} }
} }
logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login) logger.debug("CommandLineOptions.cmd_login: {}", CommandLineOptions.cmd_login)
if (CommandLineOptions.cmd_login) if (CommandLineOptions.cmd_login) {
{
cmd_login(account) cmd_login(account)
System.exit(0) System.exit(0)
} }
// If we reach this point, we can assume that there is an account and a database can be loaded / created. // If we reach this point, we can assume that there is an account and a database can be loaded / created.
Database.init(client) Database.init(client)
if (CommandLineOptions.cmd_stats) if (CommandLineOptions.cmd_stats) {
{
cmd_stats() cmd_stats()
System.exit(0) System.exit(0)
} }
if (CommandLineOptions.val_test != null) if (CommandLineOptions.val_test != null) {
{ if (CommandLineOptions.val_test == 1) {
if (CommandLineOptions.val_test == 1)
{
TestFeatures.test1() TestFeatures.test1()
} } else if (CommandLineOptions.val_test == 2) {
else if (CommandLineOptions.val_test == 2)
{
TestFeatures.test2() TestFeatures.test2()
} } else {
else
{
System.out.println("Unknown test " + CommandLineOptions.val_test) System.out.println("Unknown test " + CommandLineOptions.val_test)
} }
System.exit(1) System.exit(1)
} }
logger.debug("CommandLineOptions.val_export: {}", CommandLineOptions.val_export) logger.debug("CommandLineOptions.val_export: {}", CommandLineOptions.val_export)
if (CommandLineOptions.val_export != null) if (CommandLineOptions.val_export != null) {
{ if (CommandLineOptions.val_export!!.toLowerCase().equals("html")) {
if (CommandLineOptions.val_export!!.toLowerCase().equals("html"))
{
(HTMLExporter()).export() (HTMLExporter()).export()
System.exit(0) System.exit(0)
} } else {
else
{
show_error("Unknown export format.") show_error("Unknown export format.")
} }
} }
if (user.loggedIn) if (user.loggedIn) {
{
System.out.println("You are logged in as " + Utils.anonymize(user.userString)) System.out.println("You are logged in as " + Utils.anonymize(user.userString))
} } else {
else
{
println("You are not logged in.") println("You are not logged in.")
System.exit(1) System.exit(1)
} }
@ -156,29 +133,20 @@ class CommandLineController {
logger.debug("Calling DownloadManager.downloadMessages with limit {}", CommandLineOptions.val_limit_messages) logger.debug("Calling DownloadManager.downloadMessages with limit {}", CommandLineOptions.val_limit_messages)
d.downloadMessages(CommandLineOptions.val_limit_messages) d.downloadMessages(CommandLineOptions.val_limit_messages)
logger.debug("CommandLineOptions.cmd_no_media: {}", CommandLineOptions.cmd_no_media) logger.debug("CommandLineOptions.cmd_no_media: {}", CommandLineOptions.cmd_no_media)
if (!CommandLineOptions.cmd_no_media) if (!CommandLineOptions.cmd_no_media) {
{
logger.debug("Calling DownloadManager.downloadMedia") logger.debug("Calling DownloadManager.downloadMedia")
d.downloadMedia() d.downloadMedia()
} } else {
else
{
println("Skipping media download because --no-media is set.") println("Skipping media download because --no-media is set.")
} }
} } catch (e: Exception) {
catch (e:Exception) {
e.printStackTrace() e.printStackTrace()
logger.error("Exception caught!", e) logger.error("Exception caught!", e)
} } finally {
finally if (CommandLineOptions.cmd_daemon) {
{
if (CommandLineOptions.cmd_daemon)
{
handler.activate() handler.activate()
println("DAEMON mode requested - keeping running.") println("DAEMON mode requested - keeping running.")
} } else {
else
{
client.close() client.close()
println() println()
println("----- EXIT -----") println("----- EXIT -----")
@ -186,6 +154,7 @@ class CommandLineController {
} }
} }
} }
private fun printHeader() { private fun printHeader() {
System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz") System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz")
println() println()
@ -193,57 +162,46 @@ class CommandLineController {
println("welcome to redistribute it under certain conditions; run it with '--license' for details.") println("welcome to redistribute it under certain conditions; run it with '--license' for details.")
println() println()
} }
private fun setupFileBase() { private fun setupFileBase() {
logger.debug("Target dir at startup: {}", Utils.anonymize(Config.FILE_BASE)) logger.debug("Target dir at startup: {}", Utils.anonymize(Config.FILE_BASE))
if (CommandLineOptions.val_target != null) if (CommandLineOptions.val_target != null) {
{
Config.FILE_BASE = CommandLineOptions.val_target!! Config.FILE_BASE = CommandLineOptions.val_target!!
} }
logger.debug("Target dir after options: {}", Utils.anonymize(Config.FILE_BASE)) logger.debug("Target dir after options: {}", Utils.anonymize(Config.FILE_BASE))
System.out.println("Base directory for files: " + Utils.anonymize(Config.FILE_BASE)) System.out.println("Base directory for files: " + Utils.anonymize(Config.FILE_BASE))
} }
private fun selectAccount():String? {
private fun selectAccount(): String? {
var account = "none" var account = "none"
val accounts = Utils.getAccounts() val accounts = Utils.getAccounts()
if (CommandLineOptions.cmd_login) if (CommandLineOptions.cmd_login) {
{
logger.debug("Login requested, doing nothing.") logger.debug("Login requested, doing nothing.")
// do nothing // do nothing
} } else if (CommandLineOptions.val_account != null) {
else if (CommandLineOptions.val_account != null)
{
logger.debug("Account requested: {}", Utils.anonymize(CommandLineOptions.val_account!!)) logger.debug("Account requested: {}", Utils.anonymize(CommandLineOptions.val_account!!))
logger.trace("Checking accounts for match.") logger.trace("Checking accounts for match.")
var found = false var found = false
for (acc in accounts) for (acc in accounts) {
{
logger.trace("Checking {}", Utils.anonymize(acc)) logger.trace("Checking {}", Utils.anonymize(acc))
if (acc == CommandLineOptions.val_account) if (acc == CommandLineOptions.val_account) {
{
found = true found = true
logger.trace("Matches.") logger.trace("Matches.")
break break
} }
} }
if (!found) if (!found) {
{
show_error("Couldn't find account '" + Utils.anonymize(CommandLineOptions.val_account!!) + "'. Maybe you want to use '--login' first?") show_error("Couldn't find account '" + Utils.anonymize(CommandLineOptions.val_account!!) + "'. Maybe you want to use '--login' first?")
} }
account = CommandLineOptions.val_account!! account = CommandLineOptions.val_account!!
} } else if (accounts.size == 0) {
else if (accounts.size == 0)
{
println("No accounts found. Starting login process...") println("No accounts found. Starting login process...")
CommandLineOptions.cmd_login = true CommandLineOptions.cmd_login = true
return null return null
} } else if (accounts.size == 1) {
else if (accounts.size == 1)
{
account = accounts.firstElement() account = accounts.firstElement()
System.out.println("Using only available account: " + Utils.anonymize(account)) System.out.println("Using only available account: " + Utils.anonymize(account))
} } else {
else
{
show_error(("You didn't specify which account to use.\n" + show_error(("You didn't specify which account to use.\n" +
"Use '--account <x>' to use account <x>.\n" + "Use '--account <x>' to use account <x>.\n" +
"Use '--list-accounts' to see all available accounts.")) "Use '--list-accounts' to see all available accounts."))
@ -253,6 +211,7 @@ class CommandLineController {
logger.debug("account: {}", Utils.anonymize(account)) logger.debug("account: {}", Utils.anonymize(account))
return account return account
} }
private fun cmd_stats() { private fun cmd_stats() {
println() println()
println("Stats:") println("Stats:")
@ -264,23 +223,21 @@ class CommandLineController {
System.out.format(format, "Top message ID", Database.getInstance().getTopMessageID()) System.out.format(format, "Top message ID", Database.getInstance().getTopMessageID())
println() println()
println("Media Types:") println("Media Types:")
for ((key, value) in Database.getInstance().getMessageMediaTypesWithCount()) for ((key, value) in Database.getInstance().getMessageMediaTypesWithCount()) {
{
System.out.format(format, key, value) System.out.format(format, key, value)
} }
println() println()
println("Api layers of messages:") println("Api layers of messages:")
for ((key, value) in Database.getInstance().getMessageApiLayerWithCount()) for ((key, value) in Database.getInstance().getMessageApiLayerWithCount()) {
{
System.out.format(format, key, value) System.out.format(format, key, value)
} }
} }
@Throws(RpcErrorException::class, IOException::class) @Throws(RpcErrorException::class, IOException::class)
private fun cmd_login(phoneToUse:String?) { private fun cmd_login(phoneToUse: String?) {
val user = UserManager.getInstance() val user = UserManager.getInstance()
val phone: String val phone: String
if (phoneToUse == null) if (phoneToUse == null) {
{
println("Please enter your phone number in international format.") println("Please enter your phone number in international format.")
println("Example: +4917077651234") println("Example: +4917077651234")
phone = getLine() phone = getLine()
@ -291,8 +248,7 @@ class CommandLineController {
println("Telegram sent you a code. Please enter it here.") println("Telegram sent you a code. Please enter it here.")
val code = getLine() val code = getLine()
user.verifyCode(code) user.verifyCode(code)
if (user.isPasswordNeeded) 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.") 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() val pw = getPassword()
user.verifyPassword(pw) user.verifyPassword(pw)
@ -300,6 +256,7 @@ class CommandLineController {
storage.setPrefix("+" + user.user!!.getPhone()) 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.") 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() { private fun show_help() {
println("Valid options are:") println("Valid options are:")
println(" -h, --help Shows this help.") println(" -h, --help Shows this help.")
@ -321,33 +278,32 @@ class CommandLineController {
println(" --with-channels Backup channels as well.") println(" --with-channels Backup channels as well.")
println(" --with-supergroups Backup supergroups as well.") println(" --with-supergroups Backup supergroups as well.")
} }
private fun list_accounts() { private fun list_accounts() {
println("List of available accounts:") println("List of available accounts:")
val accounts = Utils.getAccounts() val accounts = Utils.getAccounts()
if (accounts.size > 0) if (accounts.size > 0) {
{ for (str in accounts) {
for (str in accounts)
{
System.out.println(" " + Utils.anonymize(str)) System.out.println(" " + Utils.anonymize(str))
} }
println("Use '--account <x>' to use one of those accounts.") println("Use '--account <x>' to use one of those accounts.")
} } else {
else
{
println("NO ACCOUNTS FOUND") println("NO ACCOUNTS FOUND")
println("Use '--login' to login to a telegram account.") println("Use '--login' to login to a telegram account.")
} }
} }
companion object { companion object {
private val logger = LoggerFactory.getLogger(CommandLineController::class.java) private val logger = LoggerFactory.getLogger(CommandLineController::class.java)
public fun show_error(error:String) { public fun show_error(error: String) {
logger.error(error) logger.error(error)
println("ERROR: " + error) println("ERROR: " + error)
System.exit(1) System.exit(1)
} }
fun show_license() { fun show_license() {
println("TODO: Print the GPL.") println("TODO: Print the GPL.")
} }
} }
} }

View File

@ -14,6 +14,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */ * along with this program. If not, see <http://www.gnu.org/licenses/>. */
package de.fabianonline.telegram_backup package de.fabianonline.telegram_backup
internal object CommandLineOptions { internal object CommandLineOptions {
public var cmd_console = false public var cmd_console = false
public var cmd_help = false public var cmd_help = false
@ -30,17 +31,16 @@ internal object CommandLineOptions {
var cmd_stats = false var cmd_stats = false
var cmd_channels = false var cmd_channels = false
var cmd_supergroups = false var cmd_supergroups = false
var val_account:String? = null var val_account: String? = null
var val_limit_messages:Int? = null var val_limit_messages: Int? = null
var val_target:String? = null var val_target: String? = null
var val_export:String? = null var val_export: String? = null
var val_test:Int? = null var val_test: Int? = null
@JvmStatic fun parseOptions(args:Array<String>) { @JvmStatic
var last_cmd:String? = null fun parseOptions(args: Array<String>) {
loop@ for (arg in args) var last_cmd: String? = null
{ loop@ for (arg in args) {
if (last_cmd != null) if (last_cmd != null) {
{
when (last_cmd) { when (last_cmd) {
"--account" -> val_account = arg "--account" -> val_account = arg
"--limit-messages" -> val_limit_messages = Integer.parseInt(arg) "--limit-messages" -> val_limit_messages = Integer.parseInt(arg)
@ -90,8 +90,7 @@ internal object CommandLineOptions {
else -> throw RuntimeException("Unknown command " + arg) else -> throw RuntimeException("Unknown command " + arg)
} }
} }
if (last_cmd != null) if (last_cmd != null) {
{
CommandLineController.show_error("Command $last_cmd had no parameter set.") CommandLineController.show_error("Command $last_cmd had no parameter set.")
} }
} }

View File

@ -27,7 +27,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.ConsoleAppender import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.classic.Level import ch.qos.logback.classic.Level
fun main(args: Array<String>) { fun main(args: Array<String>) {
CommandLineOptions.parseOptions(args) CommandLineOptions.parseOptions(args)
CommandLineRunner.setupLogging() CommandLineRunner.setupLogging()
@ -41,7 +41,7 @@ import ch.qos.logback.classic.Level
} else { } else {
GUIController() GUIController()
} }
} }
object CommandLineRunner { object CommandLineRunner {
fun setupLogging() { fun setupLogging() {

View File

@ -327,7 +327,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
logger.debug("Database returned {} messages with media", messages.size) logger.debug("Database returned {} messages with media", messages.size)
prog!!.onMediaDownloadStart(messages.size) prog!!.onMediaDownloadStart(messages.size)
for (msg in messages) { for (msg in messages) {
if (msg==null) continue if (msg == null) continue
val m = FileManagerFactory.getFileManager(msg, user!!, client!!) val m = FileManagerFactory.getFileManager(msg, user!!, client!!)
logger.trace("message {}, {}, {}, {}, {}", logger.trace("message {}, {}, {}, {}, {}",
msg.getId(), msg.getId(),

View File

@ -104,7 +104,7 @@ private constructor(c: TelegramClient) {
@Throws(RpcErrorException::class, IOException::class) @Throws(RpcErrorException::class, IOException::class)
fun verifyPassword(pw: String) { fun verifyPassword(pw: String) {
val password = pw.toByteArray(charset=Charsets.UTF_8) val password = pw.toByteArray(charset = Charsets.UTF_8)
val salt = (client.accountGetPassword() as TLPassword).getCurrentSalt().getData() val salt = (client.accountGetPassword() as TLPassword).getCurrentSalt().getData()
var md: MessageDigest var md: MessageDigest
try { try {

View File

@ -111,8 +111,8 @@ object Utils {
logger.debug("Comparing versions {} and {}.", v1, v2) logger.debug("Comparing versions {} and {}.", v1, v2)
if (v1.equals(v2)) return VERSIONS_EQUAL if (v1.equals(v2)) return VERSIONS_EQUAL
val v1_p = v1.split("-", limit=2) val v1_p = v1.split("-", limit = 2)
val v2_p = v2.split("-", limit=2) val v2_p = v2.split("-", limit = 2)
logger.trace("Parts to compare without suffixes: {} and {}.", v1_p[0], v2_p[0]) logger.trace("Parts to compare without suffixes: {} and {}.", v1_p[0], v2_p[0])

View File

@ -49,7 +49,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
open val isSticker: Boolean open val isSticker: Boolean
get() { get() {
if (this.isEmpty || doc == null) return false if (this.isEmpty || doc == null) return false
return doc!!.getAttributes()?.filter{it is TLDocumentAttributeSticker}?.isNotEmpty() ?: false return doc!!.getAttributes()?.filter { it is TLDocumentAttributeSticker }?.isNotEmpty() ?: false
} }
override val size: Int override val size: Int