Skip to content

Commit

Permalink
refactor: Changes according to detekt warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
PavloNetrebchuk committed Nov 13, 2024
1 parent 0a56e13 commit 8938457
Show file tree
Hide file tree
Showing 12 changed files with 212 additions and 202 deletions.
70 changes: 40 additions & 30 deletions app/src/main/java/org/openedx/app/AppActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,18 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
lifecycle.addObserver(viewModel)
viewModel.logAppLaunchEvent()
setContentView(binding.root)
val container = binding.rootLayout

setupWindowInsets(savedInstanceState)
setupWindowSettings()
setupInitialFragment(savedInstanceState)
observeLogoutEvent()
observeDownloadFailedDialog()

calendarSyncScheduler.scheduleDailySync()
}

private fun setupWindowInsets(savedInstanceState: Bundle?) {
val container = binding.rootLayout
container.addView(object : View(this) {
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
Expand All @@ -103,20 +113,10 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
})
computeWindowSizeClasses()

if (savedInstanceState != null) {
_insetTop = savedInstanceState.getInt(TOP_INSET, 0)
_insetBottom = savedInstanceState.getInt(BOTTOM_INSET, 0)
_insetCutout = savedInstanceState.getInt(CUTOUT_INSET, 0)
}

window.apply {
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

WindowCompat.setDecorFitsSystemWindows(this, false)

val insetsController = WindowInsetsControllerCompat(this, binding.root)
insetsController.isAppearanceLightStatusBars = !isUsingNightModeResources()
statusBarColor = Color.TRANSPARENT
savedInstanceState?.let {
_insetTop = it.getInt(TOP_INSET, 0)
_insetBottom = it.getInt(BOTTOM_INSET, 0)
_insetCutout = it.getInt(CUTOUT_INSET, 0)
}

binding.root.setOnApplyWindowInsetsListener { _, insets ->
Expand All @@ -137,36 +137,48 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
insets
}
binding.root.requestApplyInsetsWhenAttached()
}

private fun setupWindowSettings() {
window.apply {
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
WindowCompat.setDecorFitsSystemWindows(this, false)

val insetsController = WindowInsetsControllerCompat(this, binding.root)
insetsController.isAppearanceLightStatusBars = !isUsingNightModeResources()
statusBarColor = Color.TRANSPARENT
}
}

private fun setupInitialFragment(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
when {
corePreferencesManager.user == null -> {
if (viewModel.isLogistrationEnabled) {
addFragment(LogistrationFragment())
val fragment = if (viewModel.isLogistrationEnabled) {
LogistrationFragment()
} else {
addFragment(SignInFragment())
SignInFragment()
}
addFragment(fragment)
}

whatsNewManager.shouldShowWhatsNew() -> {
addFragment(WhatsNewFragment.newInstance())
}

corePreferencesManager.user != null -> {
addFragment(MainFragment.newInstance())
}
whatsNewManager.shouldShowWhatsNew() -> addFragment(WhatsNewFragment.newInstance())
else -> addFragment(MainFragment.newInstance())
}

val extras = intent.extras
if (extras?.containsKey(DeepLink.Keys.NOTIFICATION_TYPE.value) == true) {
handlePushNotification(extras)
intent.extras?.takeIf { it.containsKey(DeepLink.Keys.NOTIFICATION_TYPE.value) }?.let {
handlePushNotification(it)
}
}
}

private fun observeLogoutEvent() {
viewModel.logoutUser.observe(this) {
profileRouter.restartApp(supportFragmentManager, viewModel.isLogistrationEnabled)
}
}

private fun observeDownloadFailedDialog() {
lifecycleScope.launch {
viewModel.downloadFailedDialog.collect {
downloadDialogManager.showDownloadFailedPopup(
Expand All @@ -175,8 +187,6 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
)
}
}

calendarSyncScheduler.scheduleDailySync()
}

override fun onStart() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ class HandleErrorInterceptor(
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())

if (isErrorResponse(response)) {
val jsonStr = response.body?.string() ?: return response
return handleErrorResponse(response, jsonStr)
return if (isErrorResponse(response)) {
val jsonStr = response.body?.string()
if (jsonStr != null) handleErrorResponse(response, jsonStr) else response
} else {
response
}

return response
}

private fun isErrorResponse(response: Response): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class OauthRefreshTokenAuthenticator(
.create(AuthApi::class.java)
}

@Suppress("ReturnCount")
@Synchronized
override fun authenticate(route: Route?, response: Response): Request? {
val accessToken = preferencesManager.accessToken
Expand All @@ -85,16 +86,18 @@ class OauthRefreshTokenAuthenticator(
}

DISABLED_USER_ERROR_MESSAGE, JWT_DISABLED_USER_ERROR_MESSAGE, JWT_USER_EMAIL_MISMATCH -> {
runBlocking {
appNotifier.send(LogoutEvent(true))
}
null
handleDisabledUser()
}

else -> null
}
}

private fun handleDisabledUser(): Request? {
runBlocking { appNotifier.send(LogoutEvent(true)) }
return null
}

// Helper function for handling token expiration logic
private fun handleTokenExpired(response: Response, refreshToken: String, accessToken: String): Request? {
return try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,70 +137,89 @@ class SignUpViewModel(

fun register() {
logEvent(AuthAnalyticsEvent.CREATE_ACCOUNT_CLICKED)
val mapFields = uiState.value.allFields.associate { it.name to it.placeholder } +
mapOf(ApiConstants.RegistrationFields.HONOR_CODE to true.toString())
val resultMap = mapFields.toMutableMap()
uiState.value.allFields.filter { !it.required }.forEach { (k, _) ->
if (mapFields[k].isNullOrEmpty()) {
resultMap.remove(k)
}
}
val mapFields = prepareMapFields()
_uiState.update { it.copy(isButtonLoading = true, validationError = false) }

viewModelScope.launch {
try {
setErrorInstructions(emptyMap())
val validationFields = interactor.validateRegistrationFields(mapFields)
setErrorInstructions(validationFields.validationResult)

if (validationFields.hasValidationError()) {
_uiState.update { it.copy(validationError = true, isButtonLoading = false) }
} else {
val socialAuth = uiState.value.socialAuth
if (socialAuth?.accessToken != null) {
resultMap[ApiConstants.ACCESS_TOKEN] = socialAuth.accessToken
resultMap[ApiConstants.PROVIDER] = socialAuth.authType.postfix
resultMap[ApiConstants.CLIENT_ID] = config.getOAuthClientId()
}
interactor.register(resultMap.toMap())
logEvent(
event = AuthAnalyticsEvent.REGISTER_SUCCESS,
params = buildMap {
put(
AuthAnalyticsKey.METHOD.key,
(socialAuth?.authType?.methodName ?: AuthType.PASSWORD.methodName).lowercase()
)
}
)
if (socialAuth == null) {
interactor.login(
resultMap.getValue(ApiConstants.EMAIL),
resultMap.getValue(ApiConstants.PASSWORD)
)
setUserId()
_uiState.update { it.copy(successLogin = true, isButtonLoading = false) }
appNotifier.send(SignInEvent())
} else {
exchangeToken(socialAuth)
}
handleRegistration(mapFields)
}
} catch (e: Exception) {
_uiState.update { it.copy(isButtonLoading = false) }
if (e.isInternetError()) {
_uiMessage.emit(
UIMessage.SnackBarMessage(
resourceManager.getString(coreR.string.core_error_no_connection)
)
)
} else {
_uiMessage.emit(
UIMessage.SnackBarMessage(
resourceManager.getString(coreR.string.core_error_unknown_error)
)
)
handleRegistrationError(e)
}
}
}

private fun prepareMapFields(): MutableMap<String, String> {
val mapFields = uiState.value.allFields.associate { it.name to it.placeholder } +
mapOf(ApiConstants.RegistrationFields.HONOR_CODE to true.toString())

return mapFields.toMutableMap().apply {
uiState.value.allFields.filter { !it.required }.forEach { (key, _) ->
if (mapFields[key].isNullOrEmpty()) {
remove(key)
}
}
}
}

private suspend fun handleRegistration(mapFields: MutableMap<String, String>) {
val resultMap = mapFields.toMutableMap()
uiState.value.socialAuth?.let { socialAuth ->
resultMap[ApiConstants.ACCESS_TOKEN] = socialAuth.accessToken
resultMap[ApiConstants.PROVIDER] = socialAuth.authType.postfix
resultMap[ApiConstants.CLIENT_ID] = config.getOAuthClientId()
}

interactor.register(resultMap)
logRegisterSuccess()

if (uiState.value.socialAuth == null) {
loginWithCredentials(resultMap)
} else {
exchangeToken(uiState.value.socialAuth!!)
}
}

private fun logRegisterSuccess() {
logEvent(
AuthAnalyticsEvent.REGISTER_SUCCESS,
buildMap {
put(
AuthAnalyticsKey.METHOD.key,
(uiState.value.socialAuth?.authType?.methodName ?: AuthType.PASSWORD.methodName).lowercase()
)
}
)
}

private suspend fun loginWithCredentials(resultMap: Map<String, String>) {
interactor.login(
resultMap.getValue(ApiConstants.EMAIL),
resultMap.getValue(ApiConstants.PASSWORD)
)
setUserId()
_uiState.update { it.copy(successLogin = true, isButtonLoading = false) }
appNotifier.send(SignInEvent())
}

private suspend fun handleRegistrationError(e: Exception) {
_uiState.update { it.copy(isButtonLoading = false) }
val errorMessage = if (e.isInternetError()) {
coreR.string.core_error_no_connection
} else {
coreR.string.core_error_unknown_error
}
_uiMessage.emit(UIMessage.SnackBarMessage(resourceManager.getString(errorMessage)))
}

fun socialAuth(fragment: Fragment, authType: AuthType) {
_uiState.update { it.copy(isLoading = true) }
viewModelScope.launch {
Expand Down
7 changes: 0 additions & 7 deletions config/detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,15 @@ style:
active: true
ignoreAnnotated:
- 'Preview'
MaxLineLength:
active: false
ForbiddenComment:
active: false
ReturnCount:
active: true
max: 3
SerialVersionUIDInSerializableClass:
active: false

complexity:
active: true
LongMethod:
active: true
threshold: 80
ignoreAnnotated: [ 'Composable' ]
ignoreFunction: [ 'onCreateView' ]
LargeClass:
Expand All @@ -71,7 +65,6 @@ complexity:
TooManyFunctions:
active: true
thresholdInClasses: 30
thresholdInFiles: 30
thresholdInInterfaces: 30
ignoreAnnotatedFunctions: [ 'Composable' ]
ignoreOverridden: true
Expand Down
10 changes: 4 additions & 6 deletions core/src/main/java/org/openedx/core/domain/model/Block.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,11 @@ data class Block(
fun isCompleted() = completion == 1.0

fun getFirstDescendantBlock(blocks: List<Block>): Block? {
if (blocks.isEmpty()) return null
descendants.forEach { descendant ->
blocks.find { it.id == descendant }?.let { descendantBlock ->
return descendantBlock
}
return descendants.firstOrNull { descendant ->
blocks.find { it.id == descendant } != null
}?.let { descendant ->
blocks.find { it.id == descendant }
}
return null
}

fun getDownloadsCount(blocks: List<Block>): Int {
Expand Down
15 changes: 5 additions & 10 deletions core/src/main/java/org/openedx/core/module/TranscriptManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,14 @@ class TranscriptManager(
}

private fun fetchTranscriptResponse(url: String?): InputStream? {
if (url == null) {
return null
}
val response: InputStream?
try {
if (has(url)) {
response = getInputStream(url)
return response
}
if (url == null) return null

return try {
if (has(url)) getInputStream(url) else null
} catch (e: IOException) {
e.printStackTrace()
null
}
return null
}

private fun getTranscriptDir(): File? {
Expand Down
Loading

0 comments on commit 8938457

Please sign in to comment.