SettingsDialogFragment in progress; use values from settings instead of constants

This commit is contained in:
Alex Sytnyk 2018-08-10 13:16:46 +03:00
parent 30631e5719
commit 6f42612123
9 changed files with 98 additions and 74 deletions

View file

@ -18,7 +18,7 @@ import net.osmand.telegram.utils.UiUtils
class TelegramApplication : Application(), OsmandHelperListener {
val telegramHelper = TelegramHelper.instance
lateinit var telegramHelper: TelegramHelper private set
lateinit var settings: TelegramSettings private set
lateinit var uiUtils: UiUtils private set
lateinit var shareLocationHelper: ShareLocationHelper private set
@ -36,9 +36,10 @@ class TelegramApplication : Application(), OsmandHelperListener {
override fun onCreate() {
super.onCreate()
telegramHelper.appDir = filesDir.absolutePath
settings = TelegramSettings(this)
telegramHelper = TelegramHelper.getInstance(settings.locHistoryTime)
telegramHelper.appDir = filesDir.absolutePath
uiUtils = UiUtils(this)
osmandAidlHelper = OsmandAidlHelper(this)
osmandAidlHelper.listener = object : OsmandAidlHelper.OsmandHelperListener {
@ -127,7 +128,7 @@ class TelegramApplication : Application(), OsmandHelperListener {
serviceIntent.putExtra(TelegramService.USAGE_INTENT, i)
serviceIntent.putExtra(TelegramService.USAGE_OFF_INTERVAL, interval)
serviceIntent.putExtra(TelegramService.SEND_LOCATION_INTERVAL, settings.sendMyLocationInterval)
serviceIntent.putExtra(TelegramService.SEND_LOCATION_INTERVAL, settings.sendMyLocInterval)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
@ -136,7 +137,7 @@ class TelegramApplication : Application(), OsmandHelperListener {
}
fun startMyLocationService() {
val interval = settings.sendMyLocationInterval
val interval = settings.sendMyLocInterval
startTelegramService(TelegramService.USED_BY_MY_LOCATION, TelegramService.normalizeOffInterval(interval))
}

View file

@ -59,8 +59,8 @@ class TelegramService : Service(), LocationListener, TelegramIncomingMessagesLis
ctx.stopService(serviceIntent)
} else if (isUsedByMyLocation(usedBy)) {
val app = app()
if (app.settings.sendMyLocationInterval >= OFF_INTERVAL_THRESHOLD && serviceOffInterval == 0L) {
serviceOffInterval = app.settings.sendMyLocationInterval
if (app.settings.sendMyLocInterval >= OFF_INTERVAL_THRESHOLD && serviceOffInterval == 0L) {
serviceOffInterval = app.settings.sendMyLocInterval
setupServiceErrorInterval()
setupAlarm()
}
@ -84,7 +84,7 @@ class TelegramService : Service(), LocationListener, TelegramIncomingMessagesLis
initLocationUpdates()
}
if (isUsedByUsersLocations(usedBy)) {
app.telegramHelper.startLiveMessagesUpdates()
app.telegramHelper.startLiveMessagesUpdates(app.settings.sendMyLocInterval)
}
val locationNotification = app.notificationHelper.locationNotification

View file

@ -5,6 +5,27 @@ import net.osmand.telegram.helpers.TelegramHelper
import net.osmand.telegram.utils.OsmandFormatter.MetricsConstants
import net.osmand.telegram.utils.OsmandFormatter.SpeedConstants
val SEND_MY_LOC_VALUES_SEC =
listOf(1L, 2L, 3L, 5L, 10L, 15L, 30L, 60L, 90L, 2 * 60L, 3 * 60L, 5 * 60L)
val STALE_LOC_VALUES_SEC =
listOf(1 * 60L, 2 * 60L, 5 * 60L, 10 * 60L, 15 * 60L, 30 * 60L, 60 * 60L)
val LOC_HISTORY_VALUES_SEC = listOf(
5 * 60L,
15 * 60L,
30 * 60L,
1 * 60 * 60L,
2 * 60 * 60L,
3 * 60 * 60L,
5 * 60 * 60L,
8 * 60 * 60L,
12 * 60 * 60L,
24 * 60 * 60L
)
private const val SEND_MY_LOC_DEFAULT_INDEX = 6
private const val STALE_LOC_DEFAULT_INDEX = 4
private const val LOC_HISTORY_DEFAULT_INDEX = 2
private const val SETTINGS_NAME = "osmand_telegram_settings"
private const val SHARE_LOCATION_CHATS_KEY = "share_location_chats"
@ -13,11 +34,9 @@ private const val SHOW_ON_MAP_CHATS_KEY = "show_on_map_chats"
private const val METRICS_CONSTANTS_KEY = "metrics_constants"
private const val SPEED_CONSTANTS_KEY = "speed_constants"
private const val SEND_MY_LOCATION_INTERVAL_KEY = "send_my_location_interval"
private const val SEND_MY_LOCATION_INTERVAL_DEFAULT = 5L * 1000 // 5 seconds
private const val USER_LOCATION_EXPIRE_TIME_KEY = "user_location_expire_time"
private const val USER_LOCATION_EXPIRE_TIME_DEFAULT = 15L * 60 * 1000 // 15 minutes
private const val SEND_MY_LOC_INTERVAL_KEY = "send_my_loc_interval"
private const val STALE_LOC_TIME_KEY = "stale_loc_time"
private const val LOC_HISTORY_TIME_KEY = "loc_history_time"
private const val DEFAULT_VISIBLE_TIME_SECONDS = 60 * 60L // 1 hour
@ -33,8 +52,9 @@ class TelegramSettings(private val app: TelegramApplication) {
var metricsConstants = MetricsConstants.KILOMETERS_AND_METERS
var speedConstants = SpeedConstants.KILOMETERS_PER_HOUR
var sendMyLocationInterval = SEND_MY_LOCATION_INTERVAL_DEFAULT
var userLocationExpireTime = USER_LOCATION_EXPIRE_TIME_DEFAULT
var sendMyLocInterval = SEND_MY_LOC_VALUES_SEC[SEND_MY_LOC_DEFAULT_INDEX]
var staleLocTime = STALE_LOC_VALUES_SEC[STALE_LOC_DEFAULT_INDEX]
var locHistoryTime = LOC_HISTORY_VALUES_SEC[LOC_HISTORY_DEFAULT_INDEX]
init {
updatePrefs()
@ -63,7 +83,11 @@ class TelegramSettings(private val app: TelegramApplication) {
}.toMutableMap()
}
fun shareLocationToChat(chatId: Long, share: Boolean, livePeriod: Long = DEFAULT_VISIBLE_TIME_SECONDS) {
fun shareLocationToChat(
chatId: Long,
share: Boolean,
livePeriod: Long = DEFAULT_VISIBLE_TIME_SECONDS
) {
val shareLocationChats = shareLocationChats.toMutableList()
if (share) {
val lp: Long = when {
@ -124,7 +148,9 @@ class TelegramSettings(private val app: TelegramApplication) {
edit.putString(METRICS_CONSTANTS_KEY, metricsConstants.name)
edit.putString(SPEED_CONSTANTS_KEY, speedConstants.name)
edit.putLong(SEND_MY_LOCATION_INTERVAL_KEY, sendMyLocationInterval)
edit.putLong(SEND_MY_LOC_INTERVAL_KEY, sendMyLocInterval)
edit.putLong(STALE_LOC_TIME_KEY, staleLocTime)
edit.putLong(LOC_HISTORY_TIME_KEY, locHistoryTime)
edit.apply()
}
@ -153,10 +179,12 @@ class TelegramSettings(private val app: TelegramApplication) {
prefs.getString(SPEED_CONSTANTS_KEY, SpeedConstants.KILOMETERS_PER_HOUR.name)
)
sendMyLocationInterval =
prefs.getLong(SEND_MY_LOCATION_INTERVAL_KEY, SEND_MY_LOCATION_INTERVAL_DEFAULT)
userLocationExpireTime =
prefs.getLong(USER_LOCATION_EXPIRE_TIME_KEY, USER_LOCATION_EXPIRE_TIME_DEFAULT)
val sendMyLocDef = SEND_MY_LOC_VALUES_SEC[SEND_MY_LOC_DEFAULT_INDEX]
sendMyLocInterval = prefs.getLong(SEND_MY_LOC_INTERVAL_KEY, sendMyLocDef)
val staleLocDef = STALE_LOC_VALUES_SEC[STALE_LOC_DEFAULT_INDEX]
staleLocTime = prefs.getLong(STALE_LOC_TIME_KEY, staleLocDef)
val locHistoryDef = LOC_HISTORY_VALUES_SEC[LOC_HISTORY_DEFAULT_INDEX]
locHistoryTime = prefs.getLong(LOC_HISTORY_TIME_KEY, locHistoryDef)
}
private fun updatePrefs() {

View file

@ -54,7 +54,7 @@ class ShowLocationHelper(private val app: TelegramApplication) {
val messages = telegramHelper.getMessages()
for (message in messages) {
val date = Math.max(message.date, message.editDate) * 1000L
val expired = System.currentTimeMillis() - date > app.settings.userLocationExpireTime
val expired = System.currentTimeMillis() - date > app.settings.locHistoryTime
if (expired) {
removeMapPoint(message.chatId, message)
}

View file

@ -17,18 +17,14 @@ import java.util.concurrent.TimeUnit
import kotlin.collections.HashSet
class TelegramHelper private constructor() {
class TelegramHelper private constructor(var messageActiveTimeSec: Long) {
companion object {
const val OSMAND_BOT_USERNAME = "osmand_bot"
const val MESSAGE_ADD_ACTIVE_TIME_SEC = 30 * 60 // 30 min
private val log = PlatformUtil.getLog(TelegramHelper::class.java)
private const val CHATS_LIMIT = 100
private const val IGNORED_ERROR_CODE = 406
private const val UPDATE_LIVE_MESSAGES_INTERVAL_SEC = 30L
private const val MESSAGE_ACTIVE_TIME_SEC = 24 * 60 * 60 // 24 hours
private const val DEVICE_PREFIX = "Device: "
private const val LOCATION_PREFIX = "Location: "
@ -38,7 +34,7 @@ class TelegramHelper private constructor() {
private const val MINUTES_AGO_SUFFIX = " minutes ago"
private const val HOURS_AGO_SUFFIX = " hours ago"
private const val UTC_FORMAT_SUFFIX = " UTC"
private val UTC_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
@ -52,13 +48,12 @@ class TelegramHelper private constructor() {
private var helper: TelegramHelper? = null
val instance: TelegramHelper
get() {
if (helper == null) {
helper = TelegramHelper()
}
return helper!!
fun getInstance(messageActiveTimeSec: Long): TelegramHelper {
if (helper == null) {
helper = TelegramHelper(messageActiveTimeSec)
}
return helper!!
}
}
private val users = ConcurrentHashMap<Int, TdApi.User>()
@ -119,7 +114,7 @@ class TelegramHelper private constructor() {
fun removeFullInfoUpdatesListener(listener: FullInfoUpdatesListener) {
fullInfoUpdatesListeners.remove(listener)
}
fun addChatLiveMessagesListener(listener: ChatLiveMessagesListener) {
chatLiveMessagesListeners.add(listener)
}
@ -141,9 +136,9 @@ class TelegramHelper private constructor() {
fun getChat(id: Long) = chats[id]
fun getUser(id: Int) = users[id]
fun getCurrentUser() = currentUser
fun getUserMessage(user: TdApi.User) =
usersLocationMessages.values.firstOrNull { it.senderUserId == user.id }
@ -151,7 +146,7 @@ class TelegramHelper private constructor() {
usersLocationMessages.values.filter { it.chatId == chatId }
fun getMessages() = usersLocationMessages.values.toList()
fun getChatLiveMessages() = chatLiveMessages
fun getMessagesByChatIds(): Map<Long, List<TdApi.Message>> {
@ -189,7 +184,7 @@ class TelegramHelper private constructor() {
}
fun isPrivateChat(chat: TdApi.Chat): Boolean = chat.type is TdApi.ChatTypePrivate
private fun isChannel(chat: TdApi.Chat): Boolean {
return chat.type is TdApi.ChatTypeSupergroup && (chat.type as TdApi.ChatTypeSupergroup).isChannel
}
@ -234,7 +229,7 @@ class TelegramHelper private constructor() {
fun onBasicGroupFullInfoUpdated(groupId: Int, info: TdApi.BasicGroupFullInfo)
fun onSupergroupFullInfoUpdated(groupId: Int, info: TdApi.SupergroupFullInfo)
}
interface ChatLiveMessagesListener {
fun onChatLiveMessagesUpdated(messages: List<TdApi.Message>)
}
@ -326,19 +321,19 @@ class TelegramHelper private constructor() {
}
return deviceName
}
fun isOsmAndBot(userId: Int) = users[userId]?.username == OSMAND_BOT_USERNAME
fun isBot(userId: Int) = users[userId]?.type is TdApi.UserTypeBot
fun startLiveMessagesUpdates() {
fun startLiveMessagesUpdates(interval: Long) {
stopLiveMessagesUpdates()
val updateLiveMessagesExecutor = Executors.newSingleThreadScheduledExecutor()
this.updateLiveMessagesExecutor = updateLiveMessagesExecutor
updateLiveMessagesExecutor.scheduleWithFixedDelay({
incomingMessagesListeners.forEach { it.updateLocationMessages() }
}, UPDATE_LIVE_MESSAGES_INTERVAL_SEC, UPDATE_LIVE_MESSAGES_INTERVAL_SEC, TimeUnit.SECONDS)
}, interval, interval, TimeUnit.SECONDS)
}
fun stopLiveMessagesUpdates() {
@ -474,7 +469,7 @@ class TelegramHelper private constructor() {
}
}
}
private fun requestMessage(chatId: Long, messageId: Long, onComplete: (TdApi.Message) -> Unit) {
client?.send(TdApi.GetMessage(chatId, messageId)) { obj ->
when (obj.constructor) {
@ -734,7 +729,7 @@ class TelegramHelper private constructor() {
return false
}
val lastEdited = Math.max(date, editDate)
if (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) - lastEdited > MESSAGE_ACTIVE_TIME_SEC) {
if (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) - lastEdited > messageActiveTimeSec) {
return false
}
val content = content
@ -759,7 +754,7 @@ class TelegramHelper private constructor() {
}
}
}
private fun parseOsmAndBotLocationContent(oldContent:MessageOsmAndBotLocation, content: TdApi.MessageContent): MessageOsmAndBotLocation {
val messageLocation = content as TdApi.MessageLocation
return MessageOsmAndBotLocation().apply {
@ -769,7 +764,7 @@ class TelegramHelper private constructor() {
lastUpdated = (System.currentTimeMillis() / 1000).toInt()
}
}
private fun parseOsmAndBotLocation(text: String): MessageOsmAndBotLocation {
val res = MessageOsmAndBotLocation()
for (s in text.lines()) {
@ -785,7 +780,7 @@ class TelegramHelper private constructor() {
val timeSecs = parseTime(updatedS.removePrefix("(").removeSuffix(")"))
res.lat = latS.dropLast(1).toDouble()
res.lon = lonS.toDouble()
if (timeSecs < MESSAGE_ACTIVE_TIME_SEC) {
if (timeSecs < messageActiveTimeSec) {
res.lastUpdated = (System.currentTimeMillis() / 1000 - timeSecs).toInt()
} else {
res.lastUpdated = timeSecs
@ -803,7 +798,7 @@ class TelegramHelper private constructor() {
try {
when {
timeS.endsWith(FEW_SECONDS_AGO) -> return 5
timeS.endsWith(SECONDS_AGO_SUFFIX) -> {
val locStr = timeS.removeSuffix(SECONDS_AGO_SUFFIX)
return locStr.toInt()
@ -832,7 +827,7 @@ class TelegramHelper private constructor() {
}
return 0
}
class MessageOsmAndBotLocation : TdApi.MessageContent() {
var name: String = ""

View file

@ -32,7 +32,6 @@ import org.drinkless.td.libcore.telegram.TdApi
private const val CHAT_VIEW_TYPE = 0
private const val LOCATION_ITEM_VIEW_TYPE = 1
private const val LOCATION_TIMEOUT_TO_BE_STALE = 60 * 15 // 15 minutes
class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessagesListener,
FullInfoUpdatesListener, TelegramLocationListener, TelegramCompassListener {
@ -301,7 +300,7 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
}
if (location != null && item.latLon != null) {
holder.locationViewContainer?.visibility = View.VISIBLE
locationViewCache.outdatedLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > LOCATION_TIMEOUT_TO_BE_STALE
locationViewCache.outdatedLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > settings.staleLocTime
app.uiUtils.updateLocationView(
holder.directionIcon,
holder.distanceText,

View file

@ -28,6 +28,8 @@ private const val SELECTED_CHATS_KEY = "selected_chats"
private const val SHARE_LOCATION_CHAT = 1
private const val DEFAULT_CHAT = 0
private const val MESSAGE_ADD_ACTIVE_TIME_SEC = 30 * 60L // 30 min
class MyLocationTabFragment : Fragment(), TelegramListener, ChatLiveMessagesListener {
private var textMarginSmall: Int = 0
@ -497,7 +499,7 @@ class MyLocationTabFragment : Fragment(), TelegramListener, ChatLiveMessagesList
}
}
val duration = settings.getChatLivePeriod(chat.id)?.toInt()
val duration = settings.getChatLivePeriod(chat.id)
if (duration != null && duration > 0) {
holder.descriptionDuration?.text = OsmandFormatter.getFormattedDuration(context!!, duration)
holder.description?.apply {
@ -513,13 +515,13 @@ class MyLocationTabFragment : Fragment(), TelegramListener, ChatLiveMessagesList
holder.textInArea?.apply {
visibility = View.VISIBLE
text = "${getText(R.string.plus)} ${OsmandFormatter.getFormattedDuration(context!!,
TelegramHelper.MESSAGE_ADD_ACTIVE_TIME_SEC)}"
MESSAGE_ADD_ACTIVE_TIME_SEC)}"
setOnClickListener {
var newLivePeriod = app.settings.getChatLivePeriod(chat.id)
if (newLivePeriod != null) {
newLivePeriod += TelegramHelper.MESSAGE_ADD_ACTIVE_TIME_SEC
newLivePeriod += MESSAGE_ADD_ACTIVE_TIME_SEC
} else {
newLivePeriod = TelegramHelper.MESSAGE_ADD_ACTIVE_TIME_SEC.toLong()
newLivePeriod = MESSAGE_ADD_ACTIVE_TIME_SEC
}
app.settings.shareLocationToChat(chat.id, true, newLivePeriod)
notifyItemChanged(position)
@ -538,7 +540,7 @@ class MyLocationTabFragment : Fragment(), TelegramListener, ChatLiveMessagesList
holder.stopSharingSecondPart?.apply {
visibility = View.VISIBLE
text = "(${getString(R.string.in_time,
OsmandFormatter.getFormattedDuration(context!!, expiresIn, true))})"
OsmandFormatter.getFormattedDuration(context!!, expiresIn.toLong(), true))})"
}
if (expiresIn == 0) {
removeItem(chat)

View file

@ -12,8 +12,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import net.osmand.telegram.R
import net.osmand.telegram.TelegramApplication
import net.osmand.telegram.*
import net.osmand.telegram.helpers.OsmandAidlHelper
import net.osmand.telegram.helpers.TelegramHelper
import net.osmand.telegram.helpers.TelegramUiHelper
@ -161,19 +160,18 @@ class SettingsDialogFragment : DialogFragment() {
}
}
// FIXME
private inner class SendMyLocPref : DurationPref(
R.drawable.ic_action_share_location,
R.string.send_my_location,
R.string.send_my_location_desc,
listOf(30 * 60, 60 * 60, 90 * 60)
SEND_MY_LOC_VALUES_SEC
) {
override fun getCurrentValue() = OsmandFormatter.getFormattedDuration(app, values[0])
override fun getCurrentValue() =
OsmandFormatter.getFormattedDuration(app, settings.sendMyLocInterval)
override fun setCurrentValue(index: Int) {
val value = OsmandFormatter.getFormattedDuration(app, values[index])
Toast.makeText(context, value, Toast.LENGTH_SHORT).show()
settings.sendMyLocInterval = values[index]
}
}
@ -182,30 +180,31 @@ class SettingsDialogFragment : DialogFragment() {
R.drawable.ic_action_share_location,
R.string.stale_location,
R.string.stale_location_desc,
listOf(30 * 60, 60 * 60, 90 * 60)
STALE_LOC_VALUES_SEC
) {
override fun getCurrentValue() = OsmandFormatter.getFormattedDuration(app, values[0])
override fun getCurrentValue() =
OsmandFormatter.getFormattedDuration(app, settings.staleLocTime)
override fun setCurrentValue(index: Int) {
val value = OsmandFormatter.getFormattedDuration(app, values[index])
Toast.makeText(context, value, Toast.LENGTH_SHORT).show()
settings.staleLocTime = values[index]
}
}
// FIXME
private inner class LocHistoryPref : DurationPref(
R.drawable.ic_action_time_span,
R.string.location_history,
R.string.location_history_desc,
listOf(30 * 60, 60 * 60, 90 * 60)
LOC_HISTORY_VALUES_SEC
) {
override fun getCurrentValue() = OsmandFormatter.getFormattedDuration(app, values[0])
override fun getCurrentValue() =
OsmandFormatter.getFormattedDuration(app, settings.locHistoryTime)
override fun setCurrentValue(index: Int) {
val value = OsmandFormatter.getFormattedDuration(app, values[index])
Toast.makeText(context, value, Toast.LENGTH_SHORT).show()
val value = values[index]
settings.locHistoryTime = value
telegramHelper.messageActiveTimeSec = value
}
}
@ -213,7 +212,7 @@ class SettingsDialogFragment : DialogFragment() {
@DrawableRes val iconId: Int,
@StringRes val titleId: Int,
@StringRes val descriptionId: Int,
val values: List<Int>
val values: List<Long>
) {
abstract fun getCurrentValue(): String

View file

@ -33,7 +33,7 @@ object OsmandFormatter {
fixed2.minimumIntegerDigits = 1
}
fun getFormattedDuration(ctx: Context, seconds: Int, short: Boolean = false): String {
fun getFormattedDuration(ctx: Context, seconds: Long, short: Boolean = false): String {
val hours = seconds / (60 * 60)
val minutes = seconds / 60 % 60
val secs = seconds - minutes * 60