Skip to content

Commit

Permalink
Fix some detekt issues
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandarIlic committed Nov 21, 2024
1 parent 29835eb commit 983dcc4
Show file tree
Hide file tree
Showing 54 changed files with 242 additions and 164 deletions.
116 changes: 83 additions & 33 deletions app/detekt-baseline.xml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import net.primal.android.nostr.db.eventRelayHintsUpserter
import net.primal.android.nostr.ext.flatMapAsEventHintsPO
import net.primal.android.nostr.ext.flatMapAsWordCount
import net.primal.android.nostr.ext.flatMapNotNullAsCdnResource
import net.primal.android.nostr.ext.flatMapNotNullAsLinkPreviewResource
import net.primal.android.nostr.ext.flatMapNotNullAsVideoThumbnailsMap
import net.primal.android.nostr.ext.mapAsEventZapDO
import net.primal.android.nostr.ext.mapAsPostDataPO
import net.primal.android.nostr.ext.mapAsProfileDataPO
Expand All @@ -23,8 +21,6 @@ import net.primal.android.thread.db.ArticleCommentCrossRef

suspend fun ArticleResponse.persistToDatabaseAsTransaction(userId: String, database: PrimalDatabase) {
val cdnResources = this.cdnResources.flatMapNotNullAsCdnResource().asMapByKey { it.url }
val videoThumbnails = this.cdnResources.flatMapNotNullAsVideoThumbnailsMap()
val linkPreviews = this.primalLinkPreviews.flatMapNotNullAsLinkPreviewResource().asMapByKey { it.url }
val eventHints = this.primalRelayHints.flatMapAsEventHintsPO()
val wordsCountMap = this.primalLongFormWords.flatMapAsWordCount()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ fun Article.mapAsFeedArticleUi(): FeedArticleUi {
)
}

fun Int?.wordsCountToReadingTime() = ((this ?: 1) / 200) + 1
private const val WordsPerMinute = 200

fun Int?.wordsCountToReadingTime() = ((this ?: 1) / WordsPerMinute) + 1

