Skip to content

Instantly share code, notes, and snippets.

@VIkash2601
Created November 16, 2023 07:39
Show Gist options
  • Save VIkash2601/3e0cc6b97d977600661781a6f5755063 to your computer and use it in GitHub Desktop.
Save VIkash2601/3e0cc6b97d977600661781a6f5755063 to your computer and use it in GitHub Desktop.
ActHome Gist
package com.app.spinnr.act
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.*
import android.media.AudioAttributes
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO
import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.app.spinnr.App
import com.app.spinnr.BuildConfig
import com.app.spinnr.NService
import com.app.spinnr.R
import com.app.spinnr.act.ActHome.NotificationReceiver
import com.app.spinnr.databinding.ActHomeBinding
import com.app.spinnr.databinding.ItemSnackbarBinding
import com.app.spinnr.frag.*
import com.app.spinnr.frag.chat.ChatRepo
import com.app.spinnr.frag.chat.ChatRepo.unreadMessageCount
import com.app.spinnr.frag.chat.FragChat
import com.app.spinnr.frag.chat.FragIntros
import com.app.spinnr.frag.favorite.FragFavorite
import com.app.spinnr.frag.filter.FragFilter
import com.app.spinnr.frag.profile.FragProfileView
import com.app.spinnr.frag.squad.FragSquadChat
import com.app.spinnr.frag.squad.FragSquadInfo
import com.app.spinnr.frag.squad.SquadRepo
import com.app.spinnr.frag.tabs.*
import com.app.spinnr.frag.theme.FragChangeTheme
import com.app.spinnr.frag.video.FragDailyVideo
import com.app.spinnr.helper.Constant
import com.app.spinnr.listener.CompleteListener
import com.app.spinnr.listener.FragListener
import com.app.spinnr.model.*
import com.app.spinnr.model.ProfileModel.Companion.profileData
import com.app.spinnr.service.*
import com.app.spinnr.service.ANotification.createChannelApp
import com.app.spinnr.service.ApiClient.Companion.getClient
import com.app.spinnr.service.ApiClient.Companion.getClient2
import com.app.spinnr.service.ResponseListBean.Companion.saveUserData
import com.app.spinnr.util.*
import com.app.spinnr.util.Preference.Companion.GUID
import com.app.spinnr.util.Preference.Companion.USERNAME
import com.app.spinnr.util.Preference.Companion.preferenceInstance
import com.app.spinnr.util.Preference.Companion.tooltipShow
import com.app.spinnr.util.Preference.Companion.tooltipShown
import com.google.android.material.snackbar.Snackbar
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.InstallState
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.ActivityResult
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.play.core.ktx.isFlexibleUpdateAllowed
import com.google.firebase.Timestamp
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.getField
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.spotify.sdk.android.auth.AuthorizationClient
import com.spotify.sdk.android.auth.AuthorizationRequest
import com.spotify.sdk.android.auth.AuthorizationResponse
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.leolin.shortcutbadger.ShortcutBadger
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Float.max
import java.util.*
val url = ""
@SuppressLint("StaticFieldLeak")
class ActHome : AppCompatActivity(), View.OnClickListener, InstallStateUpdatedListener, NotificationCountUpdateListener {
private val TAG = ActHome::class.simpleName
lateinit var binding: ActHomeBinding
private lateinit var mContext: Context
var systemDarkMode = -1
var fragHome: FragHome? = null
lateinit var fragSearch: FragFilter
private var unreadNotificationCount = 0
override fun onNotificationCountUpdated(count: Int, isAdded: Boolean, isFrom: String) {
if (count == 0)
return
else if (isAdded)
unreadNotificationCount += count
else
unreadNotificationCount -= count
val manager = createChannel()
if (unreadNotificationCount > 0) {
// Check if a notification with the same ID exists and cancel it
manager.cancel(preferenceInstance.readString(USERNAME).hashCode())
val intent = Intent(mContext, ActHome::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
val pendingIntent = PendingIntent.getActivity(mContext, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val notification = NotificationCompat.Builder(mContext, "Spinnr-Chat")
.setSmallIcon(R.drawable.ic_stat_spinnr)
.setContentTitle("")
.setContentText("You have some unread notifications")
.setAutoCancel(true)
.setSound(null)
.setNumber(unreadNotificationCount)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent)
manager.notify(
preferenceInstance.readString(USERNAME).hashCode(),
notification.build()
)
ShortcutBadger.applyCount(mContext, unreadNotificationCount)
} else {
val mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val notifications = mNotificationManager.activeNotifications
for (notification in notifications) {
if (notification.id == preferenceInstance.readString(USERNAME).hashCode()) {
mNotificationManager.cancel(preferenceInstance.readString(USERNAME).hashCode())
}
}
}
}
fun interface NotificationReceiver {
fun onReceive(intent: Intent)
}
companion object {
var notificationReceiver: NotificationReceiver? = null
var popular = 0
var timeDx = 0L
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (netNotConnected()) showSnackBar(getString(R.string.no_internet))
}
}
private var loaded = false
private val REQUEST_CODE = 1337
private val artistList = ArrayList<ArtistListModel>()
private val artistDataList = ArrayList<ArtistData>()
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
Log.e(
"423u5",
"onConfigurationChanged: ${preferenceInstance.readString("appTheme", "systemDefault")}"
)
if (preferenceInstance.readString("appTheme", "systemDefault") == "systemDefault") {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
systemDarkMode = getSystemDarkModeStatus()
Log.e("423u5", "onConfigurationChanged: $systemDarkMode")
if (systemDarkMode == MODE_NIGHT_YES) {
binding.imgTabSquad.imageTintList = getColorStateList(R.color.white)
binding.imgTabReels.imageTintList = getColorStateList(R.color.white)
binding.imgTabChat.imageTintList = getColorStateList(R.color.white)
binding.imgTabProfile.imageTintList = getColorStateList(R.color.white)
binding.imgTabEvent.imageTintList = getColorStateList(R.color.white)
} else {
binding.imgTabSquad.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabReels.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabChat.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabProfile.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabEvent.imageTintList = getColorStateList(R.color.purpleDark)
}
recreate()
}
}
private fun getSystemDarkModeStatus(): Int {
return when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES -> MODE_NIGHT_YES
Configuration.UI_MODE_NIGHT_NO -> MODE_NIGHT_NO
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Firebase.auth.currentUser == null) {
showSnackBar("Session Expire.")
logout()
return
}
if (loaded) return
loaded = true
mContext = this
binding = ActHomeBinding.inflate(LayoutInflater.from(this))
checkTheme(TAG, delegate)
systemDarkMode = getSystemDarkModeStatus()
Log.e("423u5", "onConfigurationChanged: $systemDarkMode")
if (systemDarkMode == MODE_NIGHT_YES) {
binding.imgTabSquad.imageTintList = getColorStateList(R.color.white)
binding.imgTabReels.imageTintList = getColorStateList(R.color.white)
binding.imgTabChat.imageTintList = getColorStateList(R.color.white)
binding.imgTabProfile.imageTintList = getColorStateList(R.color.white)
binding.imgTabEvent.imageTintList = getColorStateList(R.color.white)
} else {
binding.imgTabSquad.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabReels.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabChat.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabProfile.imageTintList = getColorStateList(R.color.purpleDark)
binding.imgTabEvent.imageTintList = getColorStateList(R.color.purpleDark)
}
setContentView(binding.root)
if (savedInstanceState == null || fragHome == null) {
postDelayed({ NService.init() }, 1000)
navigateTo(FragHome().also {
fragHome = it
}, false)
}
appUpdateManager = AppUpdateManagerFactory.create(applicationContext)
// setup()
/*if (preferenceInstance.readString(Preference.SPOTIFY_TOKEN).isNotEmpty()){
callArtistListApi()
} else
updateSpotify("")*/
//ShortcutBadger.removeCount(this)
//preferenceInstance.writeInt("bbadge", 0)
//NotificationManagerCompat.from(this).cancelAll()
updateDeviceType()
checkNotificationPermission()
fragSearch = FragFilter(fragHome!!.fragListener)
preferenceInstance.writeBoolean("destroy", false)
onBackPressedCallback.isEnabled = true
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
eventCount()
getBadgeCounts()
getSelectedPushNotificationSettings()
checkOnlineStatus()
App.registerNetworkListener(object: NetworkCallback(){
override fun onAvailable(network: Network) {
super.onAvailable(network)
isOnline = true
updateOnlineStatus()
}
override fun onLost(network: Network) {
super.onLost(network)
isOnline = false
updateOnlineStatus()
}
})
var move = false
binding.spinny.setOnTouchListener { v, e ->
return@setOnTouchListener if (e.action == MotionEvent.ACTION_MOVE) {
move = true
v.x = max(e.rawX - v.width * .8f, 0f)
v.y = max(e.rawY - v.height * 1.2f, 0f)
if (v.x + v.width > binding.root.width)
v.x = binding.root.width - v.width.toFloat()
if (v.y + v.height > binding.root.height)
v.y = binding.root.height - v.height.toFloat()
true
} else if (e.action == MotionEvent.ACTION_UP && move) {
move = false
true
} else
false
}
binding.spinny.setOnClickListener {
FragChat.USERNAME = preferenceInstance.readString(USERNAME)
FragChat.GUID = preferenceInstance.readString(GUID)
navigateTo(FragChat().apply {
arguments = Bundle().apply {
putString("username", "spinny")
putString("guid", "")
}
}, true)
}
createChannelApp()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
isOnline = true
updateOnlineStatus()
} else {
isOnline = false
updateOnlineStatus()
}
}
fun getBadgeCounts(type: String = "") {
getClient2().getAppBadge(
preferenceInstance.readString(Preference.GUID),
preferenceInstance.readString(Preference.USERNAME),
type
)
.enqueue(object : Callback<ResponseBean<JsonElement>> {
override fun onResponse(
call: Call<ResponseBean<JsonElement>>,
response: Response<ResponseBean<JsonElement>>
) {
response.body()?.data?.let { element ->
val request = element.asJsonObject.get("friendRequests").asInt
fragHome?.binding?.txtHomeCount?.visibility =
if (request == 0 || netNotConnected()) View.GONE else View.VISIBLE
binding.txtHomeCount.visibility =
if (request == 0 || netNotConnected()) View.GONE else View.VISIBLE
if (request > 0) {
if (fragHome?.binding?.txtHomeCount?.text.isNullOrEmpty())
onNotificationCountUpdated(request, true, "friendRequests")
else {
if (fragHome?.binding?.txtHomeCount?.text.toString().toInt() != request) {
val newCount =
request - fragHome?.binding?.txtHomeCount?.text.toString().toInt()
onNotificationCountUpdated(newCount, true, "friendRequests")
}
}
} else {
if (!fragHome?.binding?.txtHomeCount?.text.isNullOrEmpty()) {
onNotificationCountUpdated(fragHome?.binding?.txtHomeCount?.text.toString().toInt(), false, "friendRequests")
}
}
fragHome?.binding?.txtHomeCount?.text = request.toString()
binding.txtHomeCount.text = request.toString()
val intro =
element.asJsonObject.get("receivedIntros").asInt + unreadMessageCount
binding.txtChatCount.visibility =
if (intro == 0 || netNotConnected()) View.GONE else View.VISIBLE
if (intro > 0) {
if (binding.txtChatCount.text.isNullOrEmpty())
onNotificationCountUpdated(intro, true, "intro")
else {
if (binding.txtChatCount.text.toString().toInt() != intro) {
val newCount =
intro - binding.txtChatCount.text.toString().toInt()
onNotificationCountUpdated(newCount, true, "intro")
}
}
} else {
if (!binding.txtChatCount.text.isNullOrEmpty()) {
onNotificationCountUpdated(binding.txtChatCount.text.toString().toInt(), false, "intro")
}
}
binding.txtChatCount.text = intro.toString()
val count = element.asJsonObject.get("unreadMessages").asInt
binding.txtProfileCount.visibility =
if (count == 0 || netNotConnected()) View.GONE else View.VISIBLE
if (count > 0) {
if (binding.txtProfileCount.text.isNullOrEmpty())
onNotificationCountUpdated(count, true, "count")
else {
if (binding.txtProfileCount.text.toString().toInt() != count) {
val newCount =
count - binding.txtProfileCount.text.toString().toInt()
onNotificationCountUpdated(newCount, true, "count")
}
}
} else {
if (!binding.txtProfileCount.text.isNullOrEmpty()) {
onNotificationCountUpdated(binding.txtProfileCount.text.toString().toInt(), false, "count")
}
}
binding.txtProfileCount.text = count.toString()
FragProfile.binding?.notificationCount?.visibility =
if (count == 0 || netNotConnected()) View.GONE else View.VISIBLE
FragProfile.binding?.notificationCount?.text = count.toString()
}
postDelayed({ getBadgeCounts() }, 750)
}
override fun onFailure(call: Call<ResponseBean<JsonElement>>, t: Throwable) {
postDelayed({ getBadgeCounts() }, 750)
}
})
}
fun backPress() {
try {
onBackPressedDispatcher.onBackPressed()
} catch (e: java.lang.Exception) {
}
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount <= 0) finishAffinity()
else backPress()
}
var stop = false
private fun startGettingUpdate() {
if (stop) return
getClient2().getProfile(preferenceInstance.readString(Preference.USERNAME))
.enqueue(object : Callback<ResponseListBean<ProfileStatusModel>> {
override fun onResponse(
call: Call<ResponseListBean<ProfileStatusModel>>,
response: Response<ResponseListBean<ProfileStatusModel>>
) {
if (response.body()?.data?.first()?.statusid == "3") {
showMessage("Your account has been suspended for violating our terms and conditions.") { logout() }
} else if (response.body()?.data?.first()?.statusid == "4") {
showMessage("Your account is disabled.") { logout() }
} else if (response.body()?.data?.first() == null) {
showMessage("Your account has been deleted for violating our terms and conditions.") { logout() }
} else {
preferenceInstance.writeBoolean("performSwap", response.body()?.data?.first()?.canPerformSwap == 1)
postDelayed({ startGettingUpdate() }, 1500)
}
}
override fun onFailure(call: Call<ResponseListBean<ProfileStatusModel>>, t: Throwable) {
postDelayed({ startGettingUpdate() }, 1500)
}
})
}
private fun eventCount() {
Firebase.firestore.collection("spinnr-events-chat")
.where(Filter.arrayContains("membersList", preferenceInstance.readString(USERNAME)))
.addSnapshotListener { value, _ ->
try {
var count = 0
value?.toObjects(SquadImpl::class.java)?.forEach {
count += it.unreadCount()
}
binding.txtEventCount.visibility = if (count == 0) View.GONE else View.VISIBLE
Log.e(TAG, "eventCount: count is $count")
if (count > 0) {
if (binding.txtEventCount.text.isNullOrEmpty())
onNotificationCountUpdated(count, true, "event")
else {
if (binding.txtEventCount.text.toString().toInt() < count) {
val newCount =
count - binding.txtEventCount.text.toString().toInt()
onNotificationCountUpdated(newCount, true, "event")
}
}
} else {
if (!binding.txtEventCount.text.isNullOrEmpty()) {
onNotificationCountUpdated(binding.txtEventCount.text.toString().toInt(), false, "event")
}
}
binding.txtEventCount.text = count.toString()
} catch (ignored: Exception) {
}
}
}
data class OnlineStatus(val status: Boolean = false, val updatedAt: Timestamp = Timestamp.now())
private fun checkOnlineStatus() {
Firebase.firestore.collection("users")
.addSnapshotListener { value, _ ->
value?.forEachIndexed { index, queryDocumentSnapshot ->
val onlineStatus = queryDocumentSnapshot.getField<OnlineStatus>("onlineStatus")
Log.e("423u5-online-home", "$index#${queryDocumentSnapshot.id} - ${(onlineStatus?.status == true && onlineStatus.updatedAt.seconds > currentSeconds() / 1000)} - ${Date((onlineStatus?.updatedAt?.seconds?:0L) * 1000L)}")
}
}
}
private var isOnline = true
data class OnlineStatusUpdate(val onlineStatus: OnlineStatus, val guid: String, val username: String, val platform: String)
private fun updateOnlineStatus() {
if (preferenceInstance.readString(USERNAME).isBlank()) return
Firebase.firestore.document("users/${preferenceInstance.readString(USERNAME)}")
.set(OnlineStatusUpdate(
OnlineStatus(isOnline, Timestamp(Date(System.currentTimeMillis() + 3 * 60000))),
preferenceInstance.readString(GUID), preferenceInstance.readString(USERNAME), "A"
)).addOnCompleteListener {
if (isOnline) postDelayed({ updateOnlineStatus() }, 60000 * 3)
}
}
private fun updateDeviceType() {
getClient().updateDeviceType(
mapOf(
"guid" to preferenceInstance.readString(GUID),
"username" to preferenceInstance.readString(USERNAME),
"devicetype" to "A",
"app_version" to "v" + BuildConfig.VERSION_NAME + "+" + BuildConfig.VERSION_CODE,
"model" to Build.MODEL + " ^" + Build.VERSION.SDK_INT
)
).enqueue(object : Callback<ResponseMessage> {
override fun onResponse(
call: Call<ResponseMessage>,
response: Response<ResponseMessage>
) {
}
override fun onFailure(call: Call<ResponseMessage>, t: Throwable) {}
})
}
override fun onResume() {
/*In App Update Start*/
checkForAppUpdate()
stop = false
startGettingUpdate()
appUpdateManager
.appUpdateInfo
.addOnSuccessListener { appUpdateInfo ->
if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
// If update is in progress
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
activityResultLauncher,
AppUpdateOptions.newBuilder(appUpdateType).build()
)
} else if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
// If the update is downloaded but not installed, notify the user to complete the update.
popupSnackBarForCompleteUpdate()
}
}
/*In App Update End*/
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, intentFilter);
notificationReceiver = NotificationReceiver { intent ->
val binding = ItemSnackbarBinding.inflate(LayoutInflater.from(this))
val dialog = Dialog(this)
if (intent.getStringExtra("type") == "voice") {
ActVoiceCall.type = 31
ActVoiceCall.username = intent.getStringExtra("username")!!
ActVoiceCall.token = intent.getStringExtra("squadid")!!
startActivity(Intent(this, ActVoiceCall::class.java))
return@NotificationReceiver
}
if (intent.getStringExtra("type") == "video") {
ActVideoCall.type = 32
ActVideoCall.username = intent.getStringExtra("username")!!
ActVideoCall.token = intent.getStringExtra("squadid")!!
startActivity(Intent(this, ActVideoCall::class.java))
return@NotificationReceiver
}
binding.icon.visibility = View.GONE
binding.desc.text = intent.getStringExtra("desc")
binding.root.setOnClickListener {
dialog.dismiss()
when (intent.getStringExtra("type")) {
"11" -> {
val frag = FragProfileView()
frag.arguments = Bundle().apply {
putString("guid", intent.getStringExtra("guid"))
putString("username", intent.getStringExtra("username"))
}
navigateTo(frag, true)
}
"13" -> {
navigateTo(FragFavorite(), true)
}
"22", "12" -> {
ShortcutBadger.removeCount(this)
preferenceInstance.writeInt("bbadge", 0)
navigateTo(FragIntros(), true)
}
"missed call", "14", "15" -> {
val frag =
FragChat(global = intent.getStringExtra("chatid") == "spinnr-global")
frag.arguments = Bundle().apply {
putString("guid", intent.getStringExtra("guid"))
putString("username", intent.getStringExtra("username"))
}
navigateTo(frag, true)
}
"1701" -> {
if (CoinModelImpl.recentlyEarnCoin(CoinModelImpl.DAILY_SPIN)) {
showSnackBar("You've already recorded today's video. Come back tomorrow.")
} else navigateTo(FragDailyVideo(), true)
}
"23", "25" -> {
FragSquadChat.squadId = intent.getStringExtra("squadid") ?: ""
if (FragSquadChat.squadId.isNotBlank()) {
navigateTo(FragSquadChat().apply {
arguments = Bundle().apply {
putString("id", intent.getStringExtra("squadid"))
putString("name", "")
putBoolean("forSpinny", false)
}
})
}
}
"24" -> {
navigateTo(FragSquadInfo().apply {
arguments = Bundle().apply {
putString("id", intent.getStringExtra("squadid"))
}
})
}
"voice" -> {
ActVoiceCall.type = 31
ActVoiceCall.username = intent.getStringExtra("username")!!
ActVoiceCall.token = ""
startActivity(Intent(this, ActVoiceCall::class.java))
}
"video" -> {
ActVideoCall.type = 32
ActVideoCall.username = intent.getStringExtra("username")!!
ActVideoCall.token = ""
startActivity(Intent(this, ActVideoCall::class.java))
}
}
}
dialog.setContentView(binding.root)
dialog.window?.setBackgroundDrawable(null)
dialog.window?.setDimAmount(0f)
dialog.window?.attributes?.apply {
gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
y = (height() * .75f).toInt()
}
dialog.show()
postDelayed({
dialog.dismiss()
}, 1600)
}
postDelayed({
if (preferenceInstance.readString("squadid")
.isNotBlank()
) navigateTo(FragSquadInfo().apply {
arguments = Bundle().apply {
putString("id", preferenceInstance.readString("squadid"))
}
})
if (preferenceInstance.readString("eventid").isNotBlank()) {
FragEventDetail.event = EventsImpl.EventsModel()
FragEventDetail.event.id = preferenceInstance.readString("eventid")
navigateTo(FragEventDetail().apply {
postDelayed({
preferenceInstance.writeString("eventid", "")
}, 1200)
})
}
preferenceInstance.writeString("squadid", "")
}, 1000)
super.onResume()
}
override fun onPause() {
stop = true
unregisterReceiver(receiver)
notificationReceiver = null
super.onPause()
}
private fun updateSquadBadge() {
val count = SquadRepo.requestCount + SquadRepo.unreadMessageCount
binding.txtSquadCount.visibility =
if (count == 0 || netNotConnected()) View.GONE else View.VISIBLE
if (count > 0) {
if (binding.txtSquadCount.text.isNullOrEmpty())
onNotificationCountUpdated(count, true, "squad")
else {
if (binding.txtSquadCount.text.toString().toInt() < count) {
val newCount =
binding.txtSquadCount.text.toString().toInt() - count
onNotificationCountUpdated(newCount, false, "squad")
} else {
val newCount =
count - binding.txtSquadCount.text.toString().toInt()
onNotificationCountUpdated(newCount, true, "squad")
}
}
} else {
if (!binding.txtSquadCount.text.isNullOrEmpty()) {
onNotificationCountUpdated(binding.txtSquadCount.text.toString().toInt(), false, "squad")
}
}
binding.txtSquadCount.text = "$count"
}
private fun setup() {
binding.imgBack.setOnClickListener(this)
binding.layoutTabHome.setOnClickListener(this)
binding.layoutTabSquad.setOnClickListener(this)
binding.layoutTabReels.setOnClickListener(this)
binding.layoutTabChat.setOnClickListener(this)
binding.layoutTabProfile.setOnClickListener(this)
binding.layoutTabEvent.setOnClickListener(this)
when (intent.getStringExtra("type")) {
"11" -> {
val frag = FragProfileView()
frag.arguments = Bundle().apply {
putString("guid", intent.getStringExtra("guid"))
putString("username", intent.getStringExtra("username"))
}
navigateTo(frag, true)
}
"13" -> {
navigateTo(FragFavorite(), true)
}
"22", "12" -> {
navigateTo(FragIntros(), true)
}
"missed call", "14", "15" -> {
val frag = FragChat(global = intent.getStringExtra("chatid") == "spinnr-global")
frag.arguments = Bundle().apply {
putString("guid", intent.getStringExtra("guid"))
putString("username", intent.getStringExtra("username"))
}
navigateTo(frag, true)
}
"1701" -> {
if (CoinModelImpl.recentlyEarnCoin(CoinModelImpl.DAILY_SPIN)) {
showSnackBar("You've already recorded today's video. Come back tomorrow.")
} else navigateTo(FragDailyVideo(), true)
}
"23", "25" -> {
FragSquadChat.squadId = intent.getStringExtra("squadid") ?: ""
if (FragSquadChat.squadId.isNotBlank()) navigateTo(FragSquadChat().apply {
arguments = Bundle().apply {
putString("id", intent.getStringExtra("squadid"))
putBoolean("forSpinny", false)
}
})
}
"24" -> {
navigateTo(FragSquadInfo().apply {
arguments = Bundle().apply {
putString("id", intent.getStringExtra("squadid"))
}
})
}
"voice" -> {
ActVoiceCall.type = 31
ActVoiceCall.username = intent.getStringExtra("username")!!
ActVoiceCall.token = ""
startActivity(Intent(this, ActVoiceCall::class.java))
}
"video" -> {
ActVideoCall.type = 32
ActVideoCall.username = intent.getStringExtra("username")!!
ActVideoCall.token = ""
startActivity(Intent(this, ActVideoCall::class.java))
}
}
AFirebaseService.listeners = null
ChatRepo.assets = assets
ChatRepo.start()
ChatRepo.countListener = null
SquadRepo.start()
SquadRepo.homeBadgeListener = CompleteListener { updateSquadBadge() }
getCredApi()
}
private fun createChannel() : NotificationManager {
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
val channel = NotificationChannel("Spinnr-Chat", "Spinnr-Chat", NotificationManager.IMPORTANCE_LOW)
val audioAttr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val sound = Uri.parse("android.resource://${packageName}/${R.raw.push_notification}")
channel.importance = NotificationManager.IMPORTANCE_LOW
channel.lockscreenVisibility = Notification.VISIBILITY_SECRET
channel.setShowBadge(true)
channel.setSound(null, null)
service.createNotificationChannel(channel)
}
return service
}
private fun getPushNotificationSettings() {
getClient().getAllPushNotificationTypes(
mapOf(
"username" to preferenceInstance.readString(
USERNAME
), "guid" to preferenceInstance.readString(GUID)
)
)
.enqueue(object : Callback<NotificationSettingImpl> {
override fun onResponse(
call: Call<NotificationSettingImpl>,
response: Response<NotificationSettingImpl>
) {
if (response.body()?.code == "1")
response.body()?.saveResponse()
getSelectedPushNotificationSettings()
}
override fun onFailure(call: Call<NotificationSettingImpl>, t: Throwable) {
getSelectedPushNotificationSettings()
}
})
}
private fun getSelectedPushNotificationSettings() {
getClient().getUserNotificationSettings(
mapOf(
"username" to preferenceInstance.readString(USERNAME),
"guid" to preferenceInstance.readString(GUID)
)
)
.enqueue(object : Callback<NotificationSettingImpl> {
override fun onResponse(
call: Call<NotificationSettingImpl>,
response: Response<NotificationSettingImpl>
) {
if (response.body()?.code == "1") {
response.body()?.saveResponse()
val savedData = NotificationSettingImpl.getResponse()
savedData.data.forEach { it.enable = it.status == 1 }
savedData.saveResponse()
}
notificationSettingUpdate(-1)
}
override fun onFailure(call: Call<NotificationSettingImpl>, t: Throwable) {}
})
}
fun getSpotifyToken() {
val builder = AuthorizationRequest.Builder(
Constant.SPOTIFY_CLIENT_ID, AuthorizationResponse.Type.CODE, Constant.REDIRECT_URI
)
builder.setShowDialog(true).setScopes(arrayOf("user-top-read"))
.setCampaign("your-campaign-token")
val request = builder.build()
AuthorizationClient.openLoginInBrowser(this, request)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val uri = intent!!.data
if (uri != null) {
var response = AuthorizationResponse.fromUri(uri)
when (response.type) {
AuthorizationResponse.Type.CODE -> {
Log.e("Spotify Token", "Home Code Browser--" + response.code)
preferenceInstance.writeString(Preference.SPOTIFY_ACCESS_CODE, response.code)
callTokenApi(response.code)
}
AuthorizationResponse.Type.ERROR -> {
Log.e("Spotify Error Browser", response.error)
}
else -> {}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
// Check if result comes from the correct activity
if (requestCode == REQUEST_CODE) {
val response = AuthorizationClient.getResponse(resultCode, intent)
when (response.type) {
AuthorizationResponse.Type.CODE -> {
Log.e("Spotify Token", "Home Code--" + response.code)
preferenceInstance.writeString(Preference.SPOTIFY_ACCESS_CODE, response.code)
callTokenApi(response.code)
}
AuthorizationResponse.Type.ERROR -> {
Log.e("Spotify Error", response.error)
}
else -> {}
}
} else if (resultCode == 117) {
checkNotificationPermission()
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
if (grantResults[0] == -1) showMessage(
"Please grant notification permission from settings.",
narrowPadding = true,
expanded = true,
) {
val i = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
i.data = uri
startActivityForResult(i, 117)
}
Log.w(
"423u5",
">>> ${requestCode} PERMISSION RESULT ${permissions.toList()} || ${grantResults.toList()}"
)
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun checkNotificationPermission() {
var flag = true
when {
ContextCompat.checkSelfPermission(
this, Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED -> {
Log.i("423u5", ">>. PERMISSION GRANTED")
return
}
shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) -> {
Log.i("423u5", ">>. ASK FOR DIALGO")
showMessage(
"Please grant notification permission from settings.",
narrowPadding = true,
expanded = true,
) {
val i = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
i.data = uri
startActivityForResult(i, 117)
}
}
else -> {
Log.w("423u5", ">>. REQUEST PERMISSION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
flag = false
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO), 1)
}
}
}
if (flag) {
requestPermissions(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO), 2)
}
}
private fun callTokenApi(code: String) {
ApiClient.spotifyAccessTokenApi().getAccessToken(
"Basic ZjE1OTk0NDEwMGMxNDcyY2IxODU1ZWI3MzMxN2I5Mzc6YjBmY2Q0MzFiODI2NDU4YmFkMjFhMzlhYTRjODIzYzE=",
"application/x-www-form-urlencoded",
"authorization_code",
code,
Constant.REDIRECT_URI
).enqueue(object : Callback<SpotifyAccessToken> {
override fun onResponse(
call: Call<SpotifyAccessToken>, response: Response<SpotifyAccessToken>
) {
if (response.isSuccessful) {
preferenceInstance.writeString(
Preference.SPOTIFY_TOKEN, response.body()!!.accessToken!!
)
preferenceInstance.writeString(
Preference.SPOTIFY_REFRESH_TOKEN, response.body()!!.refreshToken!!
)
callArtistListApi()
}
}
override fun onFailure(call: Call<SpotifyAccessToken>, t: Throwable) {
Log.e("Failure", "callTokenApi------->>" + t.message)
}
})
}
fun callArtistListApi() {
ApiClient.spotifyApi().getArtists(
"Bearer " + preferenceInstance.readString(Preference.SPOTIFY_TOKEN), "application/json"
).enqueue(object : Callback<SpotifyArtistModel> {
override fun onResponse(
call: Call<SpotifyArtistModel>, response: Response<SpotifyArtistModel>
) {
if (response.isSuccessful) {
if (response.body()!!.items!!.isNotEmpty()) {
artistList.clear()
response.body()!!.items?.let { artistList.addAll(it) }
addItemsInList()
} else {
updateSpotify("")
}
} else {
callRefreshTokenApi()
}
}
override fun onFailure(call: Call<SpotifyArtistModel>, t: Throwable) {
Log.e("Failure", "callArtistListApi------->>" + t.message)
}
})
}
fun callRefreshTokenApi() {
val base64AuthValue = getBase64Value(
Constant.SPOTIFY_CLIENT_ID, Constant.SPOTIFY_CLIENT_SECRET_KEY
)
val refreshToken = preferenceInstance.readString(Preference.SPOTIFY_REFRESH_TOKEN)
ApiClient.spotifyAccessTokenApi().refreshAccessToken(
"Basic ZjE1OTk0NDEwMGMxNDcyY2IxODU1ZWI3MzMxN2I5Mzc6YjBmY2Q0MzFiODI2NDU4YmFkMjFhMzlhYTRjODIzYzE=",
"application/x-www-form-urlencoded",
"refresh_token",
refreshToken
).enqueue(object : Callback<SpotifyRefreshTokenModel> {
override fun onResponse(
call: Call<SpotifyRefreshTokenModel>, response: Response<SpotifyRefreshTokenModel>
) {
if (response.isSuccessful) {
preferenceInstance.writeString(
Preference.SPOTIFY_TOKEN, response.body()!!.accessToken!!
)
}
}
override fun onFailure(call: Call<SpotifyRefreshTokenModel>, t: Throwable) {
Log.e("Failure", "callRefreshTokenApi------->>" + t.message)
}
})
}
private fun addItemsInList() {
artistDataList.clear()
for (i in 0 until artistList.size) {
val imageList = ArrayList<ArtistImageUrl>()
imageList.addAll(getImageListUrl(artistList[i].images))
val listItems = ArtistData(artistList[i].name!!, imageList)
artistDataList.add(listItems)
}
val gson = Gson()
val json = gson.toJson(artistDataList)
Log.e("Artist List", "---" + json)
preferenceInstance.writeString(Preference.SPOTIFY_ARTISTS, json)
updateSpotify(json)
}
private fun getBase64Value(spotifyClientId: String, spotifyClientSecretKey: String): String {
val str = "$spotifyClientId:$spotifyClientSecretKey"
var bytesEncoded: ByteArray? = ByteArray(0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
bytesEncoded = Base64.getEncoder().encode(str.toByteArray())
}
println("encoded value is " + String(bytesEncoded!!))
return String(bytesEncoded)
}
fun updateSpotify(json: String) {
if (!netConnected()) {
showSnackBar(getString(R.string.no_internet))
return
}
val refData: RefDataModel = RefDataModel.getRefData()
val profile: ProfileModel = profileData()
val add = profile.address().toString().toLocationArray()
var lat = ""
var long = ""
val locationObject: JSONObject? = null
locationObject?.let {
lat = it.getString("latLong").split(",").first()
long = it.getString("latLong").split(",").last()
}
val peopleType = getSelectionData(RefDataModel.K_PEOPLE_TYPE, profile.peopletype, refData)
val identity = getSelectionData(RefDataModel.K_IDENTITY, profile.identity, refData)
val interest = getSelectionData(RefDataModel.K_INTERESTS, profile.interest, refData)
val ethnicity = getSelectionData(RefDataModel.K_ETHNICITY, profile.ethnicity, refData)
val religion = getSelectionData(RefDataModel.K_RELIGION, profile.religion, refData)
val userData = UserDataUpdateModel(
preferenceInstance.readString(USERNAME),
preferenceInstance.readString(GUID),
add[0],
add[1],
add[2],
lat,
long,
profile.age,
getSelectionIds(RefDataModel.K_PEOPLE_TYPE, peopleType, refData),
getSelectionIds(RefDataModel.K_INTERESTS, interest, refData),
getSelectionIds(RefDataModel.K_IDENTITY, identity, refData),
getSelectionIds(RefDataModel.K_ETHNICITY, ethnicity, refData),
getSelectionIds(RefDataModel.K_RELIGION, religion, refData),
json
)
getClient().updateUserProfileRaw(userData)
.enqueue(object : Callback<ResponseBean<ProfileModel>> {
override fun onResponse(
call: Call<ResponseBean<ProfileModel>>,
response: Response<ResponseBean<ProfileModel>>
) {
if (response.isSuccessful) {
response.body()?.let {
if (it.code == 0) {
updateProfileData()
System.out.println(response.body()!!.msg)
}
}
}
}
override fun onFailure(call: Call<ResponseBean<ProfileModel>>, t: Throwable) {
}
})
}
private fun getSelectionIds(
key: String, data: String, refData: RefDataModel
): MutableList<RefModel> {
val selected = mutableListOf<RefModel>()
val items = data.split(",")
items.forEach {
val refModel = refData.getObject(key, it.trim())
if (refModel.refid != -1) selected.add(refModel)
}
return selected
}
private fun getSelectionData(
key: String, data: MutableList<RefModel>?, refData: RefDataModel
): String {
var output = ""
if (data == null || data.isEmpty()) return output.ifEmpty { "-" }
data.forEach {
val obj = refData.getObject(key, it.refid)
if (output.isNotEmpty()) output += ", "
output += obj.name
}
return output.ifEmpty { "-" }
}
private fun getImageListUrl(images: List<SpotifyImageUrl>?): Collection<ArtistImageUrl> {
val imageList = ArrayList<ArtistImageUrl>()
for (i in 0 until images!!.size) {
if (images[i].height == 160 && images[i].width == 160) {
val imgUrl = ArtistImageUrl(images[i].url!!)
imageList.add(imgUrl)
}
}
if (imageList.isEmpty() && images.isNotEmpty()) {
val imgUrl = ArtistImageUrl(images[0].url!!)
imageList.add(imgUrl)
}
return imageList
}
override fun onDestroy() {
Log.e("vi26", "onDestroy: ActivityDestroyed")
preferenceInstance.writeBoolean("destroy", true)
ChatRepo.end()
SquadRepo.end()
NetworkListener.listener = null
AFirebaseService.listeners = null
appUpdateManager.unregisterListener(this)
super.onDestroy()
}
fun navigateTo(frag: Fragment, backStack: Boolean = true) {
//ImageLoader.clear()
try {
preferenceInstance.writeInt(Preference.CAMERA_FACE, 0)
preferenceInstance.writeInt(Preference.CAMERA_FLASH, 0)
preferenceInstance.writeBoolean("netNotConnected", netNotConnected())
Log.e("423u5","Navigate to ${frag.javaClass.simpleName}")
changeUi(frag)
if (frag::class.java.simpleName == visibleFragment()) return
val a0 = supportFragmentManager.beginTransaction()
.replace(R.id.containerHome, frag, frag.javaClass.simpleName)
if (backStack) a0.addToBackStack(frag.javaClass.simpleName).commit()
else a0.commit()
}catch (e:Exception){
Log.e("423u5", "navigate fragment error ${e.localizedMessage}")
e.printStackTrace()
}
postDelayed({
Log.e("423u5", "Visible frag ${visibleFragment()}")
}, 1000)
}
private fun visibleFragment(): String {
for (frag in supportFragmentManager.fragments)
if (frag.isVisible)
return frag::class.java.simpleName
return ""
}
fun tooltip(v: String) {
if (tooltipShow(v) && v == "daily_spin_1")
showTooltip(
binding.imgTabReels, R.string.the_daily_spin, R.string.tooltip_desc_the_daily_spin_1
) {
tooltipShown(v)
tooltip("tooltip_events")
}
else if (tooltipShow(v) && v == "tooltip_events")
showTooltip(
binding.imgTabEvent, R.string.events, R.string.tooltip_desc_events
) {
tooltipShown(v)
tooltip("tooltip_squad")
}
else if (tooltipShow(v) && v == "daily_spin_2")
showTooltip(
binding.imgTabReels, R.string.the_daily_spin, R.string.tooltip_desc_the_daily_spin_2
) { tooltipShown(v) }
else if (tooltipShow(v) && v == "tooltip_squad") {
showTooltip(
binding.imgTabSquad, R.string.spinnr_squads_, R.string.spinnr_squads_desc
) {
tooltipShown(v)
fragHome?.showSpinnyDialog()
}
}
}
fun changeUi(frag: Fragment) {
binding.toolbarParent.visibility = View.VISIBLE
binding.bottomTab.visibility = View.VISIBLE
binding.imgBack.visibility = View.GONE
binding.tvTitle.visibility = View.GONE
binding.tvTitle.text = ""
when (frag) {
is FragReels, is FragHome, is FragProfile, is FragSquad, is FragChatList -> {
binding.toolbarParent.visibility = View.GONE
binding.bottomTab.visibility = View.VISIBLE
}
is FragSupport -> {
binding.bottomTab.visibility = View.GONE
binding.imgBack.visibility = View.VISIBLE
binding.tvTitle.visibility = View.VISIBLE
binding.tvTitle.text = mContext.resources.getString(R.string.support)
}
is FragChangeTheme -> {
binding.bottomTab.visibility = View.GONE
binding.imgBack.visibility = View.VISIBLE
binding.tvTitle.visibility = View.VISIBLE
binding.tvTitle.text = mContext.resources.getString(R.string.change_theme)
}
is FragManageAccount -> {
binding.bottomTab.visibility = View.GONE
binding.imgBack.visibility = View.VISIBLE
binding.tvTitle.visibility = View.VISIBLE
binding.tvTitle.text = mContext.resources.getString(R.string.setting)
}
is FragProfileOptions -> {
binding.bottomTab.visibility = View.GONE
binding.imgBack.visibility = View.VISIBLE
binding.tvTitle.visibility = View.VISIBLE
binding.tvTitle.text = getString(R.string.friend_nd_more)
}
is FragNotificationSettings -> {
binding.bottomTab.visibility = View.GONE
binding.imgBack.visibility = View.VISIBLE
binding.tvTitle.visibility = View.VISIBLE
binding.tvTitle.text = mContext.resources.getString(R.string.push_notifications)
}
is FragEventList, is FragEvents -> {
binding.toolbarParent.visibility = View.GONE
binding.bottomTab.visibility = View.VISIBLE
}
else -> {
binding.toolbarParent.visibility = View.GONE
binding.bottomTab.visibility = View.GONE
}
}
}
fun getCredApi(listener: FragListener? = null) {
getClient().getCreds(
preferenceInstance.readString(GUID), preferenceInstance.readString(USERNAME)
).enqueue(object : Callback<CoinModelImpl> {
override fun onResponse(
call: Call<CoinModelImpl>, response: Response<CoinModelImpl>
) {
if (response.isSuccessful) {
if (response.body()?.code != 0) {
//baseContext.logout()
} else {
response.body()?.saveLocal()
listener?.onFragResponse("result", "coin")
}
}
}
override fun onFailure(call: Call<CoinModelImpl>, t: Throwable) {}
})
}
fun updateProfileData(listener: CompleteListener? = null) {
getClient().getProfileDetail(
preferenceInstance.readString(GUID),
preferenceInstance.readString(USERNAME),
).enqueue(object : Callback<ResponseListBean<ProfileModel>> {
override fun onResponse(
call: Call<ResponseListBean<ProfileModel>>,
response: Response<ResponseListBean<ProfileModel>>
) {
if (response.body()?.code == 0) {
response.body()?.saveUserData()
listener?.onComplete()
} else {
showMessage("${response.body()?.msg}") { logout() }
}
}
override fun onFailure(call: Call<ResponseListBean<ProfileModel>>, t: Throwable) {
}
})
}
fun concatMedia(listener: CompleteListener? = null) {
val data = profileData()
val concatFiles = mutableListOf<MediaConcatPath>()
val items = data.video?.filter { it.category == "P" } ?: mutableListOf()
items.subList(0, items.size.coerceAtMost(5)).forEach {
concatFiles.add(MediaConcatPath(it.filenamepath))
}
val request = MediaConcatModel(
preferenceInstance.readString(GUID),
preferenceInstance.readString(USERNAME),
"ffmpeg-enc",
concatFiles
)
ApiClient.getMediaClient().concatMedia(request)
.enqueue(object : Callback<ResponseBean<JsonElement>> {
override fun onResponse(
call: Call<ResponseBean<JsonElement>>,
response: Response<ResponseBean<JsonElement>>
) {
listener?.onComplete()
}
override fun onFailure(call: Call<ResponseBean<JsonElement>>, t: Throwable) {
listener?.onComplete()
}
})
}
private val onBackPressedCallback: OnBackPressedCallback =
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
hideKeyboard()
if (supportFragmentManager.backStackEntryCount > 0) {
supportFragmentManager.popBackStack()
getVisibleFragment()?.let { changeUi(it) }
}
}
}
fun hideKeyboard() {
val imm: InputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(findViewById<FrameLayout>(R.id.containerHome).windowToken, 0)
}
private fun getVisibleFragment(): Fragment? {
for (frag in supportFragmentManager.fragments) if (frag.isVisible) {
return frag
}
return null
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.imgBack -> {
onBackPressed()
}
R.id.layoutTabHome -> {
deselectAllTab()
selectHomeTab()
navigateTo(fragHome!!, false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
R.id.layoutTabSquad -> {
App.appsFlyerEvent("Squad_Home")
deselectAllTab()
selectSquadTab()
SquadRepo.addedToSupport = false
SquadRepo.addedToWelcome = false
SquadRepo.addToSupport()
SquadRepo.addToWelcome()
navigateTo(FragSquad(), false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
R.id.layoutTabReels -> {
App.appsFlyerEvent("Daily_Spin_View")
deselectAllTab()
selectReelsTab()
navigateTo(FragReels(), false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
R.id.layoutTabChat -> {
deselectAllTab()
selectChatTab()
navigateTo(FragChatList(), false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
R.id.layoutTabProfile -> {
deselectAllTab()
selectProfileTab()
navigateTo(FragProfile(), false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
R.id.layoutTabEvent -> {
deselectAllTab()
selectEventTab()
App.appsFlyerEvent("Event_Home")
navigateTo(FragEvents(), false)
binding.layoutTabHome.isEnabled = false
binding.layoutTabSquad.isEnabled = false
binding.layoutTabReels.isEnabled = false
binding.layoutTabChat.isEnabled = false
binding.layoutTabProfile.isEnabled = false
binding.layoutTabEvent.isEnabled = false
postDelayed({
binding.layoutTabHome.isEnabled = true
binding.layoutTabSquad.isEnabled = true
binding.layoutTabReels.isEnabled = true
binding.layoutTabChat.isEnabled = true
binding.layoutTabProfile.isEnabled = true
binding.layoutTabEvent.isEnabled = true
}, 500)
}
else -> {
}
}
}
private fun selectProfileTab() {
binding.imgTabProfile.imageTintList = null
binding.imgTabProfile.setImageResource(R.mipmap.ic_tab_profile_select)
}
private fun selectChatTab() {
binding.imgTabChat.imageTintList = null
binding.imgTabChat.setImageResource(R.mipmap.ic_tab_chat_select)
}
private fun selectReelsTab() {
binding.imgTabReels.imageTintList = null
binding.imgTabReels.setImageResource(R.mipmap.ic_tab_dailies_select)
}
private fun selectSquadTab() {
binding.imgTabSquad.imageTintList = null
binding.imgTabSquad.setImageResource(R.mipmap.ic_tab_squad_select)
}
fun selectHomeTab() {
binding.imgTabHome.imageTintList = null
binding.imgTabHome.setImageResource(R.mipmap.ic_tab_home_select)
}
fun selectEventTab() {
binding.imgTabEvent.imageTintList = null
binding.imgTabEvent.setImageResource(R.mipmap.ic_tab_events_select)
isSelected = true
}
var isSelected = false
fun deselectAllTab() {
binding.imgTabHome.setImageResource(R.mipmap.ic_tab_home_deselect)
binding.imgTabSquad.setImageResource(R.mipmap.ic_tab_squad_deselect)
binding.imgTabReels.setImageResource(R.mipmap.ic_tab_dailies_deselect)
binding.imgTabChat.setImageResource(R.mipmap.ic_tab_chat_deselect)
binding.imgTabProfile.setImageResource(R.mipmap.ic_tab_profile_deselect)
binding.imgTabEvent.setImageResource(R.mipmap.ic_tab_events_deselect)
if (systemDarkMode == MODE_NIGHT_YES) {
binding.imgTabHome.imageTintList = getColorStateList(R.color.white)
binding.imgTabSquad.imageTintList = getColorStateList(R.color.white)
binding.imgTabReels.imageTintList = getColorStateList(R.color.white)
binding.imgTabChat.imageTintList = getColorStateList(R.color.white)
binding.imgTabProfile.imageTintList = getColorStateList(R.color.white)
binding.imgTabEvent.imageTintList = getColorStateList(R.color.white)
} else {
binding.imgTabHome.imageTintList = null
binding.imgTabSquad.imageTintList = null
binding.imgTabReels.imageTintList = null
binding.imgTabChat.imageTintList = null
binding.imgTabProfile.imageTintList = null
binding.imgTabEvent.imageTintList = null
}
isSelected = false
}
fun getFragmentByTag(tag: String) = supportFragmentManager.findFragmentByTag(tag)
/*In App Update Start*/
override fun onStateUpdate(installState: InstallState) {
if (installState.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackBarForCompleteUpdate()
}
}
private lateinit var appUpdateManager: AppUpdateManager
private val appUpdateType = AppUpdateType.FLEXIBLE
private val activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
when (result.resultCode) {
RESULT_CANCELED -> {
Log.w(TAG, "onActivityResult: Unable to download Update, User Cancelled")
Toast.makeText(
this@ActHome,
"In order to use the latest features, please update the app",
Toast.LENGTH_SHORT
).show()
setup()
}
ActivityResult.RESULT_IN_APP_UPDATE_FAILED -> {
Log.w(TAG, "onActivityResult: ${result.resultCode}")
Toast.makeText(
this@ActHome,
"In order to use the latest features, please update the app",
Toast.LENGTH_SHORT
).show()
setup()
}
RESULT_OK -> {
Log.i(TAG, "onActivityResult: ${result.data}")
Toast.makeText(
this@ActHome,
"Downloading update...",
Toast.LENGTH_SHORT
).show()
setup()
}
}
}
private fun checkForAppUpdate() {
appUpdateManager.appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
Log.w(TAG, "checkForAppUpdate: ${appUpdateInfo.updateAvailability()}")
val isUpdateAvailable =
appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
val isUpdateAllowed = appUpdateInfo.isFlexibleUpdateAllowed
if (isUpdateAvailable && isUpdateAllowed) {
// Before starting an update, register a listener for updates.
appUpdateManager.registerListener(this)
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
activityResultLauncher,
AppUpdateOptions.newBuilder(appUpdateType).build()
)
} else {
setup()
}
}.addOnFailureListener {
Log.w(TAG, "checkForAppUpdate: ${it.message}")
setup()
}
}
// Checks that the update is not installed during 'onResume()'.
// However, you should execute this check at all app entry points.
private fun popupSnackBarForCompleteUpdate() {
Snackbar.make(
findViewById(android.R.id.content),
"An update has just been downloaded. Restarting app in 5 Seconds.",
Snackbar.LENGTH_SHORT
).apply {
lifecycleScope.launch {
delay(5000L)
}
appUpdateManager.completeUpdate()
show()
}
}
/*In App Update End*/
}
fun interface NotificationCountUpdateListener {
fun onNotificationCountUpdated(count: Int, isAdded: Boolean, isFrom: String)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment