1
0
mirror of https://github.com/fabianonline/telegram_backup.git synced 2024-11-22 08:46:15 +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
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
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,11 +28,12 @@ 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 {
class CommandLineController {
private val storage: ApiStorage
var app: TelegramApp
private fun getLine(): String {
if (System.console() != null) {
return System.console().readLine("> ")
} else {
@ -40,7 +42,7 @@ class CommandLineController {
}
}
private fun getPassword():String {
private fun getPassword(): String {
if (System.console() != null) {
return String(System.console().readPassword("> "))
} else {
@ -48,26 +50,20 @@ class CommandLineController {
}
}
init{
init {
logger.info("CommandLineController started. App version {}", Config.APP_APPVER)
this.printHeader()
if (CommandLineOptions.cmd_version)
{
if (CommandLineOptions.cmd_version) {
System.exit(0)
}
else if (CommandLineOptions.cmd_help)
{
} else if (CommandLineOptions.cmd_help) {
this.show_help()
System.exit(0)
}
else if (CommandLineOptions.cmd_license)
{
} else if (CommandLineOptions.cmd_license) {
CommandLineController.show_license()
System.exit(0)
}
this.setupFileBase()
if (CommandLineOptions.cmd_list_accounts)
{
if (CommandLineOptions.cmd_list_accounts) {
this.list_accounts()
System.exit(0)
}
@ -82,72 +78,53 @@ class CommandLineController {
val handler = TelegramUpdateHandler()
logger.info("Creating Client")
val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, handler)
try
{
try {
logger.info("Initializing UserManager")
UserManager.init(client)
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.")
CommandLineOptions.cmd_login = true
}
if (account != null && user.loggedIn)
{
if (account != "+" + user.user!!.getPhone())
{
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)
{
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)
{
if (CommandLineOptions.cmd_stats) {
cmd_stats()
System.exit(0)
}
if (CommandLineOptions.val_test != null)
{
if (CommandLineOptions.val_test == 1)
{
if (CommandLineOptions.val_test != null) {
if (CommandLineOptions.val_test == 1) {
TestFeatures.test1()
}
else if (CommandLineOptions.val_test == 2)
{
} else if (CommandLineOptions.val_test == 2) {
TestFeatures.test2()
}
else
{
} 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"))
{
if (CommandLineOptions.val_export != null) {
if (CommandLineOptions.val_export!!.toLowerCase().equals("html")) {
(HTMLExporter()).export()
System.exit(0)
}
else
{
} else {
show_error("Unknown export format.")
}
}
if (user.loggedIn)
{
if (user.loggedIn) {
System.out.println("You are logged in as " + Utils.anonymize(user.userString))
}
else
{
} else {
println("You are not logged in.")
System.exit(1)
}
@ -156,29 +133,20 @@ class CommandLineController {
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)
{
if (!CommandLineOptions.cmd_no_media) {
logger.debug("Calling DownloadManager.downloadMedia")
d.downloadMedia()
}
else
{
} else {
println("Skipping media download because --no-media is set.")
}
}
catch (e:Exception) {
} catch (e: Exception) {
e.printStackTrace()
logger.error("Exception caught!", e)
}
finally
{
if (CommandLineOptions.cmd_daemon)
{
} finally {
if (CommandLineOptions.cmd_daemon) {
handler.activate()
println("DAEMON mode requested - keeping running.")
}
else
{
} else {
client.close()
println()
println("----- EXIT -----")
@ -186,6 +154,7 @@ class CommandLineController {
}
}
}
private fun printHeader() {
System.out.println("Telegram_Backup version " + Config.APP_APPVER + ", Copyright (C) 2016, 2017 Fabian Schlenz")
println()
@ -193,57 +162,46 @@ class CommandLineController {
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)
{
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? {
private fun selectAccount(): String? {
var account = "none"
val accounts = Utils.getAccounts()
if (CommandLineOptions.cmd_login)
{
if (CommandLineOptions.cmd_login) {
logger.debug("Login requested, doing 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.trace("Checking accounts for match.")
var found = false
for (acc in accounts)
{
for (acc in accounts) {
logger.trace("Checking {}", Utils.anonymize(acc))
if (acc == CommandLineOptions.val_account)
{
if (acc == CommandLineOptions.val_account) {
found = true
logger.trace("Matches.")
break
}
}
if (!found)
{
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)
{
} else if (accounts.size == 0) {
println("No accounts found. Starting login process...")
CommandLineOptions.cmd_login = true
return null
}
else if (accounts.size == 1)
{
} else if (accounts.size == 1) {
account = accounts.firstElement()
System.out.println("Using only available account: " + Utils.anonymize(account))
}
else
{
} else {
show_error(("You didn't specify which account to use.\n" +
"Use '--account <x>' to use account <x>.\n" +
"Use '--list-accounts' to see all available accounts."))
@ -253,6 +211,7 @@ class CommandLineController {
logger.debug("account: {}", Utils.anonymize(account))
return account
}
private fun cmd_stats() {
println()
println("Stats:")
@ -264,23 +223,21 @@ class CommandLineController {
System.out.format(format, "Top message ID", Database.getInstance().getTopMessageID())
println()
println("Media Types:")
for ((key, value) in Database.getInstance().getMessageMediaTypesWithCount())
{
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())
{
for ((key, value) in Database.getInstance().getMessageApiLayerWithCount()) {
System.out.format(format, key, value)
}
}
@Throws(RpcErrorException::class, IOException::class)
private fun cmd_login(phoneToUse:String?) {
private fun cmd_login(phoneToUse: String?) {
val user = UserManager.getInstance()
val phone: String
if (phoneToUse == null)
{
if (phoneToUse == null) {
println("Please enter your phone number in international format.")
println("Example: +4917077651234")
phone = getLine()
@ -291,8 +248,7 @@ class CommandLineController {
println("Telegram sent you a code. Please enter it here.")
val code = getLine()
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.")
val pw = getPassword()
user.verifyPassword(pw)
@ -300,6 +256,7 @@ class CommandLineController {
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.")
@ -321,33 +278,32 @@ class CommandLineController {
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)
{
if (accounts.size > 0) {
for (str in accounts) {
System.out.println(" " + Utils.anonymize(str))
}
println("Use '--account <x>' to use one of those accounts.")
}
else
{
} 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) {
public fun show_error(error: String) {
logger.error(error)
println("ERROR: " + error)
System.exit(1)
}
fun show_license() {
println("TODO: Print the GPL.")
}
}
}
}

View File

@ -14,6 +14,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
package de.fabianonline.telegram_backup
internal object CommandLineOptions {
public var cmd_console = false
public var cmd_help = false
@ -30,17 +31,16 @@ internal object CommandLineOptions {
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<String>) {
var last_cmd:String? = null
loop@ for (arg in args)
{
if (last_cmd != null)
{
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<String>) {
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)
@ -90,8 +90,7 @@ internal object CommandLineOptions {
else -> throw RuntimeException("Unknown command " + arg)
}
}
if (last_cmd != null)
{
if (last_cmd != null) {
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.classic.Level
fun main(args: Array<String>) {
fun main(args: Array<String>) {
CommandLineOptions.parseOptions(args)
CommandLineRunner.setupLogging()
@ -41,7 +41,7 @@ import ch.qos.logback.classic.Level
} else {
GUIController()
}
}
}
object CommandLineRunner {
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)
prog!!.onMediaDownloadStart(messages.size)
for (msg in messages) {
if (msg==null) continue
if (msg == null) continue
val m = FileManagerFactory.getFileManager(msg, user!!, client!!)
logger.trace("message {}, {}, {}, {}, {}",
msg.getId(),

View File

@ -104,7 +104,7 @@ private constructor(c: TelegramClient) {
@Throws(RpcErrorException::class, IOException::class)
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()
var md: MessageDigest
try {

View File

@ -111,8 +111,8 @@ object Utils {
logger.debug("Comparing versions {} and {}.", v1, v2)
if (v1.equals(v2)) return VERSIONS_EQUAL
val v1_p = v1.split("-", limit=2)
val v2_p = v2.split("-", limit=2)
val v1_p = v1.split("-", limit = 2)
val v2_p = v2.split("-", limit = 2)
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
get() {
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