Skip to content

Commit 8938457

Browse files
refactor: Changes according to detekt warnings
1 parent 0a56e13 commit 8938457

File tree

12 files changed

+212
-202
lines changed

12 files changed

+212
-202
lines changed

app/src/main/java/org/openedx/app/AppActivity.kt

Lines changed: 40 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,18 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
9393
lifecycle.addObserver(viewModel)
9494
viewModel.logAppLaunchEvent()
9595
setContentView(binding.root)
96-
val container = binding.rootLayout
9796

97+
setupWindowInsets(savedInstanceState)
98+
setupWindowSettings()
99+
setupInitialFragment(savedInstanceState)
100+
observeLogoutEvent()
101+
observeDownloadFailedDialog()
102+
103+
calendarSyncScheduler.scheduleDailySync()
104+
}
105+
106+
private fun setupWindowInsets(savedInstanceState: Bundle?) {
107+
val container = binding.rootLayout
98108
container.addView(object : View(this) {
99109
override fun onConfigurationChanged(newConfig: Configuration?) {
100110
super.onConfigurationChanged(newConfig)
@@ -103,20 +113,10 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
103113
})
104114
computeWindowSizeClasses()
105115

106-
if (savedInstanceState != null) {
107-
_insetTop = savedInstanceState.getInt(TOP_INSET, 0)
108-
_insetBottom = savedInstanceState.getInt(BOTTOM_INSET, 0)
109-
_insetCutout = savedInstanceState.getInt(CUTOUT_INSET, 0)
110-
}
111-
112-
window.apply {
113-
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
114-
115-
WindowCompat.setDecorFitsSystemWindows(this, false)
116-
117-
val insetsController = WindowInsetsControllerCompat(this, binding.root)
118-
insetsController.isAppearanceLightStatusBars = !isUsingNightModeResources()
119-
statusBarColor = Color.TRANSPARENT
116+
savedInstanceState?.let {
117+
_insetTop = it.getInt(TOP_INSET, 0)
118+
_insetBottom = it.getInt(BOTTOM_INSET, 0)
119+
_insetCutout = it.getInt(CUTOUT_INSET, 0)
120120
}
121121

122122
binding.root.setOnApplyWindowInsetsListener { _, insets ->
@@ -137,36 +137,48 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
137137
insets
138138
}
139139
binding.root.requestApplyInsetsWhenAttached()
140+
}
140141

142+
private fun setupWindowSettings() {
143+
window.apply {
144+
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
145+
WindowCompat.setDecorFitsSystemWindows(this, false)
146+
147+
val insetsController = WindowInsetsControllerCompat(this, binding.root)
148+
insetsController.isAppearanceLightStatusBars = !isUsingNightModeResources()
149+
statusBarColor = Color.TRANSPARENT
150+
}
151+
}
152+
153+
private fun setupInitialFragment(savedInstanceState: Bundle?) {
141154
if (savedInstanceState == null) {
142155
when {
143156
corePreferencesManager.user == null -> {
144-
if (viewModel.isLogistrationEnabled) {
145-
addFragment(LogistrationFragment())
157+
val fragment = if (viewModel.isLogistrationEnabled) {
158+
LogistrationFragment()
146159
} else {
147-
addFragment(SignInFragment())
160+
SignInFragment()
148161
}
162+
addFragment(fragment)
149163
}
150164

151-
whatsNewManager.shouldShowWhatsNew() -> {
152-
addFragment(WhatsNewFragment.newInstance())
153-
}
154-
155-
corePreferencesManager.user != null -> {
156-
addFragment(MainFragment.newInstance())
157-
}
165+
whatsNewManager.shouldShowWhatsNew() -> addFragment(WhatsNewFragment.newInstance())
166+
else -> addFragment(MainFragment.newInstance())
158167
}
159168

160-
val extras = intent.extras
161-
if (extras?.containsKey(DeepLink.Keys.NOTIFICATION_TYPE.value) == true) {
162-
handlePushNotification(extras)
169+
intent.extras?.takeIf { it.containsKey(DeepLink.Keys.NOTIFICATION_TYPE.value) }?.let {
170+
handlePushNotification(it)
163171
}
164172
}
173+
}
165174

175+
private fun observeLogoutEvent() {
166176
viewModel.logoutUser.observe(this) {
167177
profileRouter.restartApp(supportFragmentManager, viewModel.isLogistrationEnabled)
168178
}
179+
}
169180

181+
private fun observeDownloadFailedDialog() {
170182
lifecycleScope.launch {
171183
viewModel.downloadFailedDialog.collect {
172184
downloadDialogManager.showDownloadFailedPopup(
@@ -175,8 +187,6 @@ class AppActivity : AppCompatActivity(), InsetHolder, WindowSizeHolder {
175187
)
176188
}
177189
}
178-
179-
calendarSyncScheduler.scheduleDailySync()
180190
}
181191

182192
override fun onStart() {

app/src/main/java/org/openedx/app/data/networking/HandleErrorInterceptor.kt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ class HandleErrorInterceptor(
1414
override fun intercept(chain: Interceptor.Chain): Response {
1515
val response = chain.proceed(chain.request())
1616

17-
if (isErrorResponse(response)) {
18-
val jsonStr = response.body?.string() ?: return response
19-
return handleErrorResponse(response, jsonStr)
17+
return if (isErrorResponse(response)) {
18+
val jsonStr = response.body?.string()
19+
if (jsonStr != null) handleErrorResponse(response, jsonStr) else response
20+
} else {
21+
response
2022
}
21-
22-
return response
2323
}
2424

2525
private fun isErrorResponse(response: Response): Boolean {

app/src/main/java/org/openedx/app/data/networking/OauthRefreshTokenAuthenticator.kt

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ class OauthRefreshTokenAuthenticator(
6666
.create(AuthApi::class.java)
6767
}
6868

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

8788
DISABLED_USER_ERROR_MESSAGE, JWT_DISABLED_USER_ERROR_MESSAGE, JWT_USER_EMAIL_MISMATCH -> {
88-
runBlocking {
89-
appNotifier.send(LogoutEvent(true))
90-
}
91-
null
89+
handleDisabledUser()
9290
}
9391

9492
else -> null
9593
}
9694
}
9795

96+
private fun handleDisabledUser(): Request? {
97+
runBlocking { appNotifier.send(LogoutEvent(true)) }
98+
return null
99+
}
100+
98101
// Helper function for handling token expiration logic
99102
private fun handleTokenExpired(response: Response, refreshToken: String, accessToken: String): Request? {
100103
return try {

auth/src/main/java/org/openedx/auth/presentation/signup/SignUpViewModel.kt

Lines changed: 67 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -137,70 +137,89 @@ class SignUpViewModel(
137137

138138
fun register() {
139139
logEvent(AuthAnalyticsEvent.CREATE_ACCOUNT_CLICKED)
140-
val mapFields = uiState.value.allFields.associate { it.name to it.placeholder } +
141-
mapOf(ApiConstants.RegistrationFields.HONOR_CODE to true.toString())
142-
val resultMap = mapFields.toMutableMap()
143-
uiState.value.allFields.filter { !it.required }.forEach { (k, _) ->
144-
if (mapFields[k].isNullOrEmpty()) {
145-
resultMap.remove(k)
146-
}
147-
}
140+
val mapFields = prepareMapFields()
148141
_uiState.update { it.copy(isButtonLoading = true, validationError = false) }
142+
149143
viewModelScope.launch {
150144
try {
151145
setErrorInstructions(emptyMap())
152146
val validationFields = interactor.validateRegistrationFields(mapFields)
153147
setErrorInstructions(validationFields.validationResult)
148+
154149
if (validationFields.hasValidationError()) {
155150
_uiState.update { it.copy(validationError = true, isButtonLoading = false) }
156151
} else {
157-
val socialAuth = uiState.value.socialAuth
158-
if (socialAuth?.accessToken != null) {
159-
resultMap[ApiConstants.ACCESS_TOKEN] = socialAuth.accessToken
160-
resultMap[ApiConstants.PROVIDER] = socialAuth.authType.postfix
161-
resultMap[ApiConstants.CLIENT_ID] = config.getOAuthClientId()
162-
}
163-
interactor.register(resultMap.toMap())
164-
logEvent(
165-
event = AuthAnalyticsEvent.REGISTER_SUCCESS,
166-
params = buildMap {
167-
put(
168-
AuthAnalyticsKey.METHOD.key,
169-
(socialAuth?.authType?.methodName ?: AuthType.PASSWORD.methodName).lowercase()
170-
)
171-
}
172-
)
173-
if (socialAuth == null) {
174-
interactor.login(
175-
resultMap.getValue(ApiConstants.EMAIL),
176-
resultMap.getValue(ApiConstants.PASSWORD)
177-
)
178-
setUserId()
179-
_uiState.update { it.copy(successLogin = true, isButtonLoading = false) }
180-
appNotifier.send(SignInEvent())
181-
} else {
182-
exchangeToken(socialAuth)
183-
}
152+
handleRegistration(mapFields)
184153
}
185154
} catch (e: Exception) {
186-
_uiState.update { it.copy(isButtonLoading = false) }
187-
if (e.isInternetError()) {
188-
_uiMessage.emit(
189-
UIMessage.SnackBarMessage(
190-
resourceManager.getString(coreR.string.core_error_no_connection)
191-
)
192-
)
193-
} else {
194-
_uiMessage.emit(
195-
UIMessage.SnackBarMessage(
196-
resourceManager.getString(coreR.string.core_error_unknown_error)
197-
)
198-
)
155+
handleRegistrationError(e)
156+
}
157+
}
158+
}
159+
160+
private fun prepareMapFields(): MutableMap<String, String> {
161+
val mapFields = uiState.value.allFields.associate { it.name to it.placeholder } +
162+
mapOf(ApiConstants.RegistrationFields.HONOR_CODE to true.toString())
163+
164+
return mapFields.toMutableMap().apply {
165+
uiState.value.allFields.filter { !it.required }.forEach { (key, _) ->
166+
if (mapFields[key].isNullOrEmpty()) {
167+
remove(key)
199168
}
200169
}
201170
}
202171
}
203172

173+
private suspend fun handleRegistration(mapFields: MutableMap<String, String>) {
174+
val resultMap = mapFields.toMutableMap()
175+
uiState.value.socialAuth?.let { socialAuth ->
176+
resultMap[ApiConstants.ACCESS_TOKEN] = socialAuth.accessToken
177+
resultMap[ApiConstants.PROVIDER] = socialAuth.authType.postfix
178+
resultMap[ApiConstants.CLIENT_ID] = config.getOAuthClientId()
179+
}
180+
181+
interactor.register(resultMap)
182+
logRegisterSuccess()
183+
184+
if (uiState.value.socialAuth == null) {
185+
loginWithCredentials(resultMap)
186+
} else {
187+
exchangeToken(uiState.value.socialAuth!!)
188+
}
189+
}
190+
191+
private fun logRegisterSuccess() {
192+
logEvent(
193+
AuthAnalyticsEvent.REGISTER_SUCCESS,
194+
buildMap {
195+
put(
196+
AuthAnalyticsKey.METHOD.key,
197+
(uiState.value.socialAuth?.authType?.methodName ?: AuthType.PASSWORD.methodName).lowercase()
198+
)
199+
}
200+
)
201+
}
202+
203+
private suspend fun loginWithCredentials(resultMap: Map<String, String>) {
204+
interactor.login(
205+
resultMap.getValue(ApiConstants.EMAIL),
206+
resultMap.getValue(ApiConstants.PASSWORD)
207+
)
208+
setUserId()
209+
_uiState.update { it.copy(successLogin = true, isButtonLoading = false) }
210+
appNotifier.send(SignInEvent())
211+
}
212+
213+
private suspend fun handleRegistrationError(e: Exception) {
214+
_uiState.update { it.copy(isButtonLoading = false) }
215+
val errorMessage = if (e.isInternetError()) {
216+
coreR.string.core_error_no_connection
217+
} else {
218+
coreR.string.core_error_unknown_error
219+
}
220+
_uiMessage.emit(UIMessage.SnackBarMessage(resourceManager.getString(errorMessage)))
221+
}
222+
204223
fun socialAuth(fragment: Fragment, authType: AuthType) {
205224
_uiState.update { it.copy(isLoading = true) }
206225
viewModelScope.launch {

config/detekt.yml

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,15 @@ style:
4343
active: true
4444
ignoreAnnotated:
4545
- 'Preview'
46-
MaxLineLength:
47-
active: false
4846
ForbiddenComment:
4947
active: false
50-
ReturnCount:
51-
active: true
52-
max: 3
5348
SerialVersionUIDInSerializableClass:
5449
active: false
5550

5651
complexity:
5752
active: true
5853
LongMethod:
5954
active: true
60-
threshold: 80
6155
ignoreAnnotated: [ 'Composable' ]
6256
ignoreFunction: [ 'onCreateView' ]
6357
LargeClass:
@@ -71,7 +65,6 @@ complexity:
7165
TooManyFunctions:
7266
active: true
7367
thresholdInClasses: 30
74-
thresholdInFiles: 30
7568
thresholdInInterfaces: 30
7669
ignoreAnnotatedFunctions: [ 'Composable' ]
7770
ignoreOverridden: true

core/src/main/java/org/openedx/core/domain/model/Block.kt

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,11 @@ data class Block(
6363
fun isCompleted() = completion == 1.0
6464

6565
fun getFirstDescendantBlock(blocks: List<Block>): Block? {
66-
if (blocks.isEmpty()) return null
67-
descendants.forEach { descendant ->
68-
blocks.find { it.id == descendant }?.let { descendantBlock ->
69-
return descendantBlock
70-
}
66+
return descendants.firstOrNull { descendant ->
67+
blocks.find { it.id == descendant } != null
68+
}?.let { descendant ->
69+
blocks.find { it.id == descendant }
7170
}
72-
return null
7371
}
7472

7573
fun getDownloadsCount(blocks: List<Block>): Int {

core/src/main/java/org/openedx/core/module/TranscriptManager.kt

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -105,19 +105,14 @@ class TranscriptManager(
105105
}
106106

107107
private fun fetchTranscriptResponse(url: String?): InputStream? {
108-
if (url == null) {
109-
return null
110-
}
111-
val response: InputStream?
112-
try {
113-
if (has(url)) {
114-
response = getInputStream(url)
115-
return response
116-
}
108+
if (url == null) return null
109+
110+
return try {
111+
if (has(url)) getInputStream(url) else null
117112
} catch (e: IOException) {
118113
e.printStackTrace()
114+
null
119115
}
120-
return null
121116
}
122117

123118
private fun getTranscriptDir(): File? {

0 commit comments

Comments
 (0)