Skip to content

Commit

Permalink
refactor: Address NestedBlockDepth warnings by reducing block nesting
Browse files Browse the repository at this point in the history
  • Loading branch information
PavloNetrebchuk committed Nov 13, 2024
1 parent 920499c commit 0a56e13
Show file tree
Hide file tree
Showing 11 changed files with 280 additions and 245 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,39 @@ class HandleErrorInterceptor(
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())

val responseCode = response.code
if (responseCode in 400..500 && response.body != null) {
val jsonStr = response.body!!.string()

try {
val errorResponse = gson.fromJson(jsonStr, ErrorResponse::class.java)
if (errorResponse?.error != null) {
when (errorResponse.error) {
ERROR_INVALID_GRANT -> {
throw EdxError.InvalidGrantException()
}

ERROR_USER_NOT_ACTIVE -> {
throw EdxError.UserNotActiveException()
}

else -> {
return response
}
}
} else if (errorResponse?.errorDescription != null) {
throw EdxError.ValidationException(errorResponse.errorDescription ?: "")
}
} catch (e: JsonSyntaxException) {
throw IOException("JsonSyntaxException $jsonStr", e)
}
if (isErrorResponse(response)) {
val jsonStr = response.body?.string() ?: return response
return handleErrorResponse(response, jsonStr)
}

return response
}

private fun isErrorResponse(response: Response): Boolean {
return response.code in 400..500 && response.body != null
}

private fun handleErrorResponse(response: Response, jsonStr: String): Response {
return try {
val errorResponse = gson.fromJson(jsonStr, ErrorResponse::class.java)
handleParsedErrorResponse(errorResponse) ?: response
} catch (e: JsonSyntaxException) {
throw IOException("JsonSyntaxException $jsonStr", e)
}
}

private fun handleParsedErrorResponse(errorResponse: ErrorResponse?): Response? {
val exception = when {
errorResponse?.error == ERROR_INVALID_GRANT -> EdxError.InvalidGrantException()
errorResponse?.error == ERROR_USER_NOT_ACTIVE -> EdxError.UserNotActiveException()
errorResponse?.errorDescription != null ->
EdxError.ValidationException(errorResponse.errorDescription.orEmpty())

else -> return null
}
throw exception
}

companion object {
const val ERROR_INVALID_GRANT = "invalid_grant"
const val ERROR_USER_NOT_ACTIVE = "user_not_active"
Expand Down
7 changes: 2 additions & 5 deletions app/src/main/java/org/openedx/app/deeplink/DeepLinkRouter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ class DeepLinkRouter(
navigateToCourseDashboard(fm, deepLink, courseTitle)
}

DeepLinkType.UNENROLL, DeepLinkType.REMOVE_BETA_TESTER -> { /* Just navigate to dashboard */
}

DeepLinkType.UNENROLL, DeepLinkType.REMOVE_BETA_TESTER -> {} // Just navigate to dashboard
DeepLinkType.COURSE_VIDEOS -> navigateToCourseVideos(fm, deepLink)
DeepLinkType.COURSE_DATES -> navigateToCourseDates(fm, deepLink)
DeepLinkType.COURSE_DISCUSSION -> navigateToCourseDiscussion(fm, deepLink)
Expand All @@ -94,8 +92,7 @@ class DeepLinkRouter(
}

DeepLinkType.FORUM_COMMENT -> navigateToDiscussionCommentWithDiscussion(fm, deepLink)
else -> { /* ignore */
}
else -> {} // ignore
}
}

Expand Down
3 changes: 0 additions & 3 deletions config/detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,6 @@ complexity:
ignoreAnnotatedFunctions: [ 'Composable' ]
ignoreOverridden: true
ignorePrivate: true
NestedBlockDepth:
active: true
threshold: 6
CyclomaticComplexMethod:
active: true
ignoreAnnotated: [ 'Composable' ]
Expand Down
35 changes: 9 additions & 26 deletions core/src/main/java/org/openedx/core/domain/model/Block.kt
Original file line number Diff line number Diff line change
Expand Up @@ -158,33 +158,16 @@ data class EncodedVideos(
}

