Kotlin: It now compiles without any errors and / or warnings. But running it fails because raw JDBC isn't very Kotlin compatible, it seems.

This commit is contained in:
Fabian Schlenz 2017-12-11 18:39:30 +01:00
parent f75a90936d
commit 9bc2ed7666
21 changed files with 153 additions and 159 deletions

View File

@ -1,7 +1,7 @@
apply plugin: 'java'
apply plugin: 'application'
mainClassName= 'de.fabianonline.telegram_backup.CommandLineRunner'
mainClassName= 'de.fabianonline.telegram_backup.CommandLineRunnerKt'
repositories {
mavenCentral()

View File

@ -87,8 +87,8 @@ internal class ApiStorage(prefix: String?) : TelegramApiStorage {
return null
}
override fun saveDc(dc: DataCenter) {
this.dc = dc
override fun saveDc(dataCenter: DataCenter) {
this.dc = dataCenter
this._saveDc()
}

View File

@ -115,13 +115,13 @@ class CommandLineController {
}
if (CommandLineOptions.val_test != null)
{
if (CommandLineOptions.val_test === 1)
if (CommandLineOptions.val_test == 1)
{
TestFeatures.test1()
}
else if (CommandLineOptions.val_test === 2)
else if (CommandLineOptions.val_test == 2)
{
TestFeatures.test2(user, client)
TestFeatures.test2()
}
else
{

View File

@ -54,15 +54,15 @@ internal class CommandLineDownloadProgress : DownloadProgressInterface {
println("" + count + " Files to check / download")
}
override fun onMediaDownloaded(fm: AbstractMediaFileManager) {
show(fm.letter.toUpperCase())
override fun onMediaDownloaded(file_manager: AbstractMediaFileManager) {
show(file_manager.letter.toUpperCase())
}
override fun onMediaDownloadedEmpty() {
show("e")
}
override fun onMediaAlreadyPresent(fm: AbstractMediaFileManager) {
override fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager) {
show(".")
}

View File

@ -27,12 +27,11 @@ import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.classic.Level
object CommandLineRunner {
fun main(args: Array<String>) {
CommandLineOptions.parseOptions(args)
setupLogging()
checkVersion()
CommandLineRunner.setupLogging()
CommandLineRunner.checkVersion()
@ -44,8 +43,10 @@ object CommandLineRunner {
}
}
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()
@ -76,14 +77,14 @@ object CommandLineRunner {
fun checkVersion(): Boolean {
val v = Utils.getNewestVersion()
if (v != null && v!!.isNewer) {
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("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(v.body)
System.out.println()
return false
}

View File

@ -49,7 +49,7 @@ object Config {
init {
val p = Properties()
try {
p.load(Config::class.java!!.getResourceAsStream("/build.properties"))
p.load(Config::class.java.getResourceAsStream("/build.properties"))
APP_APPVER = p.getProperty("version")
} catch (e: IOException) {
throw RuntimeException(e)

View File

@ -132,8 +132,7 @@ class Database private constructor(var client: TelegramClient) {
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)
if (layer == null) layer = 0
map.put("count.messages.api_layer." + layer!!, rs.getInt(1))
map.put("count.messages.api_layer.$layer", rs.getInt(1))
}
rs.close()
return map
@ -286,15 +285,15 @@ class Database private constructor(var client: TelegramClient) {
for (abs in all) {
if (abs is TLMessage) {
val msg = abs as TLMessage
val msg = abs
ps.setInt(1, msg.getId())
ps.setString(2, "message")
val peer = msg.getToId()
if (peer is TLPeerChat) {
ps.setString(3, "group")
ps.setInt(4, (peer as TLPeerChat).getChatId())
ps.setInt(4, peer.getChatId())
} else if (peer is TLPeerUser) {
var id = (peer as TLPeerUser).getUserId()
var id = peer.getUserId()
if (id == this.user_manager.user!!.getId()) {
id = msg.getFromId()
}
@ -321,11 +320,12 @@ class Database private constructor(var client: TelegramClient) {
}
var text = msg.getMessage()
if ((text == null || text!!.equals("")) && msg.getMedia() != null) {
if (msg.getMedia() is TLMessageMediaDocument) {
text = (msg.getMedia() as TLMessageMediaDocument).getCaption()
} else if (msg.getMedia() is TLMessageMediaPhoto) {
text = (msg.getMedia() as TLMessageMediaPhoto).getCaption()
if ((text == null || text.equals("")) && msg.getMedia() != null) {
val media = msg.getMedia()
if (media is TLMessageMediaDocument) {
text = media.getCaption()
} else if (media is TLMessageMediaPhoto) {
text = media.getCaption()
}
}
ps.setString(7, text)
@ -419,19 +419,19 @@ class Database private constructor(var client: TelegramClient) {
ps_insert_or_ignore.setString(3, "empty_chat")
ps_insert_or_ignore.addBatch()
} else if (abs is TLChatForbidden) {
ps_insert_or_replace.setString(2, (abs as TLChatForbidden).getTitle())
ps_insert_or_replace.setString(2, abs.getTitle())
ps_insert_or_replace.setString(3, "chat")
ps_insert_or_replace.addBatch()
} else if (abs is TLChannelForbidden) {
ps_insert_or_replace.setString(2, (abs as TLChannelForbidden).getTitle())
ps_insert_or_replace.setString(2, abs.getTitle())
ps_insert_or_replace.setString(3, "channel")
ps_insert_or_replace.addBatch()
} else if (abs is TLChat) {
ps_insert_or_replace.setString(2, (abs as TLChat).getTitle())
ps_insert_or_replace.setString(2, abs.getTitle())
ps_insert_or_replace.setString(3, "chat")
ps_insert_or_replace.addBatch()
} else if (abs is TLChannel) {
ps_insert_or_replace.setString(2, (abs as TLChannel).getTitle())
ps_insert_or_replace.setString(2, abs.getTitle())
ps_insert_or_replace.setString(3, "channel")
ps_insert_or_replace.addBatch()
} else {
@ -467,7 +467,7 @@ class Database private constructor(var client: TelegramClient) {
"(?, ?, ?, ?, ?, ?)")
for (abs in all) {
if (abs is TLUser) {
val user = abs as TLUser
val user = 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())
@ -542,7 +542,7 @@ class Database private constructor(var client: TelegramClient) {
} else {
count += rs.getInt(2)
}
map.put("count.messages.media_type." + s!!, rs.getInt(2))
map.put("count.messages.media_type.$s", rs.getInt(2))
}
map.put("count.messages.media_type.any", count)
return map
@ -567,9 +567,9 @@ class Database private constructor(var client: TelegramClient) {
while (rs.next()) {
val u: User
if (rs.getString(2) != null || rs.getString(3) != null || rs.getString(4) != null) {
u = User(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4))
u = User(rs.getInt(1), rs.getString(2), rs.getString(3))
} else {
u = User(rs.getInt(1), "Unknown", "", "")
u = User(rs.getInt(1), "Unknown", "")
}
if (u.isMe) {
map.put("authors.count.me", rs.getInt(5))
@ -595,7 +595,7 @@ class Database private constructor(var client: TelegramClient) {
"COUNT(id) FROM messages WHERE " + c.query + " GROUP BY hour, day " +
"ORDER BY hour, day")
while (rs.next()) {
result[if (rs.getInt(1) === 0) 6 else rs.getInt(1) - 1][rs.getInt(2)] = rs.getInt(3)
result[if (rs.getInt(1) == 0) 6 else rs.getInt(1) - 1][rs.getInt(2)] = rs.getInt(3)
}
return result
} catch (e: Exception) {
@ -638,10 +638,10 @@ class Database private constructor(var client: TelegramClient) {
if (rs.getString("media_type") != null) {
h.put("media_" + rs.getString("media_type"), true)
}
h.put("from_me", rs.getInt("user_id") === user_manager.user!!.getId())
h.put("from_me", rs.getInt("user_id") == user_manager.user!!.getId())
h.put("is_new_date", !date.equals(old_date))
h.put("odd_even", if (count % 2 == 0) "even" else "odd")
h.put("same_user", old_user != null && rs.getInt("user_id") === old_user)
h.put("same_user", old_user != 0 && rs.getInt("user_id") == old_user)
old_user = rs.getInt("user_id")
old_date = date
@ -674,7 +674,7 @@ class Database private constructor(var client: TelegramClient) {
get() = "source_type IN('group', 'supergroup', 'channel') AND source_id=" + id
}
inner class User(id: Int, first_name: String?, last_name: String?, username: String) {
inner class User(id: Int, first_name: String?, last_name: String?) {
var name: String
var isMe: Boolean = false

View File

@ -43,7 +43,7 @@ class DatabaseUpdates(protected var conn: Connection, protected var db: Database
logger.debug("Checking if table database_versions exists")
rs = stmt.executeQuery("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='database_versions'")
rs.next()
if (rs.getInt(1) === 0) {
if (rs.getInt(1) == 0) {
logger.debug("Table does not exist")
version = 0
} else {
@ -286,10 +286,10 @@ internal class DB_Update_6(conn: Connection, db: Database) : DatabaseUpdate(conn
while (rs.next()) {
ps.setInt(5, rs.getInt(1))
val msg = Database.bytesToTLMessage(rs.getBytes(2))
if (msg == null || msg!!.getFwdFrom() == null) {
if (msg == null || msg.getFwdFrom() == null) {
ps.setNull(1, Types.INTEGER)
} else {
ps.setInt(1, msg!!.getFwdFrom().getFromId())
ps.setInt(1, msg.getFwdFrom().getFromId())
}
val f = FileManagerFactory.getFileManager(msg, db.user_manager, db.client)
if (f == null) {

View File

@ -66,13 +66,13 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
@Throws(RpcErrorException::class, IOException::class)
fun downloadMessages(limit: Int?) {
var completed = true
var completed: Boolean
do {
completed = true
try {
_downloadMessages(limit)
} catch (e: RpcErrorException) {
if (e.getCode() === 420) { // FLOOD_WAIT
if (e.getCode() == 420) { // FLOOD_WAIT
completed = false
Utils.obeyFloodWaitException(e)
} else {
@ -118,8 +118,8 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
var max_database_id = db!!.getTopMessageID()
System.out.println("Top message ID in database is " + max_database_id)
if (limit != null) {
System.out.println("Limit is set to " + limit!!)
max_database_id = Math.max(max_database_id, max_message_id - limit!!)
System.out.println("Limit is set to " + limit)
max_database_id = Math.max(max_database_id, max_message_id - limit)
System.out.println("New top message id 'in database' is " + max_database_id)
}
if (max_message_id - max_database_id > 1000000) {
@ -142,7 +142,6 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
}
logger.info("Searching for missing messages in the db")
val count_missing = 0
System.out.println("Checking message database for completeness...")
val db_count = db!!.getMessageCount()
val db_max = db!!.getTopMessageID()
@ -182,10 +181,9 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
// TODO Add chat title (and other stuff?) to the database
for (c in dialogs.getChats()) {
if (c is TLChannel) {
val ch = c as TLChannel
channel_access_hashes.put(c.getId(), ch.getAccessHash())
channel_names.put(c.getId(), ch.getTitle())
if (ch.getMegagroup()) {
channel_access_hashes.put(c.getId(), c.getAccessHash())
channel_names.put(c.getId(), c.getTitle())
if (c.getMegagroup()) {
supergroups.add(c.getId())
} else {
channels.add(c.getId())
@ -216,7 +214,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
channel_name = "?"
}
val channel = TLInputChannel(channel_id, access_hash)
downloadMessages(ids, channel, "channel " + channel_name!!)
downloadMessages(ids, channel, "channel $channel_name")
}
}
}
@ -234,7 +232,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
val download_count = Config.GET_MESSAGES_BATCH_SIZE
logger.trace("download_count: {}", download_count)
for (i in 0 until download_count) {
if (ids.size === 0) break
if (ids.size == 0) break
vector.add(ids.removeAt(0))
}
logger.trace("vector.size(): {}", vector.size)
@ -256,7 +254,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
}
break
} catch (e: RpcErrorException) {
if (e.getCode() === 420) { // FLOOD_WAIT
if (e.getCode() == 420) { // FLOOD_WAIT
Utils.obeyFloodWaitException(e, has_seen_flood_wait_message)
has_seen_flood_wait_message = true
} else {
@ -266,7 +264,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
}
logger.trace("response.getMessages().size(): {}", response.getMessages().size)
if (response.getMessages().size !== vector.size) {
if (response.getMessages().size != vector.size) {
CommandLineController.show_error("Requested ${vector.size} messages, but got ${response.getMessages().size}. That is unexpected. Quitting.")
}
@ -289,7 +287,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
@Throws(RpcErrorException::class, IOException::class)
fun downloadMedia() {
download_client = client!!.getDownloaderClient()
var completed = true
var completed: Boolean
do {
completed = true
try {
@ -367,19 +365,19 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
internal val logger = LoggerFactory.getLogger(DownloadManager::class.java)
@Throws(RpcErrorException::class, IOException::class, TimeoutException::class)
fun downloadFile(client: TelegramClient, targetFilename: String, size: Int, dcId: Int, volumeId: Long, localId: Int, secret: Long) {
fun downloadFile(targetFilename: String, size: Int, dcId: Int, volumeId: Long, localId: Int, secret: Long) {
val loc = TLInputFileLocation(volumeId, localId, secret)
downloadFileFromDc(client, targetFilename, loc, dcId, size)
downloadFileFromDc(targetFilename, loc, dcId, size)
}
@Throws(RpcErrorException::class, IOException::class, TimeoutException::class)
fun downloadFile(client: TelegramClient, targetFilename: String, size: Int, dcId: Int, id: Long, accessHash: Long) {
fun downloadFile(targetFilename: String, size: Int, dcId: Int, id: Long, accessHash: Long) {
val loc = TLInputDocumentFileLocation(id, accessHash)
downloadFileFromDc(client, targetFilename, loc, dcId, size)
downloadFileFromDc(targetFilename, loc, dcId, size)
}
@Throws(RpcErrorException::class, IOException::class, TimeoutException::class)
private fun downloadFileFromDc(client: TelegramClient, target: String, loc: TLAbsInputFileLocation, dcID: Int, size: Int): Boolean {
private fun downloadFileFromDc(target: String, loc: TLAbsInputFileLocation, dcID: Int, size: Int): Boolean {
var fos: FileOutputStream? = null
try {
val temp_filename = target + ".downloading"
@ -389,7 +387,7 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
var offset = 0
if (File(temp_filename).isFile()) {
logger.info("Temporary filename already exists; continuing this file")
offset = File(temp_filename).length() as Int
offset = File(temp_filename).length().toInt()
if (offset >= size) {
logger.warn("Temporary file size is >= the target size. Assuming corrupt file & deleting it")
File(temp_filename).delete()
@ -405,18 +403,13 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
logger.trace("offset: {} block_size: {} size: {}", offset, size, size)
val req = TLRequestUploadGetFile(loc, offset, size)
try {
if (dcID == null) {
response = download_client!!.executeRpcQuery(req) as TLFile
} else {
response = download_client!!.executeRpcQuery(req, dcID) as TLFile
}
response = download_client!!.executeRpcQuery(req, dcID) as TLFile
} catch (e: RpcErrorException) {
if (e.getTag().startsWith("420: FLOOD_WAIT_")) {
try_again = true
Utils.obeyFloodWaitException(e)
} else if (e.getCode() === 400) {
} else if (e.getCode() == 400) {
//Somehow this file is broken. No idea why. Let's skip it for now
try_again = true
return false
} else {
throw e
@ -424,17 +417,17 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
}
offset += response!!.getBytes().getData().size
logger.trace("response: {} total size: {}", response!!.getBytes().getData().size, offset)
logger.trace("response: {} total size: {}", response.getBytes().getData().size, offset)
fos!!.write(response!!.getBytes().getData())
fos!!.flush()
fos.write(response.getBytes().getData())
fos.flush()
try {
TimeUnit.MILLISECONDS.sleep(Config.DELAY_AFTER_GET_FILE)
} catch (e: InterruptedException) {
}
} while (offset < size && (response!!.getBytes().getData().size > 0 || try_again))
fos!!.close()
fos.close()
if (offset < size) {
System.out.println("Requested file $target with $size bytes, but got only $offset bytes.")
File(temp_filename).delete()
@ -466,12 +459,12 @@ class DownloadManager(internal var client: TelegramClient?, p: DownloadProgressI
last_download_succeeded = true
return true
} catch (ex: java.io.IOException) {
if (fos != null) fos!!.close()
if (fos != null) fos.close()
System.out.println("IOException happened while downloading " + target)
throw ex
} catch (ex: RpcErrorException) {
if (fos != null) fos!!.close()
if (ex.getCode() === 500) {
if (fos != null) fos.close()
if (ex.getCode() == 500) {
if (!last_download_succeeded) {
System.out.println("Got an Internal Server Error from Telegram. Since the file downloaded before also happened to get this error, we will stop downloading now. Please try again later.")
throw ex

View File

@ -24,9 +24,9 @@ interface DownloadProgressInterface {
fun onMessageDownloadFinished()
fun onMediaDownloadStart(count: Int)
fun onMediaDownloaded(a: AbstractMediaFileManager)
fun onMediaDownloaded(file_manager: AbstractMediaFileManager)
fun onMediaDownloadedEmpty()
fun onMediaSkipped()
fun onMediaAlreadyPresent(a: AbstractMediaFileManager)
fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager)
fun onMediaDownloadFinished()
}

View File

@ -33,7 +33,7 @@ class TLRequestAccountGetPasswordWithCurrentSalt : TLMethod<TLPassword>() {
@Throws(IOException::class)
override fun deserializeResponse(stream: InputStream, context: TLContext): TLPassword {
val response = (readTLObject(stream, context) ?: throw IOException("Unable to parse response")) as? TLPassword ?: throw IOException("Incorrect response type, expected getClass().getCanonicalName(), found response.getClass().getCanonicalName()")
return response as TLPassword
return response
}
override fun toString(): String {

View File

@ -37,64 +37,65 @@ internal class TelegramUpdateHandler : UpdateCallback {
this.db = Database.getInstance()
}
override fun onUpdates(c: TelegramClient, u: TLUpdates) {
override fun onUpdates(client: TelegramClient, updates: TLUpdates) {
if (db == null) return
if (debug) System.out.println("onUpdates - " + u.getUpdates().size + " Updates, " + u.getUsers().size + " Users, " + u.getChats().size + " Chats")
for (update in u.getUpdates()) {
processUpdate(update, c)
if (debug) System.out.println("onUpdates - " + updates.getUpdates().size + " Updates, " + updates.getUsers().size + " Users, " + updates.getChats().size + " Chats")
for (update in updates.getUpdates()) {
processUpdate(update, client)
if (debug) System.out.println(" " + update.javaClass.getName())
}
db!!.saveUsers(u.getUsers())
db!!.saveChats(u.getChats())
db!!.saveUsers(updates.getUsers())
db!!.saveChats(updates.getChats())
}
override fun onUpdatesCombined(c: TelegramClient, u: TLUpdatesCombined) {
override fun onUpdatesCombined(client: TelegramClient, updates: TLUpdatesCombined) {
if (db == null) return
if (debug) System.out.println("onUpdatesCombined")
for (update in u.getUpdates()) {
processUpdate(update, c)
for (update in updates.getUpdates()) {
processUpdate(update, client)
}
db!!.saveUsers(u.getUsers())
db!!.saveChats(u.getChats())
db!!.saveUsers(updates.getUsers())
db!!.saveChats(updates.getChats())
}
override fun onUpdateShort(c: TelegramClient, u: TLUpdateShort) {
override fun onUpdateShort(client: TelegramClient, update: TLUpdateShort) {
if (db == null) return
if (debug) System.out.println("onUpdateShort")
processUpdate(u.getUpdate(), c)
if (debug) System.out.println(" " + u.getUpdate().javaClass.getName())
processUpdate(update.getUpdate(), client)
if (debug) System.out.println(" " + update.getUpdate().javaClass.getName())
}
override fun onShortChatMessage(c: TelegramClient, m: TLUpdateShortChatMessage) {
override fun onShortChatMessage(client: TelegramClient, message: TLUpdateShortChatMessage) {
if (db == null) return
if (debug) System.out.println("onShortChatMessage - " + m.getMessage())
if (debug) System.out.println("onShortChatMessage - " + message.getMessage())
val msg = TLMessage(
m.getOut(),
m.getMentioned(),
m.getMediaUnread(),
m.getSilent(),
message.getOut(),
message.getMentioned(),
message.getMediaUnread(),
message.getSilent(),
false,
m.getId(),
m.getFromId(),
TLPeerChat(m.getChatId()),
m.getFwdFrom(),
m.getViaBotId(),
m.getReplyToMsgId(),
m.getDate(),
m.getMessage(), null, null,
m.getEntities(), null, null)
message.getId(),
message.getFromId(),
TLPeerChat(message.getChatId()),
message.getFwdFrom(),
message.getViaBotId(),
message.getReplyToMsgId(),
message.getDate(),
message.getMessage(), null, null,
message.getEntities(), null, null)
val vector = TLVector<TLAbsMessage>(TLAbsMessage::class.java)
vector.add(msg)
db!!.saveMessages(vector, Kotlogram.API_LAYER)
System.out.print('.')
}
override fun onShortMessage(c: TelegramClient, m: TLUpdateShortMessage) {
override fun onShortMessage(client: TelegramClient, message: TLUpdateShortMessage) {
val m = message
if (db == null) return
if (debug) System.out.println("onShortMessage - " + m.getOut() + " - " + m.getUserId() + " - " + m.getMessage())
val from_id: Int
val to_id: Int
if (m.getOut() === true) {
if (m.getOut() == true) {
from_id = user!!.user!!.getId()
to_id = m.getUserId()
} else {
@ -122,28 +123,28 @@ internal class TelegramUpdateHandler : UpdateCallback {
System.out.print('.')
}
override fun onShortSentMessage(c: TelegramClient, m: TLUpdateShortSentMessage) {
override fun onShortSentMessage(client: TelegramClient, message: TLUpdateShortSentMessage) {
if (db == null) return
System.out.println("onShortSentMessage")
}
override fun onUpdateTooLong(c: TelegramClient) {
override fun onUpdateTooLong(client: TelegramClient) {
if (db == null) return
System.out.println("onUpdateTooLong")
}
private fun processUpdate(update: TLAbsUpdate, client: TelegramClient) {
if (update is TLUpdateNewMessage) {
val abs_msg = (update as TLUpdateNewMessage).getMessage()
val abs_msg = update.getMessage()
val vector = TLVector<TLAbsMessage>(TLAbsMessage::class.java)
vector.add(abs_msg)
db!!.saveMessages(vector, Kotlogram.API_LAYER)
System.out.print('.')
if (abs_msg is TLMessage) {
val fm = FileManagerFactory.getFileManager(abs_msg as TLMessage, user!!, client)
if (fm != null && !fm!!.isEmpty && !fm!!.downloaded) {
val fm = FileManagerFactory.getFileManager(abs_msg, user!!, client)
if (fm != null && !fm.isEmpty && !fm.downloaded) {
try {
fm!!.download()
fm.download()
} catch (e: Exception) {
System.out.println("We got an exception while downloading media, but we're going to ignore it.")
System.out.println("Here it is anyway:")

View File

@ -21,12 +21,12 @@ internal object TestFeatures {
val path = "jdbc:sqlite:cache4.db"
var conn: Connection? = null
var conn: Connection
var stmt: Statement? = null
try {
conn = DriverManager.getConnection(path)
stmt = conn!!.createStatement()
stmt = conn.createStatement()
} catch (e: SQLException) {
CommandLineController.show_error("Could not connect to SQLITE database.")
}
@ -55,7 +55,7 @@ internal object TestFeatures {
System.out.println("Unsupported constructor: " + unsupported_constructor)
}
fun test2(user: UserManager, client: TelegramClient) {
fun test2() {
// Prints system.encoding and default charset
System.out.println("Default Charset: " + Charset.defaultCharset())
System.out.println("file.encoding: " + System.getProperty("file.encoding"))

View File

@ -74,7 +74,7 @@ private constructor(c: TelegramClient) {
this.client = c
logger.debug("Calling getFullUser")
try {
val full_user = this.client!!.usersGetFullUser(TLInputUserSelf())
val full_user = this.client.usersGetFullUser(TLInputUserSelf())
this.user = full_user.getUser().getAsUser()
} catch (e: RpcErrorException) {
// This may happen. Ignoring it.
@ -86,17 +86,17 @@ private constructor(c: TelegramClient) {
@Throws(RpcErrorException::class, IOException::class)
fun sendCodeToPhoneNumber(number: String) {
this.phone = number
this.sent_code = this.client!!.authSendCode(false, number, true)
this.sent_code = this.client.authSendCode(false, number, true)
}
@Throws(RpcErrorException::class, IOException::class)
fun verifyCode(code: String) {
this.code = code
try {
this.auth = client!!.authSignIn(phone, this.sent_code!!.getPhoneCodeHash(), this.code)
this.auth = client.authSignIn(phone, this.sent_code!!.getPhoneCodeHash(), this.code)
this.user = auth!!.getUser().getAsUser()
} catch (e: RpcErrorException) {
if (e.getCode() !== 401 || !e.getTag().equals("SESSION_PASSWORD_NEEDED")) throw e
if (e.getCode() != 401 || !e.getTag().equals("SESSION_PASSWORD_NEEDED")) throw e
this.isPasswordNeeded = true
}
@ -105,8 +105,8 @@ private constructor(c: TelegramClient) {
@Throws(RpcErrorException::class, IOException::class)
fun verifyPassword(pw: String) {
val password = pw.toByteArray(charset=Charsets.UTF_8)
val salt = (client!!.accountGetPassword() as TLPassword).getCurrentSalt().getData()
var md: MessageDigest? = null
val salt = (client.accountGetPassword() as TLPassword).getCurrentSalt().getData()
var md: MessageDigest
try {
md = MessageDigest.getInstance("SHA-256")
} catch (e: NoSuchAlgorithmException) {
@ -118,8 +118,8 @@ private constructor(c: TelegramClient) {
System.arraycopy(salt, 0, salted, 0, salt.size)
System.arraycopy(password, 0, salted, salt.size, password.size)
System.arraycopy(salt, 0, salted, salt.size + password.size, salt.size)
val hash = md!!.digest(salted)
auth = client!!.authCheckPassword(TLBytes(hash))
val hash = md.digest(salted)
auth = client.authCheckPassword(TLBytes(hash))
this.user = auth!!.getUser().getAsUser()
}

View File

@ -28,9 +28,9 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory
object Utils {
val VERSIONS_EQUAL = 0
val VERSION_1_NEWER = 1
val VERSION_2_NEWER = 2
@JvmField public val VERSIONS_EQUAL = 0
@JvmField public val VERSION_1_NEWER = 1
@JvmField public val VERSION_2_NEWER = 2
private val logger = LoggerFactory.getLogger(Utils::class.java) as Logger
@ -39,7 +39,7 @@ object Utils {
val folder = File(Config.FILE_BASE)
val files = folder.listFiles()
if (files != null)
for (f in files!!) {
for (f in files) {
if (f.isDirectory() && f.getName().startsWith("+")) {
accounts.add(f.getName())
}
@ -60,19 +60,19 @@ object Utils {
for (e in root)
if (e.isJsonObject()) {
val version = e.getAsJsonObject()
if (version.getAsJsonPrimitive("prerelease").getAsBoolean() === false) {
if (version.getAsJsonPrimitive("prerelease").getAsBoolean() == false) {
newest_version = version
break
}
}
if (newest_version == null) return null
val new_v = newest_version!!.getAsJsonPrimitive("tag_name").getAsString()
val new_v = newest_version.getAsJsonPrimitive("tag_name").getAsString()
logger.debug("Found current release version {}", new_v)
val cur_v = Config.APP_APPVER
val result = compareVersions(cur_v, new_v)
return Version(new_v, newest_version!!.getAsJsonPrimitive("html_url").getAsString(), newest_version!!.getAsJsonPrimitive("body").getAsString(), result == VERSION_2_NEWER)
return Version(new_v, newest_version.getAsJsonPrimitive("html_url").getAsString(), newest_version.getAsJsonPrimitive("body").getAsString(), result == VERSION_2_NEWER)
}
return null
} catch (e: Exception) {
@ -83,14 +83,14 @@ object Utils {
@Throws(RpcErrorException::class)
@JvmOverloads internal fun obeyFloodWaitException(e: RpcErrorException?, silent: Boolean = false) {
if (e == null || e!!.getCode() !== 420) return
if (e == null || e.getCode() != 420) return
val delay: Long = e!!.getTagInteger()!! as Long
val delay: Long = e.getTagInteger()!!.toLong()
if (!silent) {
System.out.println("")
System.out.println(
"Telegram complained about us (okay, me) making too many requests in too short time by\n" +
"sending us \"" + e!!.getTag() + "\" as an error. So we now have to wait a bit. Telegram\n" +
"sending us \"" + e.getTag() + "\" as an error. So we now have to wait a bit. Telegram\n" +
"asked us to wait for " + delay + " seconds.\n" +
"\n" +
"So I'm going to do just that for now. If you don't want to wait, you can quit by pressing\n" +
@ -106,6 +106,7 @@ object Utils {
}
@JvmStatic
fun compareVersions(v1: String, v2: String): Int {
logger.debug("Comparing versions {} and {}.", v1, v2)
if (v1.equals(v2)) return VERSIONS_EQUAL

View File

@ -171,7 +171,7 @@ class HTMLExporter {
return sb.toString()
}
private fun mapToString(map: Map<String, Integer>): String {
private fun mapToString(map: Map<String, Int>): String {
val sb = StringBuilder("[")
for ((key, value) in map) {
sb.append("['$key', $value],")

View File

@ -48,7 +48,6 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
open val isSticker: Boolean
get() {
var sticker: TLDocumentAttributeSticker? = null
if (this.isEmpty || doc == null) return false
return doc!!.getAttributes()?.filter{it is TLDocumentAttributeSticker}?.isNotEmpty() ?: false
}
@ -63,7 +62,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
init {
val d = (msg.getMedia() as TLMessageMediaDocument).getDocument()
if (d is TLDocument) {
this.doc = d as TLDocument
this.doc = d
} else if (d is TLDocumentEmpty) {
this.isEmpty = true
} else {
@ -73,14 +72,13 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
}
private fun processExtension(): String {
if (extension != null) return extension
if (doc == null) return "empty"
var ext: String? = null
var original_filename: String? = null
if (doc!!.getAttributes() != null)
for (attr in doc!!.getAttributes()) {
if (attr is TLDocumentAttributeFilename) {
original_filename = (attr as TLDocumentAttributeFilename).getFileName()
original_filename = attr.getFileName()
}
}
if (original_filename != null) {
@ -93,7 +91,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
}
// Sometimes, extensions contain a trailing double quote. Remove this. Fixes #12.
ext = ext!!.replace("\"", "")
ext = ext.replace("\"", "")
return ext
}
@ -101,7 +99,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
@Throws(RpcErrorException::class, IOException::class, TimeoutException::class)
override fun download() {
if (doc != null) {
DownloadManager.downloadFile(client, targetPathAndFilename, size, doc!!.getDcId(), doc!!.getId(), doc!!.getAccessHash())
DownloadManager.downloadFile(targetPathAndFilename, size, doc!!.getDcId(), doc!!.getId(), doc!!.getAccessHash())
}
}
}

View File

@ -44,7 +44,7 @@ import org.apache.commons.io.FileUtils
object FileManagerFactory {
fun getFileManager(m: TLMessage?, u: UserManager, c: TelegramClient): AbstractMediaFileManager? {
if (m == null) return null
val media = m!!.getMedia() ?: return null
val media = m.getMedia() ?: return null
if (media is TLMessageMediaPhoto) {
return PhotoFileManager(m, u, c)

View File

@ -50,7 +50,7 @@ class GeoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient)
override val size: Int
get() {
val f = File(targetPathAndFilename)
return if (f.isFile()) (f.length() as Int) else 100000
return if (f.isFile()) f.length().toInt() else 100000
}
override val extension: String
@ -63,7 +63,7 @@ class GeoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient)
init {
val g = (msg.getMedia() as TLMessageMediaGeo).getGeo()
if (g is TLGeoPoint) {
this.geo = g as TLGeoPoint
this.geo = g
} else if (g is TLGeoPointEmpty) {
this.isEmpty = true
} else {

View File

@ -55,14 +55,13 @@ class PhotoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient
init {
val p = (msg.getMedia() as TLMessageMediaPhoto).getPhoto()
if (p is TLPhoto) {
this.photo = p as TLPhoto
this.photo = p
var biggest: TLPhotoSize? = null
for (s in photo!!.getSizes())
for (s in photo.getSizes())
if (s is TLPhotoSize) {
val size = s as TLPhotoSize
if (biggest == null || size.getW() > biggest!!.getW() && size.getH() > biggest!!.getH()) {
biggest = size
if (biggest == null || s.getW() > biggest.getW() && s.getH() > biggest.getH()) {
biggest = s
}
}
if (biggest == null) {
@ -81,6 +80,6 @@ class PhotoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient
override fun download() {
if (isEmpty) return
val loc = photo_size.getLocation() as TLFileLocation
DownloadManager.downloadFile(client, targetPathAndFilename, size, loc.getDcId(), loc.getVolumeId(), loc.getLocalId(), loc.getSecret())
DownloadManager.downloadFile(targetPathAndFilename, size, loc.getDcId(), loc.getVolumeId(), loc.getLocalId(), loc.getSecret())
}
}

View File

@ -59,18 +59,19 @@ class StickerFileManager(msg: TLMessage, user: UserManager, client: TelegramClie
var sticker: TLDocumentAttributeSticker? = null
for (attr in doc!!.getAttributes()) {
if (attr is TLDocumentAttributeSticker) {
sticker = attr as TLDocumentAttributeSticker
sticker = attr
}
}
val file = StringBuilder()
if (sticker!!.getStickerset() is TLInputStickerSetShortName) {
file.append((sticker!!.getStickerset() as TLInputStickerSetShortName).getShortName())
} else if (sticker!!.getStickerset() is TLInputStickerSetID) {
file.append((sticker!!.getStickerset() as TLInputStickerSetID).getId())
val set = sticker!!.getStickerset()
if (set is TLInputStickerSetShortName) {
file.append(set.getShortName())
} else if (set is TLInputStickerSetID) {
file.append(set.getId())
}
file.append("_")
file.append(sticker!!.getAlt().hashCode())
file.append(sticker.getAlt().hashCode())
return file.toString()
}