Merge pull request #5917 from osmandapp/TelegramStaleLocation

Telegram icons stale location
This commit is contained in:
Alexander Sytnyk 2018-08-28 15:40:32 +03:00 committed by GitHub
commit a7ed7cde21
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 197 additions and 25 deletions

View file

@ -273,7 +273,7 @@ class TelegramService : Service(), LocationListener, TelegramIncomingMessagesLis
override fun doInBackground(vararg messages: TdApi.Message): Void? {
for (message in messages) {
app.showLocationHelper.addLocationToMap(message)
app.showLocationHelper.addOrUpdateLocationOnMap(message)
}
return null
}

View file

@ -11,6 +11,8 @@ import net.osmand.telegram.helpers.TelegramUiHelper.ListItem
import net.osmand.telegram.utils.AndroidUtils
import org.drinkless.td.libcore.telegram.TdApi
import java.io.File
import android.net.Uri
import net.osmand.telegram.R
class ShowLocationHelper(private val app: TelegramApplication) {
@ -30,7 +32,7 @@ class ShowLocationHelper(private val app: TelegramApplication) {
}
}
fun showLocationOnMap(item: ListItem) {
fun showLocationOnMap(item: ListItem, stale: Boolean = false) {
if (item.latLon == null) {
return
}
@ -41,10 +43,10 @@ class ShowLocationHelper(private val app: TelegramApplication) {
item.getVisibleName(),
item.getVisibleName(),
item.chatTitle,
Color.RED,
Color.WHITE,
ALatLon(item.latLon!!.latitude, item.latLon!!.longitude),
null,
generatePhotoParams(item.photoPath)
generatePhotoParams(if (stale) item.grayscalePhotoPath else item.photoPath, stale)
)
}
}
@ -53,16 +55,18 @@ class ShowLocationHelper(private val app: TelegramApplication) {
execOsmandApi {
val messages = telegramHelper.getMessages()
for (message in messages) {
val date = Math.max(message.date, message.editDate) * 1000L
val expired = System.currentTimeMillis() - date > app.settings.locHistoryTime * 1000L
if (expired) {
val date = telegramHelper.getLastUpdatedTime(message)
val messageShowingTime = System.currentTimeMillis() / 1000 - date
if (messageShowingTime > app.settings.locHistoryTime) {
removeMapPoint(message.chatId, message)
} else if (app.settings.isShowingChatOnMap(message.chatId)) {
addOrUpdateLocationOnMap(message, true)
}
}
}
}
fun addLocationToMap(message: TdApi.Message) {
fun addOrUpdateLocationOnMap(message: TdApi.Message, update: Boolean = false) {
execOsmandApi {
val chatId = message.chatId
val chatTitle = telegramHelper.getChat(message.chatId)?.title
@ -70,6 +74,8 @@ class ShowLocationHelper(private val app: TelegramApplication) {
if (chatTitle != null && content is TdApi.MessageLocation) {
var userName = ""
var photoPath: String? = null
val date = telegramHelper.getLastUpdatedTime(message)
val stale = System.currentTimeMillis() / 1000 - date > app.settings.staleLocTime
val user = telegramHelper.getUser(message.senderUserId)
if (user != null) {
userName = "${user.firstName} ${user.lastName}".trim()
@ -79,20 +85,34 @@ class ShowLocationHelper(private val app: TelegramApplication) {
if (userName.isEmpty()) {
userName = user.phoneNumber
}
photoPath = telegramHelper.getUserPhotoPath(user)
photoPath = if (stale) {
telegramHelper.getUserGreyPhotoPath(user)
} else {
telegramHelper.getUserPhotoPath(user)
}
}
if (userName.isEmpty()) {
userName = message.senderUserId.toString()
}
setupMapLayer()
val params = generatePhotoParams(photoPath)
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName,
chatTitle, Color.RED, ALatLon(content.location.latitude, content.location.longitude), null, params)
val params = generatePhotoParams(photoPath, stale)
if (update) {
osmandAidlHelper.updateMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName,
chatTitle, Color.WHITE, ALatLon(content.location.latitude, content.location.longitude), null, params)
} else {
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName,
chatTitle, Color.WHITE, ALatLon(content.location.latitude, content.location.longitude), null, params)
}
} else if (chatTitle != null && content is MessageOsmAndBotLocation && content.isValid()) {
val name = content.name
setupMapLayer()
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name,
chatTitle, Color.RED, ALatLon(content.lat, content.lon), null, null)
if (update) {
osmandAidlHelper.updateMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name,
chatTitle, Color.WHITE, ALatLon(content.lat, content.lon), null, null)
} else {
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name,
chatTitle, Color.WHITE, ALatLon(content.lat, content.lon), null, null)
}
}
}
}
@ -101,7 +121,7 @@ class ShowLocationHelper(private val app: TelegramApplication) {
execOsmandApi {
val messages = telegramHelper.getChatMessages(chatId)
for (message in messages) {
addLocationToMap(message)
addOrUpdateLocationOnMap(message)
}
}
}
@ -135,11 +155,21 @@ class ShowLocationHelper(private val app: TelegramApplication) {
}
}
private fun generatePhotoParams(photoPath: String?): Map<String, String>? {
if (TextUtils.isEmpty(photoPath)) {
return null
private fun generatePhotoParams(photoPath: String?, stale: Boolean = false): Map<String, String>? {
val photoUri = if (TextUtils.isEmpty(photoPath)) {
val resId = if (stale) {
R.drawable.img_user_picture
} else {
R.drawable.img_user_picture_active
}
AndroidUtils.resourceToUri(app, resId)
} else {
AndroidUtils.getUriForFile(app, File(photoPath))
}
val photoUri = AndroidUtils.getUriForFile(app, File(photoPath))
return generatePhotoParamsFromUri(photoUri)
}
private fun generatePhotoParamsFromUri(photoUri: Uri): Map<String, String>? {
app.grantUriPermission(
app.settings.appToConnectPackage,
photoUri,

View file

@ -3,6 +3,7 @@ package net.osmand.telegram.helpers
import android.text.TextUtils
import net.osmand.PlatformUtil
import net.osmand.telegram.helpers.TelegramHelper.TelegramAuthenticationParameterType.*
import net.osmand.telegram.utils.*
import org.drinkless.td.libcore.telegram.Client
import org.drinkless.td.libcore.telegram.Client.ResultHandler
import org.drinkless.td.libcore.telegram.TdApi
@ -320,6 +321,14 @@ class TelegramHelper private constructor() {
}
}
fun getUserGreyPhotoPath(user: TdApi.User): String? {
return if (hasGrayscaleUserPhoto(user.id)) {
"$appDir/$GRAYSCALE_PHOTOS_DIR${user.id}$GRAYSCALE_PHOTOS_EXT"
} else {
null
}
}
fun getOsmAndBotDeviceName(message: TdApi.Message): String {
var deviceName = ""
if (message.replyMarkup is TdApi.ReplyMarkupInlineKeyboard) {
@ -358,6 +367,10 @@ class TelegramHelper private constructor() {
updateLiveMessagesExecutor?.awaitTermination(1, TimeUnit.MINUTES)
}
fun hasGrayscaleUserPhoto(userId: Int): Boolean {
return File("$appDir/$GRAYSCALE_PHOTOS_DIR$userId$GRAYSCALE_PHOTOS_EXT").exists()
}
private fun hasLocalUserPhoto(user: TdApi.User): Boolean {
val localPhoto = user.profilePhoto?.small?.local
return if (localPhoto != null) {

View file

@ -59,6 +59,7 @@ object TelegramUiHelper {
res.chatWithBot = chatWithBot
if (!chatWithBot) {
res.userId = userId
val user = helper.getUser(userId)
val message = messages.firstOrNull { it.viaBotUserId == 0 }
if (message != null) {
res.lastUpdated = helper.getLastUpdatedTime(message)
@ -67,6 +68,9 @@ object TelegramUiHelper {
res.latLon = LatLon(content.location.latitude, content.location.longitude)
}
}
if (user != null) {
res.grayscalePhotoPath = helper.getUserGreyPhotoPath(user)
}
}
} else if (type is TdApi.ChatTypeBasicGroup) {
res.placeholderId = R.drawable.img_group_picture
@ -137,6 +141,7 @@ object TelegramUiHelper {
name = TelegramUiHelper.getUserName(user)
latLon = LatLon(content.location.latitude, content.location.longitude)
photoPath = helper.getUserPhotoPath(user)
grayscalePhotoPath = helper.getUserGreyPhotoPath(user)
placeholderId = R.drawable.img_user_picture
userId = message.senderUserId
lastUpdated = helper.getLastUpdatedTime(message)
@ -153,6 +158,8 @@ object TelegramUiHelper {
internal set
var photoPath: String? = null
internal set
var grayscalePhotoPath: String? = null
internal set
var placeholderId: Int = 0
internal set
var userId: Int = 0

View file

@ -311,7 +311,13 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
val canBeOpenedOnMap = item.canBeOpenedOnMap()
val openOnMapView = holder.getOpenOnMapClickView()
TelegramUiHelper.setupPhoto(app, holder.icon, item.photoPath, item.placeholderId, false)
val staleLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > settings.staleLocTime
if (staleLocation) {
TelegramUiHelper.setupPhoto(app, holder.icon, item.grayscalePhotoPath, item.placeholderId, false)
} else {
TelegramUiHelper.setupPhoto(app, holder.icon, item.photoPath, R.drawable.img_user_picture_active, false)
}
holder.title?.text = item.getVisibleName()
openOnMapView?.isEnabled = canBeOpenedOnMap
if (canBeOpenedOnMap) {
@ -319,7 +325,7 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
if (!isOsmAndInstalled()) {
showOsmAndMissingDialog()
} else {
app.showLocationHelper.showLocationOnMap(item)
app.showLocationHelper.showLocationOnMap(item, staleLocation)
}
}
} else {
@ -327,7 +333,7 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
}
if (location != null && item.latLon != null) {
holder.locationViewContainer?.visibility = if (item.lastUpdated > 0) View.VISIBLE else View.GONE
locationViewCache.outdatedLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > settings.staleLocTime
locationViewCache.outdatedLocation = staleLocation
app.uiUtils.updateLocationView(
holder.directionIcon,
holder.distanceText,

View file

@ -25,6 +25,8 @@ import net.osmand.telegram.ui.LoginDialogFragment.LoginDialogType
import net.osmand.telegram.ui.MyLocationTabFragment.ActionButtonsListener
import net.osmand.telegram.ui.views.LockableViewPager
import net.osmand.telegram.utils.AndroidUtils
import net.osmand.telegram.utils.GRAYSCALE_PHOTOS_DIR
import net.osmand.telegram.utils.GRAYSCALE_PHOTOS_EXT
import org.drinkless.td.libcore.telegram.TdApi
import java.lang.ref.WeakReference
@ -33,7 +35,7 @@ private const val PERMISSION_REQUEST_LOCATION = 1
private const val MY_LOCATION_TAB_POS = 0
private const val LIVE_NOW_TAB_POS = 1
class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListener {
class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListener, TelegramIncomingMessagesListener {
private val log = PlatformUtil.getLog(TelegramHelper::class.java)
@ -150,6 +152,7 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
if (telegramHelper.listener != this) {
telegramHelper.listener = this
}
telegramHelper.addIncomingMessagesListener(this)
app.locationProvider.checkIfLastKnownLocationIsValid()
@ -164,6 +167,7 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
override fun onPause() {
super.onPause()
telegramHelper.listener = null
telegramHelper.removeIncomingMessagesListener(this)
app.locationProvider.pauseAllUpdates()
@ -219,21 +223,29 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
}
override fun onTelegramChatsChanged() {
telegramHelper.getMessagesByChatIds(settings.locHistoryTime).forEach {
addGrayPhoto(it.key)
}
runOnUi {
listeners.forEach { it.get()?.onTelegramChatsChanged() }
}
}
override fun onTelegramChatChanged(chat: TdApi.Chat) {
addGrayPhoto(chat.id)
runOnUi {
listeners.forEach { it.get()?.onTelegramChatChanged(chat) }
}
}
override fun onTelegramUserChanged(user: TdApi.User) {
val photoPath = telegramHelper.getUserPhotoPath(user)
if (photoPath != null) {
addGrayPhoto(user.id, photoPath)
}
val message = telegramHelper.getUserMessage(user)
if (message != null) {
app.showLocationHelper.addLocationToMap(message)
app.showLocationHelper.addOrUpdateLocationOnMap(message)
}
runOnUi {
listeners.forEach { it.get()?.onTelegramUserChanged(user) }
@ -255,6 +267,14 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
}
}
override fun onReceiveChatLocationMessages(chatId: Long, vararg messages: TdApi.Message) {
addGrayPhoto(chatId)
}
override fun onDeleteChatLocationMessages(chatId: Long, messages: List<TdApi.Message>) {}
override fun updateLocationMessages() {}
override fun switchButtonsVisibility(visible: Boolean) {
val buttonsVisibility = if (visible) View.VISIBLE else View.GONE
if (buttonsBar.visibility != buttonsVisibility) {
@ -331,6 +351,23 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
}
}
private fun addGrayPhoto(chatId: Long) {
val chat = app.telegramHelper.getChat(chatId)
val chatIconPath = chat?.photo?.small?.local?.path
if (chat != null && chatIconPath != null) {
addGrayPhoto(app.telegramHelper.getUserIdFromChatType(chat.type), chatIconPath)
}
}
private fun addGrayPhoto(userId: Int, originalPhotoPath: String) {
if (userId != 0 && !app.telegramHelper.hasGrayscaleUserPhoto(userId)) {
app.uiUtils.convertAndSaveGrayPhoto(
originalPhotoPath,
"${app.filesDir.absolutePath}/$GRAYSCALE_PHOTOS_DIR$userId$GRAYSCALE_PHOTOS_EXT"
)
}
}
private fun isOsmAndInstalled() = AndroidUtils.isAppInstalled(this, settings.appToConnectPackage)
private fun runOnUi(action: (() -> Unit)) {

View file

@ -2,6 +2,7 @@ package net.osmand.telegram.utils
import android.Manifest
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
@ -131,6 +132,14 @@ object AndroidUtils {
}
}
fun resourceToUri(ctx: Context, resID: Int): Uri {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://${ctx.resources.getResourcePackageName(resID)}" +
"/${ctx.resources.getResourceTypeName(resID)}" +
"/${ctx.resources.getResourceEntryName(resID)}"
)
}
fun isAppInstalled(ctx: Context, appPackage: String): Boolean {
try {
ctx.packageManager.getPackageInfo(appPackage, 0)

View file

@ -6,6 +6,7 @@ import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.AsyncTask
import android.support.annotation.ColorInt
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
@ -16,14 +17,21 @@ import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import net.osmand.Location
import net.osmand.PlatformUtil
import net.osmand.data.LatLon
import net.osmand.telegram.R
import net.osmand.telegram.TelegramApplication
import net.osmand.telegram.ui.views.DirectionDrawable
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
class UiUtils(private val app: TelegramApplication) {
const val GRAYSCALE_PHOTOS_DIR = "grayscale_photos/"
const val GRAYSCALE_PHOTOS_EXT = ".jpeg"
class UiUtils(private val app: TelegramApplication) {
private val drawableCache = LinkedHashMap<Long, Drawable>()
private val circleBitmapCache = LinkedHashMap<String, Bitmap>()
@ -107,6 +115,16 @@ class UiUtils(private val app: TelegramApplication) {
return getDrawable(id, if (light) R.color.icon_light else 0)
}
fun convertAndSaveGrayPhoto(originalPhotoPath: String, greyPhotoPath: String) {
if (File(originalPhotoPath).exists()) {
ConvertPhotoToGrayscale().executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
originalPhotoPath,
greyPhotoPath
)
}
}
private fun createCircleBitmap(source: Bitmap, recycleSource: Boolean = false): Bitmap {
val size = Math.min(source.width, source.height)
@ -208,4 +226,56 @@ class UiUtils(private val app: TelegramApplication) {
var screenOrientation: Int = 0
var outdatedLocation: Boolean = false
}
private class ConvertPhotoToGrayscale : AsyncTask<String, String, Void?>() {
private val log = PlatformUtil.getLog(ConvertPhotoToGrayscale::class.java)
override fun doInBackground(vararg params: String?): Void? {
val userOriginalPhotoPath = params[0]
val userGrayScalePhotoPath = params[1]
if (userOriginalPhotoPath != null && userGrayScalePhotoPath != null) {
convertToGrayscaleAndSave(userOriginalPhotoPath, userGrayScalePhotoPath)
}
return null
}
fun convertToGrayscaleAndSave(coloredImagePath: String, newFilePath: String) {
val currentImage = BitmapFactory.decodeFile(coloredImagePath)
val grayscaleImage = toGrayscale(currentImage)
saveBitmap(grayscaleImage, newFilePath)
}
private fun toGrayscale(bmpOriginal: Bitmap): Bitmap {
val bmpGrayscale = Bitmap.createBitmap(bmpOriginal.width, bmpOriginal.height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmpGrayscale)
val paint = Paint()
val cm = ColorMatrix()
cm.setSaturation(0f)
val f = ColorMatrixColorFilter(cm)
paint.colorFilter = f
c.drawBitmap(bmpOriginal, 0f, 0f, paint)
return bmpGrayscale
}
private fun saveBitmap(bitmap: Bitmap, newFilePath: String) {
var fout: FileOutputStream? = null
try {
val file = File(newFilePath)
if (file.parentFile != null) {
file.parentFile.mkdirs()
}
fout = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout)
} catch (e: Exception) {
log.error(e)
} finally {
try {
fout?.close()
} catch (e: IOException) {
log.error(e)
}
}
}
}
}