private fun getDefaultVideoInfoForDownloading(): VideoInfo? {
var result: VideoInfo? = null

if (isPreferredVideoInfo(mobileLow)) {
result = mobileLow
} else if (isPreferredVideoInfo(mobileHigh)) {
result = mobileHigh
} else if (isPreferredVideoInfo(desktopMp4)) {
result = desktopMp4
} else {
fallback?.let {
if (isPreferredVideoInfo(it) &&
!VideoUtil.videoHasFormat(it.url, AppDataConstants.VIDEO_FORMAT_M3U8)
) {
result = fallback
}
}

if (result == null) {
hls?.let {
if (isPreferredVideoInfo(it)) {
result = hls
}
}
}
return when {
isPreferredVideoInfo(mobileLow) -> mobileLow
isPreferredVideoInfo(mobileHigh) -> mobileHigh
isPreferredVideoInfo(desktopMp4) -> desktopMp4
fallback != null && isPreferredVideoInfo(fallback) &&
!VideoUtil.videoHasFormat(fallback!!.url, AppDataConstants.VIDEO_FORMAT_M3U8) -> fallback

hls != null && isPreferredVideoInfo(hls) -> hls
else -> null
}

return result
}

private fun isPreferredVideoInfo(videoInfo: VideoInfo?): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,41 +38,43 @@ abstract class AbstractDownloader : KoinComponent {
): DownloadResult {
isCanceled = false
return try {
val response = downloadApi.downloadFile(url).body()
if (response != null) {
val file = File(path)
if (file.exists()) {
file.delete()
val responseBody = downloadApi.downloadFile(url).body() ?: return DownloadResult.ERROR
initializeFile(path)
responseBody.byteStream().use { inputStream ->
FileOutputStream(File(path)).use { outputStream ->
writeToFile(inputStream, outputStream)
}
file.createNewFile()
input = response.byteStream()
currentDownloadingFilePath = path
fos = FileOutputStream(file)
fos.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
var read: Int
while (input!!.read(buffer).also { read = it } != -1) {
output?.write(buffer, 0, read)
}
output?.flush()
}
DownloadResult.SUCCESS
} else {
DownloadResult.ERROR
}
DownloadResult.SUCCESS
} catch (e: Exception) {
e.printStackTrace()
if (isCanceled) {
DownloadResult.CANCELED
} else {
DownloadResult.ERROR
}
if (isCanceled) DownloadResult.CANCELED else DownloadResult.ERROR
} finally {
fos?.close()
input?.close()
closeResources()
}
}

private fun initializeFile(path: String) {
val file = File(path)
if (file.exists()) file.delete()
file.createNewFile()
currentDownloadingFilePath = path
}

private fun writeToFile(inputStream: InputStream, outputStream: FileOutputStream) {
val buffer = ByteArray(BUFFER_SIZE)
var bytesRead: Int
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
}

private fun closeResources() {
fos?.close()
input?.close()
}

suspend fun cancelDownloading() {
isCanceled = true
withContext(Dispatchers.IO) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,33 +60,54 @@ abstract class BaseDownloadViewModel(

private suspend fun updateDownloadModelsStatus(models: List<DownloadModel>) {
val downloadModelMap = models.associateBy { it.id }
for (item in downloadableChildrenMap) {
var downloadingCount = 0
var downloadedCount = 0
item.value.forEach { blockId ->
val downloadModel = downloadModelMap[blockId]
if (downloadModel != null) {
if (downloadModel.downloadedState.isWaitingOrDownloading) {
downloadModelsStatus[blockId] = DownloadedState.DOWNLOADING
downloadingCount++
} else if (downloadModel.downloadedState.isDownloaded) {
downloadModelsStatus[blockId] = DownloadedState.DOWNLOADED
downloadedCount++
}
} else {
downloadModelsStatus[blockId] = DownloadedState.NOT_DOWNLOADED

downloadableChildrenMap.forEach { (parentId, children) ->
val (downloadingCount, downloadedCount) = updateChildrenStatus(children, downloadModelMap)
updateParentStatus(parentId, children.size, downloadingCount, downloadedCount)
}

downloadingModelsList = models.filter { it.downloadedState.isWaitingOrDownloading }
_downloadingModelsFlow.emit(downloadingModelsList)
}

private fun updateChildrenStatus(
children: List<String>,
downloadModelMap: Map<String, DownloadModel>
): Pair<Int, Int> {
var downloadingCount = 0
var downloadedCount = 0

children.forEach { blockId ->
val downloadModel = downloadModelMap[blockId]
downloadModelsStatus[blockId] = when {
downloadModel?.downloadedState?.isWaitingOrDownloading == true -> {
downloadingCount++
DownloadedState.DOWNLOADING
}

downloadModel?.downloadedState?.isDownloaded == true -> {
downloadedCount++
DownloadedState.DOWNLOADED
}
}

downloadModelsStatus[item.key] = when {
downloadingCount > 0 -> DownloadedState.DOWNLOADING
downloadedCount == item.value.size -> DownloadedState.DOWNLOADED
else -> DownloadedState.NOT_DOWNLOADED
}
}

downloadingModelsList = models.filter { it.downloadedState.isWaitingOrDownloading }
_downloadingModelsFlow.emit(downloadingModelsList)
return downloadingCount to downloadedCount
}

private fun updateParentStatus(
parentId: String,
childrenSize: Int,
downloadingCount: Int,
downloadedCount: Int
) {
downloadModelsStatus[parentId] = when {
downloadingCount > 0 -> DownloadedState.DOWNLOADING
downloadedCount == childrenSize -> DownloadedState.DOWNLOADED
else -> DownloadedState.NOT_DOWNLOADED
}
}

protected fun setBlocks(list: List<Block>) {
Expand Down Expand Up @@ -200,23 +221,27 @@ abstract class BaseDownloadViewModel(
}
}

@Suppress("NestedBlockDepth")
protected fun addDownloadableChildrenForSequentialBlock(sequentialBlock: Block) {
for (item in sequentialBlock.descendants) {
allBlocks[item]?.let { blockDescendant ->
if (blockDescendant.type == BlockType.VERTICAL) {
for (unitBlockId in blockDescendant.descendants) {
val block = allBlocks[unitBlockId]
if (block?.isDownloadable == true) {
val id = sequentialBlock.id
val children = downloadableChildrenMap[id] ?: listOf()
downloadableChildrenMap[id] = children + block.id
}
sequentialBlock.descendants.forEach { descendantId ->
val blockDescendant = allBlocks[descendantId] ?: return@forEach

if (blockDescendant.type == BlockType.VERTICAL) {
blockDescendant.descendants.forEach { unitBlockId ->
val block = allBlocks[unitBlockId]
if (block?.isDownloadable == true) {
addDownloadableChild(sequentialBlock.id, block.id)
}
}
}
}
}

private fun addDownloadableChild(parentId: String, childId: String) {
val children = downloadableChildrenMap[parentId] ?: listOf()
downloadableChildrenMap[parentId] = children + childId
}

fun logBulkDownloadToggleEvent(toggle: Boolean) {
logEvent(
CoreAnalyticsEvent.VIDEO_BULK_DOWNLOAD_TOGGLE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,22 +93,14 @@ class DownloadHelper(
}

private fun calculateDirectorySize(directory: File): Long {
var size: Long = 0
if (!directory.exists()) return 0

if (directory.exists()) {
val files = directory.listFiles()

if (files != null) {
for (file in files) {
size += if (file.isDirectory) {
calculateDirectorySize(file)
} else {
file.length()
}
}
return directory.listFiles()?.sumOf { file ->
if (file.isDirectory) {
calculateDirectorySize(file)
} else {
file.length()
}
}

return size
} ?: 0
}
}
Loading

0 comments on commit 0a56e13

Please sign in to comment.