1
0
mirror of https://github.com/fabianonline/telegram_backup.git synced 2024-11-23 01:06:17 +00:00

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: 'java'
apply plugin: 'application' apply plugin: 'application'
mainClassName= 'de.fabianonline.telegram_backup.CommandLineRunner' mainClassName= 'de.fabianonline.telegram_backup.CommandLineRunnerKt'
repositories { repositories {
mavenCentral() mavenCentral()

View File

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

View File

@ -115,13 +115,13 @@ class CommandLineController {
} }
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(user, client) TestFeatures.test2()
} }
else else
{ {

View File

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

View File

@ -27,12 +27,11 @@ 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
object CommandLineRunner {
fun main(args: Array<String>) { fun main(args: Array<String>) {
CommandLineOptions.parseOptions(args) CommandLineOptions.parseOptions(args)
setupLogging() CommandLineRunner.setupLogging()
checkVersion() CommandLineRunner.checkVersion()
@ -44,8 +43,10 @@ object CommandLineRunner {
} }
} }
object CommandLineRunner {
fun setupLogging() { fun setupLogging() {
val logger = LoggerFactory.getLogger(CommandLineRunner::class.java) as Logger 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 rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger
val rootContext = rootLogger.getLoggerContext() val rootContext = rootLogger.getLoggerContext()
rootContext.reset() rootContext.reset()
@ -76,14 +77,14 @@ object CommandLineRunner {
fun checkVersion(): Boolean { fun checkVersion(): Boolean {
val v = Utils.getNewestVersion() 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("A newer version is vailable!")
System.out.println("You are using: " + Config.APP_APPVER) System.out.println("You are using: " + Config.APP_APPVER)
System.out.println("Available: " + v!!.version) System.out.println("Available: " + v.version)
System.out.println("Get it here: " + v!!.url) System.out.println("Get it here: " + v.url)
System.out.println() System.out.println()
System.out.println("Changes in this version:") System.out.println("Changes in this version:")
System.out.println(v!!.body) System.out.println(v.body)
System.out.println() System.out.println()
return false return false
} }

View File

@ -49,7 +49,7 @@ object Config {
init { init {
val p = Properties() val p = Properties()
try { try {
p.load(Config::class.java!!.getResourceAsStream("/build.properties")) p.load(Config::class.java.getResourceAsStream("/build.properties"))
APP_APPVER = p.getProperty("version") APP_APPVER = p.getProperty("version")
} catch (e: IOException) { } catch (e: IOException) {
throw RuntimeException(e) 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") val rs = stmt!!.executeQuery("SELECT COUNT(id), api_layer FROM messages GROUP BY api_layer ORDER BY api_layer")
while (rs.next()) { while (rs.next()) {
var layer = rs.getInt(2) 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() rs.close()
return map return map
@ -286,15 +285,15 @@ class Database private constructor(var client: TelegramClient) {
for (abs in all) { for (abs in all) {
if (abs is TLMessage) { if (abs is TLMessage) {
val msg = abs as TLMessage val msg = abs
ps.setInt(1, msg.getId()) ps.setInt(1, msg.getId())
ps.setString(2, "message") ps.setString(2, "message")
val peer = msg.getToId() val peer = msg.getToId()
if (peer is TLPeerChat) { if (peer is TLPeerChat) {
ps.setString(3, "group") ps.setString(3, "group")
ps.setInt(4, (peer as TLPeerChat).getChatId()) ps.setInt(4, peer.getChatId())
} else if (peer is TLPeerUser) { } else if (peer is TLPeerUser) {
var id = (peer as TLPeerUser).getUserId() var id = peer.getUserId()
if (id == this.user_manager.user!!.getId()) { if (id == this.user_manager.user!!.getId()) {
id = msg.getFromId() id = msg.getFromId()
} }
@ -321,11 +320,12 @@ class Database private constructor(var client: TelegramClient) {
} }
var text = msg.getMessage() var text = msg.getMessage()
if ((text == null || text!!.equals("")) && msg.getMedia() != null) { if ((text == null || text.equals("")) && msg.getMedia() != null) {
if (msg.getMedia() is TLMessageMediaDocument) { val media = msg.getMedia()
text = (msg.getMedia() as TLMessageMediaDocument).getCaption() if (media is TLMessageMediaDocument) {
} else if (msg.getMedia() is TLMessageMediaPhoto) { text = media.getCaption()
text = (msg.getMedia() as TLMessageMediaPhoto).getCaption() } else if (media is TLMessageMediaPhoto) {
text = media.getCaption()
} }
} }
ps.setString(7, text) 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.setString(3, "empty_chat")
ps_insert_or_ignore.addBatch() ps_insert_or_ignore.addBatch()
} else if (abs is TLChatForbidden) { } 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.setString(3, "chat")
ps_insert_or_replace.addBatch() ps_insert_or_replace.addBatch()
} else if (abs is TLChannelForbidden) { } 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.setString(3, "channel")
ps_insert_or_replace.addBatch() ps_insert_or_replace.addBatch()
} else if (abs is TLChat) { } 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.setString(3, "chat")
ps_insert_or_replace.addBatch() ps_insert_or_replace.addBatch()
} else if (abs is TLChannel) { } 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.setString(3, "channel")
ps_insert_or_replace.addBatch() ps_insert_or_replace.addBatch()
} else { } else {
@ -467,7 +467,7 @@ class Database private constructor(var client: TelegramClient) {
"(?, ?, ?, ?, ?, ?)") "(?, ?, ?, ?, ?, ?)")
for (abs in all) { for (abs in all) {
if (abs is TLUser) { if (abs is TLUser) {
val user = abs as TLUser val user = abs
ps_insert_or_replace.setInt(1, user.getId()) ps_insert_or_replace.setInt(1, user.getId())
ps_insert_or_replace.setString(2, user.getFirstName()) ps_insert_or_replace.setString(2, user.getFirstName())
ps_insert_or_replace.setString(3, user.getLastName()) ps_insert_or_replace.setString(3, user.getLastName())
@ -542,7 +542,7 @@ class Database private constructor(var client: TelegramClient) {
} else { } else {
count += rs.getInt(2) 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) map.put("count.messages.media_type.any", count)
return map return map
@ -567,9 +567,9 @@ class Database private constructor(var client: TelegramClient) {
while (rs.next()) { while (rs.next()) {
val u: User val u: User
if (rs.getString(2) != null || rs.getString(3) != null || rs.getString(4) != null) { 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 { } else {
u = User(rs.getInt(1), "Unknown", "", "") u = User(rs.getInt(1), "Unknown", "")
} }
if (u.isMe) { if (u.isMe) {
map.put("authors.count.me", rs.getInt(5)) 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 " + "COUNT(id) FROM messages WHERE " + c.query + " GROUP BY hour, day " +
"ORDER BY hour, day") "ORDER BY hour, day")
while (rs.next()) { 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 return result
} catch (e: Exception) { } catch (e: Exception) {
@ -638,10 +638,10 @@ class Database private constructor(var client: TelegramClient) {
if (rs.getString("media_type") != null) { if (rs.getString("media_type") != null) {
h.put("media_" + rs.getString("media_type"), true) 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("is_new_date", !date.equals(old_date))
h.put("odd_even", if (count % 2 == 0) "even" else "odd") 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_user = rs.getInt("user_id")
old_date = date 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 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 name: String
var isMe: Boolean = false 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") logger.debug("Checking if table database_versions exists")
rs = stmt.executeQuery("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='database_versions'") rs = stmt.executeQuery("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='database_versions'")
rs.next() rs.next()
if (rs.getInt(1) === 0) { if (rs.getInt(1) == 0) {
logger.debug("Table does not exist") logger.debug("Table does not exist")
version = 0 version = 0
} else { } else {
@ -286,10 +286,10 @@ internal class DB_Update_6(conn: Connection, db: Database) : DatabaseUpdate(conn
while (rs.next()) { while (rs.next()) {
ps.setInt(5, rs.getInt(1)) ps.setInt(5, rs.getInt(1))
val msg = Database.bytesToTLMessage(rs.getBytes(2)) val msg = Database.bytesToTLMessage(rs.getBytes(2))
if (msg == null || msg!!.getFwdFrom() == null) { if (msg == null || msg.getFwdFrom() == null) {
ps.setNull(1, Types.INTEGER) ps.setNull(1, Types.INTEGER)
} else { } else {
ps.setInt(1, msg!!.getFwdFrom().getFromId()) ps.setInt(1, msg.getFwdFrom().getFromId())
} }
val f = FileManagerFactory.getFileManager(msg, db.user_manager, db.client) val f = FileManagerFactory.getFileManager(msg, db.user_manager, db.client)
if (f == null) { if (f == null) {

View File

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

View File

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

View File

@ -33,7 +33,7 @@ class TLRequestAccountGetPasswordWithCurrentSalt : TLMethod<TLPassword>() {
@Throws(IOException::class) @Throws(IOException::class)
override fun deserializeResponse(stream: InputStream, context: TLContext): TLPassword { 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()") 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 { override fun toString(): String {

View File

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

View File

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

View File

@ -74,7 +74,7 @@ private constructor(c: TelegramClient) {
this.client = c this.client = c
logger.debug("Calling getFullUser") logger.debug("Calling getFullUser")
try { try {
val full_user = this.client!!.usersGetFullUser(TLInputUserSelf()) val full_user = this.client.usersGetFullUser(TLInputUserSelf())
this.user = full_user.getUser().getAsUser() this.user = full_user.getUser().getAsUser()
} catch (e: RpcErrorException) { } catch (e: RpcErrorException) {
// This may happen. Ignoring it. // This may happen. Ignoring it.
@ -86,17 +86,17 @@ private constructor(c: TelegramClient) {
@Throws(RpcErrorException::class, IOException::class) @Throws(RpcErrorException::class, IOException::class)
fun sendCodeToPhoneNumber(number: String) { fun sendCodeToPhoneNumber(number: String) {
this.phone = number 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) @Throws(RpcErrorException::class, IOException::class)
fun verifyCode(code: String) { fun verifyCode(code: String) {
this.code = code this.code = code
try { 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() this.user = auth!!.getUser().getAsUser()
} catch (e: RpcErrorException) { } 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 this.isPasswordNeeded = true
} }
@ -105,8 +105,8 @@ 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? = null var md: MessageDigest
try { try {
md = MessageDigest.getInstance("SHA-256") md = MessageDigest.getInstance("SHA-256")
} catch (e: NoSuchAlgorithmException) { } catch (e: NoSuchAlgorithmException) {
@ -118,8 +118,8 @@ private constructor(c: TelegramClient) {
System.arraycopy(salt, 0, salted, 0, salt.size) System.arraycopy(salt, 0, salted, 0, salt.size)
System.arraycopy(password, 0, salted, salt.size, password.size) System.arraycopy(password, 0, salted, salt.size, password.size)
System.arraycopy(salt, 0, salted, salt.size + password.size, salt.size) System.arraycopy(salt, 0, salted, salt.size + password.size, salt.size)
val hash = md!!.digest(salted) val hash = md.digest(salted)
auth = client!!.authCheckPassword(TLBytes(hash)) auth = client.authCheckPassword(TLBytes(hash))
this.user = auth!!.getUser().getAsUser() this.user = auth!!.getUser().getAsUser()
} }

View File

@ -28,9 +28,9 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
object Utils { object Utils {
val VERSIONS_EQUAL = 0 @JvmField public val VERSIONS_EQUAL = 0
val VERSION_1_NEWER = 1 @JvmField public val VERSION_1_NEWER = 1
val VERSION_2_NEWER = 2 @JvmField public val VERSION_2_NEWER = 2
private val logger = LoggerFactory.getLogger(Utils::class.java) as Logger private val logger = LoggerFactory.getLogger(Utils::class.java) as Logger
@ -39,7 +39,7 @@ object Utils {
val folder = File(Config.FILE_BASE) val folder = File(Config.FILE_BASE)
val files = folder.listFiles() val files = folder.listFiles()
if (files != null) if (files != null)
for (f in files!!) { for (f in files) {
if (f.isDirectory() && f.getName().startsWith("+")) { if (f.isDirectory() && f.getName().startsWith("+")) {
accounts.add(f.getName()) accounts.add(f.getName())
} }
@ -60,19 +60,19 @@ object Utils {
for (e in root) for (e in root)
if (e.isJsonObject()) { if (e.isJsonObject()) {
val version = e.getAsJsonObject() val version = e.getAsJsonObject()
if (version.getAsJsonPrimitive("prerelease").getAsBoolean() === false) { if (version.getAsJsonPrimitive("prerelease").getAsBoolean() == false) {
newest_version = version newest_version = version
break break
} }
} }
if (newest_version == null) return null 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) logger.debug("Found current release version {}", new_v)
val cur_v = Config.APP_APPVER val cur_v = Config.APP_APPVER
val result = compareVersions(cur_v, new_v) 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 return null
} catch (e: Exception) { } catch (e: Exception) {
@ -83,14 +83,14 @@ object Utils {
@Throws(RpcErrorException::class) @Throws(RpcErrorException::class)
@JvmOverloads internal fun obeyFloodWaitException(e: RpcErrorException?, silent: Boolean = false) { @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) { if (!silent) {
System.out.println("") System.out.println("")
System.out.println( System.out.println(
"Telegram complained about us (okay, me) making too many requests in too short time by\n" + "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" + "asked us to wait for " + delay + " seconds.\n" +
"\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" + "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 { fun compareVersions(v1: String, v2: String): Int {
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

View File

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

View File

@ -48,7 +48,6 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
open val isSticker: Boolean open val isSticker: Boolean
get() { get() {
var sticker: TLDocumentAttributeSticker? = null
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
} }
@ -63,7 +62,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
init { init {
val d = (msg.getMedia() as TLMessageMediaDocument).getDocument() val d = (msg.getMedia() as TLMessageMediaDocument).getDocument()
if (d is TLDocument) { if (d is TLDocument) {
this.doc = d as TLDocument this.doc = d
} else if (d is TLDocumentEmpty) { } else if (d is TLDocumentEmpty) {
this.isEmpty = true this.isEmpty = true
} else { } else {
@ -73,14 +72,13 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
} }
private fun processExtension(): String { private fun processExtension(): String {
if (extension != null) return extension
if (doc == null) return "empty" if (doc == null) return "empty"
var ext: String? = null var ext: String? = null
var original_filename: String? = null var original_filename: String? = null
if (doc!!.getAttributes() != null) if (doc!!.getAttributes() != null)
for (attr in doc!!.getAttributes()) { for (attr in doc!!.getAttributes()) {
if (attr is TLDocumentAttributeFilename) { if (attr is TLDocumentAttributeFilename) {
original_filename = (attr as TLDocumentAttributeFilename).getFileName() original_filename = attr.getFileName()
} }
} }
if (original_filename != null) { 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. // Sometimes, extensions contain a trailing double quote. Remove this. Fixes #12.
ext = ext!!.replace("\"", "") ext = ext.replace("\"", "")
return ext return ext
} }
@ -101,7 +99,7 @@ open class DocumentFileManager(msg: TLMessage, user: UserManager, client: Telegr
@Throws(RpcErrorException::class, IOException::class, TimeoutException::class) @Throws(RpcErrorException::class, IOException::class, TimeoutException::class)
override fun download() { override fun download() {
if (doc != null) { 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 { object FileManagerFactory {
fun getFileManager(m: TLMessage?, u: UserManager, c: TelegramClient): AbstractMediaFileManager? { fun getFileManager(m: TLMessage?, u: UserManager, c: TelegramClient): AbstractMediaFileManager? {
if (m == null) return null if (m == null) return null
val media = m!!.getMedia() ?: return null val media = m.getMedia() ?: return null
if (media is TLMessageMediaPhoto) { if (media is TLMessageMediaPhoto) {
return PhotoFileManager(m, u, c) return PhotoFileManager(m, u, c)

View File

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

View File

@ -55,14 +55,13 @@ class PhotoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient
init { init {
val p = (msg.getMedia() as TLMessageMediaPhoto).getPhoto() val p = (msg.getMedia() as TLMessageMediaPhoto).getPhoto()
if (p is TLPhoto) { if (p is TLPhoto) {
this.photo = p as TLPhoto this.photo = p
var biggest: TLPhotoSize? = null var biggest: TLPhotoSize? = null
for (s in photo!!.getSizes()) for (s in photo.getSizes())
if (s is TLPhotoSize) { if (s is TLPhotoSize) {
val size = s as TLPhotoSize if (biggest == null || s.getW() > biggest.getW() && s.getH() > biggest.getH()) {
if (biggest == null || size.getW() > biggest!!.getW() && size.getH() > biggest!!.getH()) { biggest = s
biggest = size
} }
} }
if (biggest == null) { if (biggest == null) {
@ -81,6 +80,6 @@ class PhotoFileManager(msg: TLMessage, user: UserManager, client: TelegramClient
override fun download() { override fun download() {
if (isEmpty) return if (isEmpty) return
val loc = photo_size.getLocation() as TLFileLocation 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 var sticker: TLDocumentAttributeSticker? = null
for (attr in doc!!.getAttributes()) { for (attr in doc!!.getAttributes()) {
if (attr is TLDocumentAttributeSticker) { if (attr is TLDocumentAttributeSticker) {
sticker = attr as TLDocumentAttributeSticker sticker = attr
} }
} }
val file = StringBuilder() val file = StringBuilder()
if (sticker!!.getStickerset() is TLInputStickerSetShortName) { val set = sticker!!.getStickerset()
file.append((sticker!!.getStickerset() as TLInputStickerSetShortName).getShortName()) if (set is TLInputStickerSetShortName) {
} else if (sticker!!.getStickerset() is TLInputStickerSetID) { file.append(set.getShortName())
file.append((sticker!!.getStickerset() as TLInputStickerSetID).getId()) } else if (set is TLInputStickerSetID) {
file.append(set.getId())
} }
file.append("_") file.append("_")
file.append(sticker!!.getAlt().hashCode()) file.append(sticker.getAlt().hashCode())
return file.toString() return file.toString()
} }