fun FeedArticleUi.generateNaddrString(): String =
Naddr(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fun GridLoadingPlaceholder(
}

BoxWithConstraints {
val height = maxWidth / 3
val height = maxWidth.div(other = 3)
Column(
modifier = modifier
.verticalScroll(state = rememberScrollState())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fun HeightAdjustableLoadingLazyListPlaceholder(
) {
InfiniteLottieAnimation(
modifier = Modifier
.scale(10f)
.scale(scale = 10f)
.padding(itemPadding),
resId = animationRawResId,
)
Expand Down Expand Up @@ -87,8 +87,7 @@ fun LazyListScope.heightAdjustableLoadingLazyListPlaceholder(
.height(height),
) {
InfiniteLottieAnimation(
modifier = Modifier
.scale(10f),
modifier = Modifier.scale(scale = 10f),
resId = animationRawResId,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ fun NostrUserText(
LegendaryStyle.BROWN -> PrimalIcons.PrimalBadgeBrown
LegendaryStyle.BLUE -> PrimalIcons.PrimalBadgeBlue
LegendaryStyle.SUN_FIRE -> PrimalIcons.PrimalBadgeSunFire
LegendaryStyle.NO_CUSTOMIZATION -> throw IllegalStateException()
LegendaryStyle.NO_CUSTOMIZATION -> error("Should not be rendered with custom icon.")
}
Icon(
imageVector = badgeVector,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import net.primal.android.core.compose.icons.primaliconpack.More
import net.primal.android.stats.ui.EventZapUiModel
import net.primal.android.theme.AppTheme

private const val MaxZapsInSingleLine = 3

@ExperimentalLayoutApi
@Composable
fun ThreadNoteTopZapsSection(
Expand All @@ -34,7 +36,7 @@ fun ThreadNoteTopZapsSection(
onClick: (() -> Unit)? = null,
) {
Box(modifier = modifier) {
if (zaps.size > 3) {
if (zaps.size > MaxZapsInSingleLine) {
TwoLineTopZapsSection(
modifier = Modifier.animateContentSize(),
zaps = zaps,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ package net.primal.android.core.ext

import android.content.ActivityNotFoundException
import androidx.compose.ui.platform.UriHandler
import timber.log.Timber

fun UriHandler.openUriSafely(uri: String) {
try {
openUri(uri)
} catch (error: ActivityNotFoundException) {
Timber.w(error)
} catch (_: ActivityNotFoundException) {
runCatching {
val scheme = if (uri.contains("@")) "mailto" else "https"
openUri("$scheme://$uri")
}
} catch (error: IllegalArgumentException) {
} catch (_: IllegalArgumentException) {
runCatching {
openUri("https://$uri")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import coil.decode.VideoFrameDecoder
import coil.disk.DiskCache

object AvatarCoilImageLoader {
private var avatarCoilImageLoader: ImageLoader? = null
private var defaultImageLoader: ImageLoader? = null
private var noGifsImageLoader: ImageLoader? = null

fun provideImageLoader(context: Context): ImageLoader =
avatarCoilImageLoader ?: constructImageLoader(context = context).also { avatarCoilImageLoader = it }
defaultImageLoader ?: constructImageLoader(context = context).also { defaultImageLoader = it }

fun provideNoGifsImageLoader(context: Context): ImageLoader =
noGifsImageLoader ?: constructNoGifsImageLoader(context = context).also { noGifsImageLoader = it }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class PrimalImageLoaderFactory @Inject constructor(
.diskCache {
DiskCache.Builder()
.directory(imageCacheDir)
.maxSizePercent(0.02)
.maxSizePercent(percent = 0.02)
.build()
}
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,13 @@ fun Long.shortened(): String {
return "1T+"
}

@Suppress("MagicNumber")
fun Long.toMegaBytes(roundUp: Boolean = true): String = (this / 1024f.pow(2)).toStringWithTwoDecimals(roundUp)

@Suppress("MagicNumber")
fun Long.toGigaBytes(roundUp: Boolean = true): String = (this / 1024f.pow(3)).toStringWithTwoDecimals(roundUp)

@Suppress("MagicNumber")
fun Float.toStringWithTwoDecimals(roundUp: Boolean): String {
val roundedValue = if (roundUp) {
ceil(this * 100) / 100
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class NotePublishHandler @Inject constructor(
replyToAuthorId: String? = null,
): Boolean {
if (rootArticleId != null && rootPostId != null) {
throw IllegalStateException("You can not have both article and post as root events.")
error("You can not have both article and post as root events.")
}

val replyPostData = replyToPostId?.let {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ class AdvancedSearchViewModel @Inject constructor(
} else {
val stringFilters = arrayOf(
this.orientation.toFilterQuery(),
this.minReadTime.times(238).toFilterQueryOrEmpty("minwords", delimiter = ":"),
this.maxReadTime.times(238).toFilterQueryOrEmpty("maxwords", delimiter = ":"),
this.minReadTime.times(other = 238).toFilterQueryOrEmpty("minwords", delimiter = ":"),
this.maxReadTime.times(other = 238).toFilterQueryOrEmpty("maxwords", delimiter = ":"),
this.minDuration.toFilterQueryOrEmpty("minduration", delimiter = ":"),
this.maxDuration.toFilterQueryOrEmpty("maxduration", delimiter = ":"),
this.minContentScore.toFilterQueryOrEmpty("minscore", delimiter = ":"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ import net.primal.android.explore.home.ui.PEOPLE_INDEX
import net.primal.android.explore.home.ui.TOPICS_INDEX
import net.primal.android.explore.home.ui.ZAPS_INDEX
import net.primal.android.explore.home.zaps.ExploreZaps
import net.primal.android.feeds.domain.buildExploreMediaFeedSpec
import net.primal.android.feeds.domain.exploreMediaFeedSpec
import net.primal.android.notes.feed.grid.MediaFeedGrid
import net.primal.android.notes.feed.note.ui.events.NoteCallbacks
import net.primal.android.premium.legend.LegendaryStyle
Expand Down Expand Up @@ -200,7 +200,7 @@ private fun ExploreHomeScreen(

MEDIA_INDEX -> {
MediaFeedGrid(
feedSpec = buildExploreMediaFeedSpec(),
feedSpec = exploreMediaFeedSpec,
contentPadding = paddingValues,
onNoteClick = { noteCallbacks.onNoteClick?.invoke(it) },
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,44 +87,62 @@ class ExplorePeopleViewModel @Inject constructor(
private fun follow(profileId: String) =
viewModelScope.launch {
updateStateProfileFollow(profileId)
try {

val followResult = runCatching {
profileRepository.follow(
userId = activeAccountStore.activeUserId(),
followedUserId = profileId,
)
} catch (error: Exception) {
Timber.w(error)
when (error) {
is WssException, is NostrPublishException, is ProfileRepository.FollowListNotFound ->
setState { copy(error = UiError.FailedToFollowUser(error)) }

is MissingRelaysException -> setState { copy(error = UiError.MissingRelaysConfiguration(error)) }
}

else -> setState { copy(error = UiError.GenericError()) }
if (followResult.isFailure) {
followResult.exceptionOrNull()?.let { error ->
Timber.w(error)
when (error) {
is WssException, is NostrPublishException, is ProfileRepository.FollowListNotFound ->
setState { copy(error = UiError.FailedToFollowUser(error)) }

is MissingRelaysException -> setState {
copy(
error = UiError.MissingRelaysConfiguration(error),
)
}

else -> setState { copy(error = UiError.GenericError()) }
}
updateStateProfileUnfollow(profileId)
}
updateStateProfileUnfollow(profileId)
}
}

private fun unfollow(profileId: String) =
viewModelScope.launch {
updateStateProfileUnfollow(profileId)
try {

val unfollowResult = runCatching {
profileRepository.unfollow(
userId = activeAccountStore.activeUserId(),
unfollowedUserId = profileId,
)
} catch (error: Exception) {
Timber.w(error)
when (error) {
is WssException, is NostrPublishException, is ProfileRepository.FollowListNotFound ->
setState { copy(error = UiError.FailedToUnfollowUser(error)) }

is MissingRelaysException -> setState { copy(error = UiError.MissingRelaysConfiguration(error)) }
}

else -> setState { copy(error = UiError.GenericError()) }
if (unfollowResult.isFailure) {
unfollowResult.exceptionOrNull()?.let { error ->
Timber.w(error)
when (error) {
is WssException, is NostrPublishException, is ProfileRepository.FollowListNotFound ->
setState { copy(error = UiError.FailedToUnfollowUser(error)) }

is MissingRelaysException -> setState {
copy(
error = UiError.MissingRelaysConfiguration(error),
)
}

else -> setState { copy(error = UiError.GenericError()) }
}
updateStateProfileFollow(profileId)
}
updateStateProfileFollow(profileId)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ private fun RowScope.TopicLoadingItem(
.height(36.dp)
.clip(RoundedCornerShape(percent = 100))
.fillMaxWidth()
.scale(20f)
.scale(scale = 20f)
.weight(weight = weight)
.border(width = 1.dp, color = Color.Red),
resId = resId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ fun buildAdvancedSearchNotificationsFeedSpec(query: String) =

fun buildReadsTopicFeedSpec(hashtag: String) = """{"kind":"reads","topic":"${hashtag.substring(startIndex = 1)}"}"""

fun buildExploreMediaFeedSpec() = """{"id":"explore-media"}"""
const val exploreMediaFeedSpec = """{"id":"explore-media"}"""

fun String.extractTopicFromFeedSpec(): String? {
val noteQueryStartIndex = this.indexOf("\"query\":\"kind:1 #")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class DvmFeedListItemViewModel @Inject constructor(
private fun onZapClick(zapAction: UiEvent.OnZapClick) =
viewModelScope.launch {
if (zapAction.dvmFeed.data.dvmLnUrlDecoded == null) {
setState { copy(error = UiError.MissingLightningAddress(RuntimeException())) }
setState { copy(error = UiError.MissingLightningAddress(IllegalStateException("Missing ln url"))) }
return@launch
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
Expand Down Expand Up @@ -238,21 +236,19 @@ private fun DvmFeedListItem(
},
)
if (showFollowsActionsAvatarRow) {
val maxAvatarsToShow = 5
val profileAvatarSize = 28.dp
val avatarVisiblePercentage = 0.75f
val avatarsShown = dvmFeed.actionUserAvatars.size.coerceAtMost(maxAvatarsToShow)
val avatarsShown = dvmFeed.actionUserAvatars.size.coerceAtMost(MaxAvatarsToShow)

AvatarThumbnailsRow(
modifier = Modifier
.size(
width = profileAvatarSize * avatarVisiblePercentage * (avatarsShown - 1) +
width = profileAvatarSize * AvatarVisiblePercentage * (avatarsShown - 1) +
profileAvatarSize,
height = profileAvatarSize,
),
avatarCdnImages = dvmFeed.actionUserAvatars,
onClick = {},
maxAvatarsToShow = maxAvatarsToShow,
maxAvatarsToShow = MaxAvatarsToShow,
displayAvatarOverflowIndicator = false,
avatarBorderColor = listItemContainerColor,
avatarSize = profileAvatarSize,
Expand All @@ -266,6 +262,9 @@ private fun DvmFeedListItem(
}
}

private const val AvatarVisiblePercentage = 0.75f
private const val MaxAvatarsToShow = 5

@Composable
fun DvmFeedThumbnail(
avatarCdnImage: CdnImage?,
Expand Down Expand Up @@ -419,7 +418,7 @@ private fun Badge(
fontWeight = FontWeight.Bold,
color = textColor,
style = AppTheme.typography.bodySmall,
fontSize = TextUnit(10f, TextUnitType.Sp),
fontSize = 10.sp,
textAlign = TextAlign.Center,
)
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package net.primal.android.networking.primal.upload

class UnsuccessfulFileUpload(cause: Throwable?) : RuntimeException()
class UnsuccessfulFileUpload : RuntimeException()
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ class RelayPool(
when (it) {
is NostrIncomingMessage.OkMessage -> emit(it)
is NostrIncomingMessage.NoticeMessage -> throw NostrNoticeException(reason = it.message)
else -> throw IllegalStateException("$it is not allowed")
else -> error("$it is not allowed")
}
}
.timeout(PUBLISH_TIMEOUT.milliseconds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ private fun String.nostrUriToBytes(): ByteArray? {
val key = matcher.group(3)?.lowercase() ?: return null
return try {
(type + key).bechToBytesOrThrow()
} catch (error: Exception) {
Timber.w(error)
} catch (ignored: Exception) {
Timber.w(ignored)
null
}
}
Expand Down Expand Up @@ -145,8 +145,8 @@ private fun String.extract(parser: (bechPrefix: String?, key: String?) -> String

return try {
parser(bechPrefix, key)
} catch (error: Exception) {
Timber.w(error)
} catch (ignored: Exception) {
Timber.w(ignored)
null
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ inline fun <reified T> PrimalEvent?.takeContentOrNull(): T? {
NostrJson.decodeFromJsonElement<T>(
NostrJson.parseToJsonElement(this.content),
)
} catch (error: IllegalArgumentException) {
} catch (_: IllegalArgumentException) {
null
}
}
Loading

0 comments on commit 983dcc4

Please sign in to comment.