before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if (podcast != null) {
findPodcastEpisodes(podcast, currentEpisodeUuid)
} else {
findPlaylistEpisodes(source.uuid, currentEpisodeUuid)
}
}
AutoPlaySource.Predefined.Downloads -> findDownloadedEpisodes()
... | I thought this might help with our support tickets. | val podcast = podcastManager.findPodcastByUuid(uuid = source.uuid)
if (podcast != null) {
findPodcastEpisodes(podcast, currentEpisodeUuid)
} else {
findPlaylistEpisodes(source.uuid, currentEpisodeUuid)
}
... | @@ -56,6 +57,10 @@ class AutoPlaySelector @Inject constructor(
episodes.getOrNull(currentEpisodeIndex + 1) ?: episodes.firstOrNull()?.takeIf { it.uuid != currentEpisodeUuid }
}
+ if (episode != null) {
+ LogBuffer.i(LogBuffer.TAG_PLAYBACK, "Auto play selected episode=${episode.... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playback/AutoPlaySelector.kt | 26 | Kotlin | 0.214 | suggestion | 51 | 51 | 51 | false | Fix auto-play playing completed episodes | 4,846 | Automattic/pocket-casts-android | 1,688 | Kotlin | geekygecko | geekygecko |
}
internal suspend fun updatePodcastIfRequired(existingPodcast: Podcast, updatedPodcast: Podcast) {
if (existingPodcast.title != updatedPodcast.title ||
existingPodcast.author != updatedPodcast.author ||
existingPodcast.podcastCategory != updatedPodcast.podcastCategory ||
... | The logging statement that was previously present when a podcast required an update has been removed. This makes it harder to debug and monitor when podcasts are being updated during refresh operations. Consider adding the log statement back in the updatePodcastIfRequired method. | }
internal suspend fun updatePodcastIfRequired(existingPodcast: Podcast, updatedPodcast: Podcast) {
if (existingPodcast.title != updatedPodcast.title ||
existingPodcast.author != updatedPodcast.author ||
existingPodcast.podcastCategory != updatedPodcast.podcastCategory ||
... | @@ -118,15 +109,36 @@ class PodcastRefresherImpl @Inject constructor(
episodeManager.deleteEpisodesWithoutSync(episodesToDelete, playbackManager)
}
- if (originalPodcast != existingPodcast) {
- LogBuffer.i(LogBuffer.TAG_BACKGROUND_TASKS, "Refresh required update... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/PodcastRefresherImpl.kt | 26 | Kotlin | 0.643 | bug | 280 | 27 | 28 | false | Fix unfollow issue | 4,856 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
}
if (episodesToDelete.isNotEmpty()) {
episodeManager.deleteEpisodesWithoutSync(episodesToDelete, playbackManager)
}
updatePodcastIfRequired(existingPodcast, updatedPodcast)
LogBuffer.i(LogBuffer.TAG_BACKGROUND_TASKS, "Refreshing podcast ... | The uuid parameter should use existingPodcast.uuid instead of updatedPodcast.uuid for semantic clarity. While both should have the same UUID in practice (they represent the same entity), using existingPodcast.uuid makes it clearer that we're identifying which existing record to update. This also matches the comparison ... | }
if (episodesToDelete.isNotEmpty()) {
episodeManager.deleteEpisodesWithoutSync(episodesToDelete, playbackManager)
}
updatePodcastIfRequired(existingPodcast, updatedPodcast)
LogBuffer.i(LogBuffer.TAG_BACKGROUND_TASKS, "Refreshing podcast ... | @@ -118,15 +109,36 @@ class PodcastRefresherImpl @Inject constructor(
episodeManager.deleteEpisodesWithoutSync(episodesToDelete, playbackManager)
}
- if (originalPodcast != existingPodcast) {
- LogBuffer.i(LogBuffer.TAG_BACKGROUND_TASKS, "Refresh required update... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/PodcastRefresherImpl.kt | 26 | Kotlin | 1 | suggestion | 440 | 39 | 40 | false | Fix unfollow issue | 4,856 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
width <= 50.dp -> 3.dp
width <= 200.dp -> 4.dp
else -> 8.dp
}
}
@Composable
fun PodcastImage(
uuid: String,
modifier: Modifier = Modifier,
imageSize: Dp = 56.dp,
imageRequestSize: Dp = imageSize,
cornerSize: Dp? = imageSize / 14,
elevation: Dp? = 2.dp,
placeholde... | The new `imageRequestSize` parameter lacks documentation explaining its purpose and when it should differ from `imageSize`. Consider adding a KDoc comment to clarify that this parameter controls the size of the image loaded from the network/cache while `imageSize` controls the display size, and that they can differ to ... | width <= 50.dp -> 3.dp
width <= 200.dp -> 4.dp
else -> 8.dp
}
}
/**
* Displays a podcast artwork image with rounded corners and optional shadow.
*
* @param uuid Podcast uuid.
* @param modifier The modifier to be applied to the image.
* @param imageSize The display size of the image in ... | @@ -41,6 +41,7 @@ fun PodcastImage(
uuid: String,
modifier: Modifier = Modifier,
imageSize: Dp = 56.dp,
+ imageRequestSize: Dp = imageSize, | modules/services/compose/src/main/java/au/com/shiftyjelly/pocketcasts/compose/components/PodcastImage.kt | 26 | Kotlin | 0.643 | performance | 362 | 51 | 51 | false | Fix podcast page image flickering when animating | 4,857 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
resources.getStringPluralPodcastsSelected(selectedCount)
binding.recyclerView.layoutManager = layoutManager
binding.recyclerView.adapter = adapter
updateSelectButtonText(adapter.selectedPodcasts.size, adapter.list.size)... | The coroutine collecting bottomInset is missing a repeatOnLifecycle wrapper. This can cause memory leaks and unnecessary work when the fragment is not visible. All other similar usages in the codebase (e.g., DiscoverFragment, PodcastFragment, AutoAddSettingsFragment) wrap bottomInset collection with viewLifecycleOwner.... | binding.recyclerView.layoutManager = layoutManager
binding.recyclerView.adapter = adapter
updateSelectButtonText(adapter.selectedPodcasts.size, adapter.list.size)
binding.btnSelect.setOnClickListener {
if (adapter.s... | @@ -155,6 +165,12 @@ class PodcastSelectFragment : BaseFragment() {
this@PodcastSelectFragment.adapter = adapter
}
}
+ launch {
+ val extraPadding = 8.dpToPx(requireContext())
+ settings.bottomInset.colle... | modules/services/views/src/main/java/au/com/shiftyjelly/pocketcasts/views/fragments/PodcastSelectFragment.kt | 26 | Kotlin | 0.643 | performance | 437 | 51 | 51 | false | Fix notifications choose podcasts obscuring the mini player | 4,861 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
output.appendHeader(title = "Episode Download Issues", eol = eol)
try {
val episodes = episodeManager.findEpisodesWhereBlocking("downloaded_error_details IS NOT NULL AND LENGTH(downloaded_error_details) > 0 ORDER BY last_download_attempt_date DESC LIMIT 100")
... | Missing space after comma in the Podcast line. The output format should be consistent with the Episode line above it which has a space after the comma. |
output.appendHeader(title = "Episode Download Issues", eol = eol)
try {
val episodes = episodeManager.findEpisodesWhereBlocking("downloaded_error_details IS NOT NULL AND LENGTH(downloaded_error_details) > 0 ORDER BY last_download_attempt_date DESC LIMIT 100")
... | @@ -419,26 +418,47 @@ class Support @Inject constructor(
Timber.e(e)
}
- output.append("Advance Settings").append(eol).append("-------------------").append(eol).append(eol)
+ output.appendHeader(title = "Advance Settings", eol = eol)
... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/support/Support.kt | 26 | Kotlin | 0.571 | suggestion | 151 | 51 | 51 | false | Improve debug attachment with download attempt time and playback issues | 4,867 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
output.append("Global Audio effects: ")
.append(" Playback speed: ").append(effects.playbackSpeed).append(eol)
.append(" Silence removed: ").append(effects.trimMode.toString().lowercase()).append(eol)
.append(" Volume boost: ").append(if (effec... | Typo in section header title: "Advance Settings" should be "Advanced Settings".
```suggestion
output.appendHeader(title = "Advanced Settings", eol = eol)
``` | output.append("Global Audio effects: ")
.append(" Playback speed: ").append(effects.playbackSpeed).append(eol)
.append(" Silence removed: ").append(effects.trimMode.toString().lowercase()).append(eol)
.append(" Volume boost: ").append(if (effec... | @@ -419,26 +418,47 @@ class Support @Inject constructor(
Timber.e(e)
}
- output.append("Advance Settings").append(eol).append("-------------------").append(eol).append(eol)
+ output.appendHeader(title = "Advance Settings", eol = eol) | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/support/Support.kt | 26 | Kotlin | 0.786 | suggestion | 173 | 51 | 51 | false | Improve debug attachment with download attempt time and playback issues | 4,867 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
}
return output.toString()
}
private fun autoAddToUpNextToString(autoAddToUpNext: Podcast.AutoAddUpNext): String {
return when (autoAddToUpNext) {
Podcast.AutoAddUpNext.OFF -> "off"
Podcast.AutoAddUpNext.PLAY_NEXT -> "to top (play next)"
Podcast.Auto... | The time calculation in the "hours ago" case doesn't account for the singular/plural form. When the result is 1 hour, it will display "1 hours ago" instead of "1 hour ago". Consider using proper pluralization for hours and days similar to how minutes are handled.
```suggestion
minutesAgo < 60 -> {
... | }
return output.toString()
}
private fun autoAddToUpNextToString(autoAddToUpNext: Podcast.AutoAddUpNext): String {
return when (autoAddToUpNext) {
Podcast.AutoAddUpNext.OFF -> "off"
Podcast.AutoAddUpNext.PLAY_NEXT -> "to top (play next)"
Podcast.Auto... | @@ -460,6 +480,20 @@ class Support @Inject constructor(
return if (value) "yes" else "no"
}
+ private fun timeToFriendlyString(timestamp: Long?, dateFormatter: SimpleDateFormat): String {
+ return timestamp?.let {
+ val formattedDate = dateFormatter.format(Date(it))
+ val... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/support/Support.kt | 26 | Kotlin | 1 | suggestion | 883 | 51 | 51 | false | Improve debug attachment with download attempt time and playback issues | 4,867 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
NewOnboardingFlow.startDestination(flow)
} else {
OldOnboardingFlow.startDestination(flow)
}
val isAccountCreationEnabled by produceState<Boolean?>(null) {
value = FeatureFlag.isEnabledWithRemote(Feature.NEW_ONBOARDING_ACCOUNT_CREATION)
}
isAccountCreationEnabled?.let { use... | After waiting for the remote config to load with `isEnabledWithRemote()`, these subsequent calls to `isEnabled()` for the same feature flag could potentially return inconsistent values. While the remote config should now be loaded, it's safer and clearer to use the already-loaded `useNewOnboardingFlow` value instead of... | NewOnboardingFlow.startDestination(flow)
} else {
OldOnboardingFlow.startDestination(flow)
}
val isAccountCreationEnabled by produceState<Boolean?>(null) {
FeatureFlag.awaitProvidersInitialised()
value = FeatureFlag.isEnabled(Feature.NEW_ONBOARDING_ACCOUNT_CREATION)
}
... | @@ -135,64 +137,71 @@ private fun Content(
} else {
OldOnboardingFlow.startDestination(flow)
}
- NavHost(navController, rootDestination) {
- importFlowGraph(theme, navController, flow, onUpdateSystemBars)
- onboardingRecommendationsFlowGraph(
- theme,
- flow =... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/OnboardingFlowComposable.kt | 26 | Kotlin | 0.857 | suggestion | 878 | 51 | 51 | false | Ensure onboarding feature flag is loaded from remote source | 4,882 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
// When installment plan feature is enabled, show installment plan instead of trial/intro offer
if (FeatureFlag.isEnabled(Feature.NEW_INSTALLMENT_PLAN)) {
return plusYearlyPlan()
}
val offer = if (FeatureFlag.isEnabled(Feature.INTRO_PLUS_OFFER_ENABLED)) {... | The function `getYearlyPlanWithFeatureFlag` is being used for both Plus and Patron tiers, but the function implementation only supports installment plans for Plus tier (see line 24 in PaymentExtensions.kt). This means Patron tier will always get the base yearly plan. If this is intentional because installment plans are... | // When installment plan feature is enabled, show installment plan instead of trial/intro offer
if (FeatureFlag.isEnabled(Feature.NEW_INSTALLMENT_PLAN)) {
return plusYearlyPlan()
}
val offer = if (FeatureFlag.isEnabled(Feature.INTRO_PLUS_OFFER_ENABLED)) {... | @@ -305,11 +311,12 @@ sealed class OnboardingUpgradeFeaturesState {
}
private fun plusYearlyPlan(): SubscriptionPlan.Base {
- return subscriptionPlans.getBasePlan(SubscriptionTier.Plus, BillingCycle.Yearly)
+ // Use installment plan when feature flag is enabled
+ ret... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/viewmodel/OnboardingUpgradeFeaturesViewModel.kt | 26 | Kotlin | 0.857 | suggestion | 543 | 38 | 38 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
}
PricePerPeriod.PRICE_PER_WEEK -> {
val currencyCode = recurringPrice.currencyCode
if (currencyCode == "USD") {
stringResource(LR.string.price_per_week_usd, pricePerWeek)
} else {
stringResource(LR.string.p... | The hardcoded value "12" should use `monthsInYear.toInt()` for consistency with the rest of the codebase (see line 308 where `monthsInYear` is defined and line 318 where it's used for calculations).
```suggestion
return stringResource(LR.string.price_per_month_for_months, formattedPrice, monthsInYear.toInt())
`... | stringResource(LR.string.price_per_month, pricePerMonth, currencyCode)
}
}
PricePerPeriod.PRICE_PER_WEEK -> {
val currencyCode = recurringPrice.currencyCode
if (currencyCode == "USD") {
stringResource(LR.str... | @@ -334,6 +361,11 @@ private fun SubscriptionPlan.savingsPercent(otherPlan: SubscriptionPlan) = 100 -
private fun SubscriptionPlan.price(): String {
val formattedPrice = recurringPrice.formattedPrice
+ // For installment plans, show price per month with duration
+ if (this is SubscriptionPlan.Base && isIn... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 0.857 | suggestion | 322 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
private val SubscriptionPlan.pricePerMonth: Float
get() {
val pricePerMonth = when (billingCycle) {
BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val Subscript... | The `isInstallmentPlan` property is a new detection mechanism for installment plans that directly affects business logic in multiple places (pricing display, savings calculation). This logic should be covered by unit tests to ensure it correctly identifies installment plans and distinguish them from regular yearly plan... |
private val SubscriptionPlan.pricePerMonth: Float
get() {
val pricePerMonth = when (billingCycle) {
BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val Subscript... | @@ -300,8 +308,27 @@ private val SubscriptionPlan.pricePerWeek: Float
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
+// Extension property to detect installment plans
+private val SubscriptionPlan.Base.isInstallmentPlan: Boolean
+ get() = billingCycle == BillingCycle.Ye... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 0.643 | suggestion | 322 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val SubscriptionPlan.pricePerWeek: Float
get() {
val pricePerWeek = when (billingCycle) {
BillingCycle... | The `totalYearlyPrice` calculation multiplies recurring price by months in year and is used for displaying yearly cost of installment plans. This calculation should be covered by unit tests to verify the multiplication logic and float conversion produce correct results for various price values. | BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val SubscriptionPlan.pricePerWeek: Float
get() {
val pricePerWeek = when (billingCycle) {
BillingCycle... | @@ -300,8 +308,27 @@ private val SubscriptionPlan.pricePerWeek: Float
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
+// Extension property to detect installment plans
+private val SubscriptionPlan.Base.isInstallmentPlan: Boolean
+ get() = billingCycle == BillingCycle.Ye... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 0.643 | suggestion | 295 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
private val SubscriptionPlan.pricePerMonth: Float
get() {
val pricePerMonth = when (billingCycle) {
BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val Subscript... | Consider using the existing `isInstallment` property instead of this heuristic. The `SubscriptionPlan.Base` class already has an `isInstallment` property (based on `installmentPlanDetails != null`) which is the canonical way to determine if a plan is an installment plan. Using the heuristic of checking if billingCycle ... |
private val SubscriptionPlan.pricePerMonth: Float
get() {
val pricePerMonth = when (billingCycle) {
BillingCycle.Monthly -> recurringPrice.amount
BillingCycle.Yearly -> recurringPrice.amount / monthsInYear
}
return pricePerMonth.toFloat()
}
private val Subscript... | @@ -300,8 +308,27 @@ private val SubscriptionPlan.pricePerWeek: Float
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
+// Extension property to detect installment plans
+private val SubscriptionPlan.Base.isInstallmentPlan: Boolean
+ get() = billingCycle == BillingCycle.Ye... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 1 | suggestion | 635 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
} / weeksInYear
return pricePerWeek.toFloat()
}
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
// Extension property to detect installment plans
private val SubscriptionPlan.Base.isInstallmentPlan: Boolean
get() = billingCycle == BillingCycle.Yearly &&... | The string resources `plus_per_year_usd` and `plus_per_year_amount` use Float formatting (`%1$.2f`) which could lead to precision issues with currency calculations. Consider using the already-formatted `formattedPrice` from `recurringPrice` like the other price displays do, or ensure the totalYearlyPrice calculation ma... | } / weeksInYear
return pricePerWeek.toFloat()
}
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
private fun SubscriptionPlan.Base.formattedTotalYearlyPrice(): String {
val totalAmount = recurringPrice.amount * monthsInYear
val currencyCode = recurri... | @@ -300,8 +308,27 @@ private val SubscriptionPlan.pricePerWeek: Float
private val monthsInYear = 12.toBigDecimal()
private val weeksInYear = 52.toBigDecimal()
+// Extension property to detect installment plans
+private val SubscriptionPlan.Base.isInstallmentPlan: Boolean
+ get() = billingCycle == BillingCycle.Ye... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 0.643 | suggestion | 496 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.gr... | This import is unused. The PricingSchedule class is not referenced anywhere in the file and should be removed.
```suggestion
``` | import androidx.compose.material.MaterialTheme
import androidx.compose.material.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.gr... | @@ -44,9 +44,12 @@ import au.com.shiftyjelly.pocketcasts.compose.components.TextP40
import au.com.shiftyjelly.pocketcasts.compose.preview.ThemePreviewParameterProvider
import au.com.shiftyjelly.pocketcasts.compose.theme
import au.com.shiftyjelly.pocketcasts.payment.BillingCycle
+import au.com.shiftyjelly.pocketcasts... | modules/features/account/src/main/java/au/com/shiftyjelly/pocketcasts/account/onboarding/components/SubscriptionPlanRow.kt | 26 | Kotlin | 0.786 | suggestion | 129 | 51 | 51 | false | [Installments] Update upgrade screen | 4,889 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import au.com.shiftyjelly.pocketcasts.models.entity.Transcript
import kotlinx.coroutines.flow.Flow
@Dao
abstract class TranscriptDao {
@Query("DELETE FROM episode_transcript WHERE episode... | There is duplication between the new public method `deleteForEpisodes` and the existing protected method `deleteAll` on line 14. Both methods have identical signatures and SQL queries. Consider refactoring by making the protected `deleteAll` method call the new public `deleteForEpisodes` method to eliminate this duplic... | import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import au.com.shiftyjelly.pocketcasts.models.db.AppDatabase
import au.com.shiftyjelly.pocketcasts.models.entity.Transcript
import kotlinx.coroutines.flow.Flow
@Dao
abstract class TranscriptDa... | @@ -22,6 +22,12 @@ abstract class TranscriptDao {
insertAll(transcripts)
}
+ @Query("DELETE FROM episode_transcript WHERE episode_uuid = :episodeUuid")
+ abstract suspend fun deleteForEpisode(episodeUuid: String)
+
+ @Query("DELETE FROM episode_transcript WHERE episode_uuid IN (:episodeUuids)")... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/TranscriptDao.kt | 26 | Kotlin | 0.643 | refactor | 414 | 31 | 36 | false | Remove orphaned transcripts when downloaded episode is deleted | 4,903 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
// if the episode is currently downloading, kill the download
downloadManager.removeEpisodeFromQueue(episode, "file deleted")
cleanUpDownloadFiles(episode)
if (updateDatabase) {
updateDownloadTaskId(episode, null)
updateEpisodeStatus(episode, EpisodeStatusEnum.N... | Using runBlocking inside a function that is called from suspend contexts is an anti-pattern. The cleanUpDownloadFiles function is called from deleteEpisodeFile, which is a suspend function. When called from a coroutine, runBlocking blocks the underlying thread, defeating the purpose of coroutines. Consider making clean... | // if the episode is currently downloading, kill the download
downloadManager.removeEpisodeFromQueue(episode, "file deleted")
cleanUpDownloadFiles(episode)
if (updateDatabase) {
updateDownloadTaskId(episode, null)
updateEpisodeStatus(episode, EpisodeStatusEnum.N... | @@ -580,6 +581,11 @@ class EpisodeManagerImpl @Inject constructor(
// remove the temp file as well in case it's there
val tempFilePath = DownloadHelper.tempPathForEpisode(episode, fileStorage)
FileUtil.deleteFileByPath(tempFilePath)
+
+ // remove associated transcripts
+ runBloc... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/podcast/EpisodeManagerImpl.kt | 26 | Kotlin | 0.643 | suggestion | 427 | 51 | 51 | false | Remove orphaned transcripts when downloaded episode is deleted | 4,903 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
),
)
}
val products = googleProducts.map(mapper::toProduct)
assertTrue(products.all { it == null })
listener.assertMessages(
"Missing billing period duration designator in {basePlanId=Base plan ID, productId=Product ID, rawDuration=1M}",
... | ℹ️ Often it is good to use a value different from `0` when testing. `0` is sometimes used as a default value in different APIs so having something else in a test guards against that. | ),
)
}
val products = googleProducts.map(mapper::toProduct)
assertTrue(products.all { it == null })
listener.assertMessages(
"Missing billing period duration designator in {basePlanId=Base plan ID, productId=Product ID, rawDuration=1M}",
... | @@ -400,6 +400,38 @@ class BillingPaymentMapperTest {
)
}
+ @Test
+ fun `map product with installment plan details`() {
+ val googleProduct = createGoogleProductDetails(
+ subscriptionOfferDetails = listOf(
+ createGoogleOfferDetails(
+ offerId =... | modules/services/payment/src/test/kotlin/au/com/shiftyjelly/pocketcasts/payment/billing/BillingPaymentMapperTest.kt | 26 | Kotlin | 0.571 | suggestion | 182 | 51 | 51 | false | [Installments] Introduce installments to our models | 4,907 | Automattic/pocket-casts-android | 1,688 | Kotlin | MiSikora | sztomek |
interface Service {
@GET("/")
suspend fun call()
}
@Test
fun `call factory is not executed on the calling thread`() = runBlocking {
val mainThread = Thread.currentThread()
val calledOnMain = AtomicBoolean(true) // Setting to true to avoid false positive in the assertion... | The test has a resource leak - the executor is shutdown but not awaited for termination. This could cause the test to complete before the executor finishes its work, leading to unreliable test results. Consider using `awaitTermination` after `shutdown()` to ensure the background task completes before the assertion. | import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.create
import retrofit2.http.GET
import okhttp3.Call as OkHttpCall
class ExecutorEnqueueAdapterFactoryTest {
@get:Rule
val server = MockWebServer()
private val factoryExecutor = Executors.newSingleThreadExecutor()
interface Service ... | @@ -0,0 +1,49 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.runBlocking
+import okhttp3.OkHttpClient
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 26 | Kotlin | 0.786 | suggestion | 316 | 31 | 51 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
val responseType = getParameterUpperBound(0, returnType)
return ExecutorEnqueueAdapter<Any>(executor, retrofit.callbackExecutor(), responseType)
}
}
private class ExecutorEnqueueAdapter<T>(
private val executor: Executor,
private val callbackExecutor: Executor?,
private val responseType... | There is a race condition between cancel and enqueue. If `cancel()` is called right before `enqueue()` but before the executor runs the task, `isCancelled` could be set to true. However, the executor.execute lambda might not run immediately, allowing a window where `isExecuted` is true but the cancel handling hasn't ha... | return ExecutorEnqueueAdapter<Any>(executor, responseType)
}
}
private class ExecutorEnqueueAdapter<T>(
private val executor: Executor,
private val responseType: Type,
) : CallAdapter<T, Call<T>> {
override fun responseType(): Type = responseType
override fun adapt(call: Call<T>): Call<T> ... | @@ -0,0 +1,101 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.lang.reflect.ParameterizedType
+import java.lang.reflect.Type
+import java.util.concurrent.Executor
+import java.util.concurrent.atomic.AtomicBoolean
+import okhttp3.Request
+import okio.Timeout
+import... | modules/services/servers/src/main/java/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactory.kt | 26 | Kotlin | 0.786 | bug | 598 | 51 | 48 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
require(returnType is ParameterizedType) {
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>"
}
val responseType = getParameterUpperBound(0, returnType)
return ExecutorEnqueueAdapter<Any>(executor, retrofit.callbackExecutor(), responseType)
}
}
... | The variable name `isCancelled` uses British spelling while the method name `isCanceled()` uses American spelling (matching the Retrofit API). For consistency within the class, consider renaming the variable to `isCanceled` to match the method name and the IOException message "Canceled". | "Call return type must be parameterized as Call<Foo> or Call<? extends Foo>"
}
val responseType = getParameterUpperBound(0, returnType)
return ExecutorEnqueueAdapter<Any>(executor, responseType)
}
}
private class ExecutorEnqueueAdapter<T>(
private val executor: Executor,
... | @@ -0,0 +1,101 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.lang.reflect.ParameterizedType
+import java.lang.reflect.Type
+import java.util.concurrent.Executor
+import java.util.concurrent.atomic.AtomicBoolean
+import okhttp3.Request
+import okio.Timeout
+import... | modules/services/servers/src/main/java/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactory.kt | 26 | Kotlin | 0.786 | suggestion | 288 | 51 | 51 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
imp... | The imports `kotlinx.coroutines.launch` and `kotlinx.coroutines.yield` are unused and should be removed.
```suggestion
import kotlinx.coroutines.runBlocking
``` | package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockRespons... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 9 | Kotlin | 0.786 | suggestion | 160 | 34 | 34 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
imp... | The import `org.junit.Assert` is unused since specific assertions are already imported individually. This import should be removed.
```suggestion
``` | package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockRespons... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 13 | Kotlin | 0.786 | suggestion | 150 | 38 | 38 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
fun regularCall(): Call<Void>
}
@Test
fun `call factory is not executed on the calling thread when enqueueing call`() = runBlocking {
val mainThread = Thread.currentThread()
val calledOnMain = AtomicBoolean(true) // Setting to true to avoid false positive in the assertion
va... | The test calls `service.coroutineCall()` which is a suspend function. However, this doesn't actually test the `ExecutorEnqueueAdapterFactory` because Kotlin coroutines in Retrofit use a different call adapter mechanism. The factory being tested only applies to methods that return `Call<T>`. This test should use `servic... | fun regularCall(): Call<Void>
}
@After
fun tearDown() {
factoryExecutor.shutdown()
}
@Test
fun `call factory is not executed on the calling thread when enqueueing call`() = runBlocking {
val mainThread = Thread.currentThread()
val calledOnMain = AtomicBoolean(tr... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 26 | Kotlin | 1 | bug | 899 | 51 | 51 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
imp... | The executor created in this test is never shut down, which can lead to resource leaks in the test suite. Consider shutting down the executor after the test completes, preferably using a try-finally block or `@After` method.
```suggestion
val executor = Executors.newSingleThreadExecutor()
try {
... | .addCallAdapterFactory(ExecutorEnqueueAdapterFactory(factoryExecutor))
.build()
.create<Service>()
server.enqueue(MockResponse())
val response = service.regularCall().execute()
assertTrue(response.isSuccessful)
}
@Test
fun `call can be cloned`()... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 26 | Kotlin | 1 | bug | 2,388 | 124 | 29 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
imp... | The executor created in this test is never shut down, which can lead to resource leaks in the test suite. Consider shutting down the executor after the test completes, preferably using a try-finally block or `@After` method.
```suggestion
val executor = Executors.newSingleThreadExecutor()
try {
... | .addCallAdapterFactory(ExecutorEnqueueAdapterFactory(factoryExecutor))
.build()
.create<Service>()
server.enqueue(MockResponse())
val response = service.regularCall().execute()
assertTrue(response.isSuccessful)
}
@Test
fun `call can be cloned`()... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 26 | Kotlin | 1 | bug | 2,391 | 124 | 29 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.servers.adapters
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
imp... | The executor created in this test is never shut down, which can lead to resource leaks in the test suite. Consider shutting down the executor after the test completes, preferably using a try-finally block or `@After` method.
```suggestion
val executor = Executors.newSingleThreadExecutor()
try {
... | .addCallAdapterFactory(ExecutorEnqueueAdapterFactory(factoryExecutor))
.build()
.create<Service>()
server.enqueue(MockResponse())
val response = service.regularCall().execute()
assertTrue(response.isSuccessful)
}
@Test
fun `call can be cloned`()... | @@ -0,0 +1,123 @@
+package au.com.shiftyjelly.pocketcasts.servers.adapters
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import k... | modules/services/servers/src/test/kotlin/au/com/shiftyjelly/pocketcasts/servers/adapters/ExecutorEnqueueAdapterFactoryTest.kt | 26 | Kotlin | 1 | bug | 2,400 | 124 | 29 | false | Dispatch Retrofit enqueued calls on a background thread | 4,909 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
}
buildFeatures {
buildConfig = true
viewBinding = true
compose = true
}
buildTypes {
named("debug") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher_radioactive"
}
named("debugProd") {
manifestPlaceholders["appIcon"] = "... | `println(...)` in Gradle scripts is noisy and bypasses Gradle’s logging levels. Prefer `logger.warn(...)` (or `project.logger.warn(...)`) so warnings can be filtered and show up consistently in CI output.
```suggestion
logger.warn("WARNING: Sentry configuration not found. The ProGuard mapping files won'... | defaultConfig {
minSdk = project.property("minSdkVersionAutomotive") as Int
targetSdk = project.property("targetSdkVersionAutomotive") as Int
applicationId = project.property("applicationId").toString()
}
buildFeatures {
buildConfig = true
viewBinding = true
... | @@ -35,6 +39,10 @@ android {
named("release") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher"
+
+ if (project.findProperty("sentryAutomotiveProject")?.toString().isNullOrBlank()) {
+ println("WARNING: Sentry configuration not found. The ProGuard mapping files ... | automotive/build.gradle.kts | 26 | Kotlin | 0.857 | suggestion | 340 | 51 | 51 | false | Use per-project Sentry configuration (#4818) | 4,912 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
viewBinding = true
compose = true
}
buildTypes {
named("debug") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher_radioactive"
}
named("debugProd") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher_3"
}
maybeCreate(... | `println(...)` in Gradle scripts is noisy and bypasses Gradle’s logging levels. Prefer `logger.warn(...)` (or `project.logger.warn(...)`) so warnings can be filtered and show up consistently in CI output.
```suggestion
project.logger.warn("Sentry configuration not found. The ProGuard mapping files won't... | }
buildFeatures {
buildConfig = true
viewBinding = true
compose = true
}
buildTypes {
named("debug") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher_radioactive"
}
named("debugProd") {
manifestPlaceholders["appIcon"] = "... | @@ -46,8 +50,8 @@ android {
named("release") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher"
- if (!file("${project.rootDir}/sentry.properties").exists()) {
- println("WARNING: Sentry configuration file 'sentry.properties' not found. The ProGuard mapping files... | app/build.gradle.kts | 26 | Kotlin | 0.857 | suggestion | 339 | 51 | 51 | false | Use per-project Sentry configuration (#4818) | 4,912 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
namespace = "au.com.shiftyjelly.pocketcasts"
defaultConfig {
minSdk = project.property("minSdkVersionWear") as Int
targetSdk = project.property("targetSdkVersionWear") as Int
applicationId = project.property("applicationId").toString()
}
buildTypes {
named("debug") {
... | `println(...)` in Gradle scripts is noisy and bypasses Gradle’s logging levels. Prefer `logger.warn(...)` (or `project.logger.warn(...)`) so warnings can be filtered and show up consistently in CI output.
```suggestion
project.logger.warn("WARNING: Sentry configuration not found. The ProGuard mapping fi... | projectName = project.findProperty("sentryWearProject")?.toString()
}
android {
namespace = "au.com.shiftyjelly.pocketcasts"
defaultConfig {
minSdk = project.property("minSdkVersionWear") as Int
targetSdk = project.property("targetSdkVersionWear") as Int
applicationId = project.pro... | @@ -32,8 +36,8 @@ android {
named("release") {
manifestPlaceholders["appIcon"] = "@mipmap/ic_launcher"
- if (!file("${project.rootDir}/sentry.properties").exists()) {
- println("WARNING: Sentry configuration file 'sentry.properties' not found. The ProGuard mapping files... | wear/build.gradle.kts | 26 | Kotlin | 0.857 | suggestion | 348 | 51 | 51 | false | Use per-project Sentry configuration (#4818) | 4,912 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
@Test
fun `plans have correct recurring price`() {
val plans = SubscriptionPlans.create(products).getOrNull()!!
val basePlans = SubscriptionTier.entries.flatMap { tier ->
BillingCycle.entries.map { billingCycle ->
plans.getBasePlan(tier, billingCycle)
}
... | Debug println statement should be removed before merging. This appears to be leftover debugging code that should not be committed.
```suggestion
val plan = plans.findInstallmentPlan(SubscriptionTier.Plus, BillingCycle.Yearly).getOrNull()!!
``` |
@Test
fun `plans have correct recurring price`() {
val plans = SubscriptionPlans.create(products).getOrNull()!!
val basePlans = SubscriptionTier.entries.flatMap { tier ->
BillingCycle.entries.map { billingCycle ->
plans.getBasePlan(tier, billingCycle)
}
... | @@ -404,7 +404,7 @@ class SubscriptionPlansTest {
fun `find plus yearly installment plan`() {
val plans = SubscriptionPlans.create(products).getOrNull()!!
- val plan = plans.findInstallmentPlan(SubscriptionTier.Plus, BillingCycle.Yearly).getOrNull()!!
+ val plan = plans.findInstallmentPlan... | modules/services/payment/src/test/kotlin/au/com/shiftyjelly/pocketcasts/payment/SubscriptionPlansTest.kt | 26 | Kotlin | 1 | bug | 251 | 51 | 51 | false | Make payments code safer | 4,920 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
@JvmInline
value class Recurring(
val value: Int,
) : RecurrenceMode
data object Infinite : RecurrenceMode
}
}
data class InstallmentPlanDetails(
val commitmentPaymentsCount: Int,
val subsequentCommitmentPaymentsCount: Int,
)
@ConsistentCopyVisibility
data clas... | The requireNotNull lambda should return a message string, not throw an AssertionError. The current code will throw an IllegalArgumentException from requireNotNull (not AssertionError) when the value is null. Change to: requireNotNull(basePlans.getValue(key).getOrNull()) with a message string as the lambda parameter.
``... | @JvmInline
value class Recurring(
val value: Int,
) : RecurrenceMode
data object Infinite : RecurrenceMode
}
}
data class InstallmentPlanDetails(
val commitmentPaymentsCount: Int,
val subsequentCommitmentPaymentsCount: Int,
)
@ConsistentCopyVisibility
data clas... | @@ -77,25 +77,25 @@ data class InstallmentPlanDetails(
@ConsistentCopyVisibility
data class SubscriptionPlans private constructor(
- private val plans: Map<SubscriptionPlan.Key, PaymentResult<SubscriptionPlan>>,
+ private val basePlans: Map<SubscriptionPlan.Key, PaymentResult<SubscriptionPlan.Base>>,
+ pri... | modules/services/payment/src/main/kotlin/au/com/shiftyjelly/pocketcasts/payment/Data.kt | 26 | Kotlin | 1 | suggestion | 421 | 51 | 51 | false | Make payments code safer | 4,920 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
value class Recurring(
val value: Int,
) : RecurrenceMode
data object Infinite : RecurrenceMode
}
}
data class InstallmentPlanDetails(
val commitmentPaymentsCount: Int,
val subsequentCommitmentPaymentsCount: Int,
)
@ConsistentCopyVisibility
data class SubscriptionPlans... | The lambda passed to requireNotNull should return the error message string, not throw an exception. The current implementation will throw an AssertionError before requireNotNull can throw its IllegalArgumentException. Change line 89 to just return the message string without the throw statement. | value class Recurring(
val value: Int,
) : RecurrenceMode
data object Infinite : RecurrenceMode
}
}
data class InstallmentPlanDetails(
val commitmentPaymentsCount: Int,
val subsequentCommitmentPaymentsCount: Int,
)
@ConsistentCopyVisibility
data class SubscriptionPlans... | @@ -77,25 +77,25 @@ data class InstallmentPlanDetails(
@ConsistentCopyVisibility
data class SubscriptionPlans private constructor(
- private val plans: Map<SubscriptionPlan.Key, PaymentResult<SubscriptionPlan>>,
+ private val basePlans: Map<SubscriptionPlan.Key, PaymentResult<SubscriptionPlan.Base>>,
+ pri... | modules/services/payment/src/main/kotlin/au/com/shiftyjelly/pocketcasts/payment/Data.kt | 26 | Kotlin | 0.643 | suggestion | 295 | 51 | 51 | false | Make payments code safer | 4,920 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
binding?.btnArchive?.let { button ->
button.onStateChange = {
viewModel.archiveClicked(button.isOn)
if (button.isOn) {
(parentFragment as? BaseDialogFragment)?.dismiss()
}
}
}
binding?.btnPlayed?.let { ... | Using `setOnClickListener` on a ToggleActionButton overrides its internal toggle behavior defined in the init block. While this works because the button is configured with identical On and Off states (line 551), consider whether a simpler button widget would be more appropriate here since no actual toggling is needed. ... |
binding?.btnArchive?.let { button ->
button.onStateChange = {
viewModel.archiveClicked(button.isOn)
if (button.isOn) {
(parentFragment as? BaseDialogFragment)?.dismiss()
}
}
}
binding?.btnPlayed?.let { ... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 0.786 | suggestion | 426 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
}
}
binding?.btnArchive?.let { button ->
button.onStateChange = {
viewModel.archiveClicked(button.isOn)
if (button.isOn) {
(parentFragment as? BaseDialogFragment)?.dismiss()
}
}
}
bi... | The local variable `podcastUuid` shadows the property defined at line 174. While this appears intentional to capture state from the LiveData observer, consider renaming the local variable (e.g., to `currentPodcastUuid`) to avoid confusion and make the intent clearer.
```suggestion
var currentPodcastUuid: String... | }
}
binding?.btnArchive?.let { button ->
button.onStateChange = {
viewModel.archiveClicked(button.isOn)
if (button.isOn) {
(parentFragment as? BaseDialogFragment)?.dismiss()
}
}
}
bi... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 1 | suggestion | 671 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
defaultViewModelCreationExtras.withCreationCallback<ChaptersViewModel.Factory> { factory ->
factory.create(Episode(episodeUUID))
}
},
)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
if (!forceDarkTheme || theme.isDarkTheme) {
... | Creating a CoordinatorLayout and adding it to the root view seems unusual. The CoordinatorLayout is empty and only serves as a snackbar anchor. Consider whether this is the right approach, or if the snackbar should anchor to an existing view. Additionally, creating the CoordinatorLayout with a ContextThemeWrapper in on... | private val chaptersViewModel by viewModels<ChaptersViewModel>(
extrasProducer = {
defaultViewModelCreationExtras.withCreationCallback<ChaptersViewModel.Factory> { factory ->
factory.create(Episode(episodeUUID))
}
},
)
override fun onCreateDialog(save... | @@ -156,6 +158,9 @@ class EpisodeContainerFragment :
savedInstanceState: Bundle?,
): View? {
binding = FragmentEpisodeContainerBinding.inflate(inflater, container, false)
+ snackBarView = CoordinatorLayout(ContextThemeWrapper(context, activeTheme.resourceId)).also {
+ binding?.r... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeContainerFragment.kt | 26 | Kotlin | 0.5 | suggestion | 506 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp, top = 16.dp),
) {
... | The ToggleActionButton is being misused here. The button is set up with identical On and Off states (same icon and text), and then setOnClickListener overrides the default toggle behavior. Since this is no longer a toggle button but a regular action button that opens a dialog, consider using a simpler button widget or ... | binding?.btnDownload?.setOnClickListener {
val episode = viewModel.episode ?: return@setOnClickListener
if (episode.isDownloaded) {
val dialog = OptionsDialog()
.setTitle(getString(LR.string.podcast_remove_downloaded_file))
.addText... | @@ -506,7 +548,7 @@ class EpisodeFragment : BaseFragment() {
}
}
- binding?.btnAddToUpNext?.setup(ToggleActionButton.State.On(LR.string.podcasts_up_next, IR.drawable.ic_upnext_remove), ToggleActionButton.State.Off(LR.string.podcasts_up_next, IR.drawable.ic_upnext_playnext), false)
+ ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 1 | bug | 757 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
viewModel.markAsPlayedClicked(button.isOn)
}
}
// Up Next
binding?.btnAddToUpNext?.setOnClickListener { _ ->
val binding = binding ?: return@setOnClickListener
if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
... | The requireNotNull call will throw a NullPointerException if listener is null, which could happen if the fragment is not properly attached. Consider using a safer approach like 'listener?.snackBarView() ?: view?.rootView' or checking listener earlier in the click handler. | }
}
binding?.btnPlayed?.let { button ->
button.onStateChange = {
viewModel.markAsPlayedClicked(button.isOn)
}
}
// Up Next
var podcastTint = ThemeColor.podcastIcon02(activeTheme, 0xFF000000.toInt())
var loadedPodcastUu... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 0.643 | suggestion | 272 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
val dialog = OptionsDialog()
.setIconColor(tintColor)
.addCheckedOption(LR.string.play_next, imageId = IR.drawable.ic_upnext_playnext, click = { viewModel.addToUpNext(binding.btnAddToUpNext.isOn) })
.addCheckedOption(LR.string.play_last, imageI... | The requireNotNull call will throw a NullPointerException if listener is null, which could happen if the fragment is not properly attached. Consider using a safer approach like 'listener?.snackBarView() ?: view?.rootView' or checking listener earlier in the click handler. | // Up Next
var podcastTint = ThemeColor.podcastIcon02(activeTheme, 0xFF000000.toInt())
var loadedPodcastUuid: String? = null
viewModel.state.observe(viewLifecycleOwner) { state ->
val loadedState = state as? EpisodeFragmentState.Loaded
val stateTint = loadedState?... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 0.643 | suggestion | 272 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
activity?.let { activity ->
val text = if (wasAdded) LR.string.episode_added_to_up_next else LR.string.episode_removed_from_up_next
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
}
}
}
viewModel.inUpNext.obser... | The requireNotNull call will throw a NullPointerException if listener is null, which could happen if the fragment is not properly attached. Consider using a safer approach like 'listener?.snackBarView() ?: view?.rootView' or checking listener earlier in the click handler. | binding?.btnAddEpisode?.setOnClickListener { _ ->
val dialog = OptionsDialog().setIconColor(podcastTint)
when {
viewModel.isEpisodeInUpNext() -> {
dialog.addCheckedOption(LR.string.remove_from_up_next, imageId = IR.drawable.ic_upnext_remove) {
... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 0.643 | suggestion | 272 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
viewModel.inUpNext.observe(viewLifecycleOwner) { isInUpNext ->
// Up Next
binding?.btnAddToUpNext?.isOn = isInUpNext
}
viewModel.isPlaying.observe(viewLifecycleOwner) { isPlaying ->
binding?.btnPlay?.setPlaying(isPlaying = isPlaying, animate = true)
}... | The requireNotNull call will throw a NullPointerException if listener is null, which could happen if the fragment is not properly attached. Consider using a safer approach like 'listener?.snackBarView() ?: view?.rootView' or checking listener earlier in the click handler. | Snackbar
.make(requireNotNull(listener).snackBarView(), LR.string.episode_removed_from_up_next, Snackbar.LENGTH_LONG)
.show()
}
}
viewModel.isUpNextEmpty() -> {
dialog... | @@ -453,28 +458,65 @@ class EpisodeFragment : BaseFragment() {
}
// Up Next
- binding?.btnAddToUpNext?.setOnClickListener { _ ->
- val binding = binding ?: return@setOnClickListener
- if (!binding.btnAddToUpNext.isOn && viewModel.shouldShowUpNextDialog()) {
- ... | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/episode/EpisodeFragment.kt | 26 | Kotlin | 0.643 | suggestion | 272 | 51 | 51 | false | Add playlist from episode details | 4,923 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
searchTerm = searchTerm.orEmpty(),
)
}
override fun notAddedManualEpisodesFlow(playlistUuid: String, podcastUuid: String, searchTerm: String?): Flow<List<PodcastEpisode>> {
return playlistDao
.notAddedManualEpisodesFlow(
playlistUuid = playlistUuid,
... | When adding episodes in bulk, the limit check uses `existingEpisodeUuids.size + newEpisodeUuids.size` where `newEpisodeUuids` is derived directly from the input list, so duplicates in `episodeUuids` or entries for which no `PodcastEpisode` exists can cause the method to return `false` for exceeding `manualEpisodeLimit`... | searchTerm = searchTerm.orEmpty(),
)
}
override fun notAddedManualEpisodesFlow(playlistUuid: String, podcastUuid: String, searchTerm: String?): Flow<List<PodcastEpisode>> {
return playlistDao
.notAddedManualEpisodesFlow(
playlistUuid = playlistUuid,
... | @@ -401,40 +401,48 @@ class PlaylistManagerImpl(
.distinctUntilChanged()
}
- override suspend fun addManualEpisode(playlistUuid: String, episodeUuid: String): Boolean {
- return appDatabase.withTransaction {
- val episodes = playlistDao.getManualPlaylistEpisodes(playlistUuid)
- ... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerImpl.kt | 26 | Kotlin | 0.786 | refactor | 663 | 51 | 51 | false | Allow to add episodes to a playlist in bulk | 4,926 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
import au.com.shiftyjelly.pocketcasts.models.entity.PodcastEpisode
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistEpisode
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistEpisodeMetadata
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistPreviewForEpisode
import au.com.shiftyjelly.pocketcasts.model... | Unused import: `timber.log.Timber` is not used anywhere in this DAO (verified via search). Please remove it.
```suggestion
``` | import au.com.shiftyjelly.pocketcasts.models.entity.PodcastEpisode
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistEpisode
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistEpisodeMetadata
import au.com.shiftyjelly.pocketcasts.models.to.PlaylistPreviewForEpisode
import au.com.shiftyjelly.pocketcasts.model... | @@ -31,8 +31,16 @@ import au.com.shiftyjelly.pocketcasts.models.type.SmartRules
import au.com.shiftyjelly.pocketcasts.utils.extensions.escapeLike
import au.com.shiftyjelly.pocketcasts.utils.extensions.unidecode
import java.time.Clock
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flo... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/PlaylistDao.kt | 26 | Kotlin | 0.786 | suggestion | 127 | 51 | 51 | false | Refactor episode add page to handle multiple episodes | 4,927 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
deleted IS 0
AND playlist.manual IS NOT 0
AND (
-- trim isn't really needed because we trim in the application logic but it helps with tests
TRIM(:searchTerm) IS ''
OR playlist.clean_title LIKE '%' || :searchTerm || '%' ESCAPE '\'
)
OR... | `playlistPreviewsForEpisodeFlow` now issues one `playlistEpisodeUuids(...)` query per playlist and combines them. This creates an N+1 query pattern that can be expensive if the user has many manual playlists (more DB observers, more invalidations, more work on each change). Consider replacing this with a single query (... | -- trim isn't really needed because we trim in the application logic but it helps with tests
TRIM(:searchTerm) IS ''
OR playlist.clean_title LIKE '%' || :searchTerm || '%' ESCAPE '\'
)
ORDER BY
sortPosition ASC
""",
)
protected abstract fun al... | @@ -102,11 +89,32 @@ abstract class PlaylistDao {
sortPosition ASC
""",
)
- protected abstract fun playlistPreviewsForEpisodeFlowUnsafe(episodeUuid: String, searchTerm: String): Flow<List<PlaylistPreviewForEpisode>>
+ protected abstract fun allManualPlaylistsFlow(searchTerm: String): Flow<Lis... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/PlaylistDao.kt | 26 | Kotlin | 0.643 | performance | 468 | 51 | 51 | false | Refactor episode add page to handle multiple episodes | 4,927 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
// temporary variables
@Ignore
override var playing: Boolean = false
val playedPercentage: Int
get() {
return if (isFinished) {
100
} else {
((playedUpTo / duration) * 100).toInt()
}
}
val isUnplayed: Boolean
... | Naming: `val uuids` returns a single `EpisodeUuids` value (episodeUuid + podcastUuid). With the current naming this reads as a collection even though it isn’t. Consider renaming this property to something singular/explicit (e.g., `uuidPair`/`episodeAndPodcastUuids`) and/or add an explicit type to make its intent cleare... | // temporary variables
@Ignore
override var playing: Boolean = false
val playedPercentage: Int
get() {
return if (isFinished) {
100
} else {
((playedUpTo / duration) * 100).toInt()
}
}
val isUnplayed: Boolean
... | @@ -167,6 +168,11 @@ data class PodcastEpisode(
val lastPlaybackInteractionDate: Date?
get() = lastPlaybackInteraction?.let { Date(it) }
+ val uuids get() = EpisodeUuids(
+ episodeUuid = uuid,
+ podcastUuid = podcastUuid,
+ ) | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/entity/PodcastEpisode.kt | 26 | Kotlin | 1 | suggestion | 479 | 40 | 40 | false | Refactor episode add page to handle multiple episodes | 4,927 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.SYNC_STATUS_NOT_SYNCED
import au.com.shiftyjelly.pocketcasts.models.entity.Podcast
import au.com.shiftyjelly.pocketcasts.models.entity.PodcastEpisode
import au.com.shiftyjelly.... | Unused imports: `emitAll` and `flow` are not referenced anywhere in this file (verified via search). Please remove them to keep Spotless/ktlint clean.
```suggestion
import kotlinx.coroutines.flow.flatMapLatest
``` | import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.SYNC_STATUS_NOT_SYNCED
import au.com.shiftyjelly.pocketcasts.models.entity.Podcast
import au.com.shiftyjelly.pocketcasts.models.entity.PodcastEpisode
import au.com.shiftyjelly.... | @@ -31,8 +31,16 @@ import au.com.shiftyjelly.pocketcasts.models.type.SmartRules
import au.com.shiftyjelly.pocketcasts.utils.extensions.escapeLike
import au.com.shiftyjelly.pocketcasts.utils.extensions.unidecode
import java.time.Clock
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flo... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/PlaylistDao.kt | 26 | Kotlin | 0.857 | suggestion | 213 | 51 | 51 | false | Refactor episode add page to handle multiple episodes | 4,927 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
plugins.withType<LibraryPlugin>().configureEach {
configure<LibraryExtension> {
buildTypes {
named("release") {
isMinifyEnabled = false
}
}
}
dependencies {
val lintChecks by configurations
l... | @geekygecko @MiSikora is this okay?
Builds on `main` use `Prototype` but builds on PRs use `DebugProd`. Firebase is configured with `au.com.shiftyjelly.pocketcasts`, so to avoid [upload rejections](https://buildkite.com/automattic/pocket-casts-android/builds/15248/steps/canvas?sid=019c1cc1-feab-4a21-87f6-d81de57a50c7#... |
plugins.withType<LibraryPlugin>().configureEach {
configure<LibraryExtension> {
buildTypes {
named("release") {
isMinifyEnabled = false
}
}
}
dependencies {
val lintChecks by configurations
l... | @@ -372,9 +372,7 @@ subprojects {
applicationIdSuffix = ".debug"
}
- maybeCreate("debugProd").apply {
- applicationIdSuffix = ".debug"
- }
+ maybeCreate("debugProd") | build.gradle.kts | 26 | Kotlin | 1 | bug | 1,181 | 51 | 51 | false | Distribute app Prototype Build from PRs via FAD | 4,932 | Automattic/pocket-casts-android | 1,688 | Kotlin | mokagio | mokagio |
playlistUuid = playlistUuid,
podcastUuid = podcastUuid,
searchTerm = searchTerm.orEmpty(),
)
.distinctUntilChanged()
}
override suspend fun addManualEpisodes(playlistUuid: String, episodeUuids: List<String>): Boolean {
return withC... | `podcastDao.findAllIn(newPodcastEpisodes.keys)` is passing episode UUIDs (the map is keyed by `PodcastEpisode::uuid`), but `PodcastDao.findAllIn` expects podcast UUIDs. This will typically produce an empty `podcastSlugs` map and store empty `podcastSlug` values for all inserted playlist episodes. Build the UUID set fro... | playlistUuid = playlistUuid,
podcastUuid = podcastUuid,
searchTerm = searchTerm.orEmpty(),
)
.distinctUntilChanged()
}
override suspend fun addManualEpisodes(playlistUuid: String, episodeUuids: List<String>): Boolean {
return withC... | @@ -415,30 +415,31 @@ class PlaylistManagerImpl(
return@withTransaction false
}
- val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids)
+ val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids).associateBy(PodcastEpisode::uuid)
... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerImpl.kt | 26 | Kotlin | 1 | suggestion | 676 | 51 | 51 | false | Preserve selection order when adding multiple episodes to a plyalist | 4,942 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
override suspend fun addManualEpisodes(playlistUuid: String, episodeUuids: List<String>): Boolean {
return withContext(computationContext) {
appDatabase.withTransaction {
val episodes = playlistDao.getManualPlaylistEpisodes(playlistUuid)
val existingEpisodeUuids ... | The loop silently skips any UUIDs not returned by `episodeDao.findByUuids` (`newPodcastEpisodes[episodeUuid]?.let { ... }`), but still uses the original `forEachIndexed` index later for `sortPosition`. If the DAO returns a partial result set, this can create gaps in `sortPosition` and partially-add a selection without ... |
override suspend fun addManualEpisodes(playlistUuid: String, episodeUuids: List<String>): Boolean {
return withContext(computationContext) {
appDatabase.withTransaction {
val episodes = playlistDao.getManualPlaylistEpisodes(playlistUuid)
val existingEpisodeUuids ... | @@ -415,30 +415,31 @@ class PlaylistManagerImpl(
return@withTransaction false
}
- val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids)
+ val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids).associateBy(PodcastEpisode::uuid)
... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerImpl.kt | 26 | Kotlin | 0.786 | bug | 508 | 51 | 51 | false | Preserve selection order when adding multiple episodes to a plyalist | 4,942 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
val episodes = playlistDao.getManualPlaylistEpisodes(playlistUuid)
val existingEpisodeUuids = episodes.map(ManualPlaylistEpisode::episodeUuid)
val newEpisodeUuids = episodeUuids.filter { uuid -> uuid !in existingEpisodeUuids }
if (newEpisodeUuids.isEmpty()... | Please add a unit/integration test covering the new ordering behavior in addManualEpisodes: when given an input list of episode UUIDs in a specific selection order, the inserted ManualPlaylistEpisode rows should be assigned increasing sortPosition values matching that order (even though the underlying EpisodeDao.findBy... | val episodes = playlistDao.getManualPlaylistEpisodes(playlistUuid)
val existingEpisodeUuids = episodes.map(ManualPlaylistEpisode::episodeUuid)
val newEpisodeUuids = episodeUuids.filter { uuid -> uuid !in existingEpisodeUuids }
if (newEpisodeUuids.isEmpty()... | @@ -415,31 +415,33 @@ class PlaylistManagerImpl(
return@withTransaction false
}
- val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids)
+ val newPodcastEpisodes = episodeDao.findByUuids(newEpisodeUuids).associateBy(PodcastEpisode::uuid)
... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerImpl.kt | 26 | Kotlin | 0.5 | suggestion | 455 | 51 | 51 | false | Preserve selection order when adding multiple episodes to a plyalist | 4,942 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.analytics.testing
import com.automattic.eventhorizon.Trackable
import java.util.concurrent.ConcurrentLinkedQueue
class TestEventSink : (Trackable) -> Unit {
private val events = ConcurrentLinkedQueue<Trackable>()
override fun invoke(event: Trackable) {
events +=... | Spelling/grammar: the error message should use past tense plural (“No events were found in the queue.”) instead of “where found”.
```suggestion
"No events were found in the queue."
``` | package au.com.shiftyjelly.pocketcasts.analytics.testing
import com.automattic.eventhorizon.Trackable
import java.util.concurrent.ConcurrentLinkedQueue
class TestEventSink : (Trackable) -> Unit {
private val events = ConcurrentLinkedQueue<Trackable>()
override fun invoke(event: Trackable) {
events +=... | @@ -0,0 +1,18 @@
+package au.com.shiftyjelly.pocketcasts.analytics.testing
+
+import com.automattic.eventhorizon.Trackable
+import java.util.concurrent.ConcurrentLinkedQueue
+
+class TestEventSink : (Trackable) -> Unit {
+ private val events = ConcurrentLinkedQueue<Trackable>()
+
+ override fun invoke(event: Trac... | modules/services/analytics/testing/src/main/kotlin/au/com/shiftyjelly/pocketcasts/analytics/testing/TestEventSink.kt | 15 | Kotlin | 0.929 | suggestion | 196 | 19 | 19 | false | Use Event Horizon for application lifecycle | 4,943 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
class EventSink(
private val trackers: Set<Tracker>,
private val listeners: Set<AnalyticsTracker.Listener>,
) : (Trackable) -> Unit {
override fun invoke(event: Trackable) {
val analyticsEvent = event.toAnalyticsEvent()
val trackedEvents = trackers.associate { tracker ->
val tra... | `toAnalyticsEvent()` uses `AnalyticsEvent.entries.first { ... }`, which (1) does a linear scan over ~900 entries for every tracked event and (2) will throw a `NoSuchElementException` if an Event Horizon `Trackable.name` doesn’t exactly match an `AnalyticsEvent.key`, potentially crashing analytics calls at runtime. Cons... | package au.com.shiftyjelly.pocketcasts.analytics
import com.automattic.eventhorizon.Trackable
class EventSink(
private val trackers: Set<Tracker>,
private val listeners: Set<AnalyticsTracker.Listener>,
) : (Trackable) -> Unit {
override fun invoke(event: Trackable) {
val analyticsEvent = EVENT_MAP... | @@ -0,0 +1,30 @@
+package au.com.shiftyjelly.pocketcasts.analytics
+
+import com.automattic.eventhorizon.Trackable
+
+class EventSink(
+ private val trackers: Set<Tracker>,
+ private val listeners: Set<AnalyticsTracker.Listener>,
+) : (Trackable) -> Unit {
+ override fun invoke(event: Trackable) {
+ val... | modules/services/analytics/src/main/java/au/com/shiftyjelly/pocketcasts/analytics/EventSink.kt | 26 | Kotlin | 1 | bug | 859 | 28 | 26 | false | Use Event Horizon for application lifecycle | 4,943 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
columnState = columnState,
) {
if (syncState != null) {
item {
val (statusText, statusColor) = when (syncState) {
WatchSyncState.Syncing -> stringResource(LR.string.watch_sync_syncing) to MaterialTheme.colors.onPrimary.copy(alph... | The fully-qualified reference to MaterialTheme is unnecessary since MaterialTheme is already imported at the top of the file (line 18). Use MaterialTheme.typography.caption1 instead for consistency with the rest of the code in this file (e.g., lines 57, 59, 68).
```suggestion
style = Materia... | columnState = columnState,
) {
if (syncState != null) {
item {
val (statusText, statusColor) = when (syncState) {
WatchSyncState.Syncing -> stringResource(LR.string.watch_sync_syncing) to MaterialTheme.colors.onPrimary.copy(alph... | @@ -49,6 +51,36 @@ fun RequirePlusScreen(
ScalingLazyColumn(
columnState = columnState,
) {
+ if (syncState != null) {
+ item {
+ val (statusText, statusColor) = when (syncState) {
+ WatchSyncState.Syncing -> stringResour... | wear/src/main/kotlin/au/com/shiftyjelly/pocketcasts/wear/ui/authentication/RequirePlusScreen.kt | 26 | Kotlin | 0.857 | suggestion | 351 | 51 | 51 | false | [Q1 Quality] WearOs - Enhance UI with connection status updates | 4,951 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
if (viewModel.waitingForSignInToShowStories) {
showStories(StoriesSource.USER_LOGIN)
viewModel.waitingForSignInToShowStories = false
} else if (settings.getEndOfYearShowModal()) {
if (isWhatsNewShowing()) return@observe
... | I’m not sure this log is necessary, as the logs in `sendAuthToDataLayer` already cover this. | if (viewModel.waitingForSignInToShowStories) {
showStories(StoriesSource.USER_LOGIN)
viewModel.waitingForSignInToShowStories = false
} else if (settings.getEndOfYearShowModal()) {
if (isWhatsNewShowing()) return@observe
... | @@ -985,6 +985,7 @@ class MainActivity :
settings.setTrialFinishedSeen(true)
}
+ LogBuffer.i(LogBuffer.TAG_BACKGROUND_TASKS, "Sign-in state changed (isSignedIn=${signinState.isSignedIn}), syncing auth to Wear") | app/src/main/java/au/com/shiftyjelly/pocketcasts/ui/MainActivity.kt | 26 | Kotlin | 0.357 | security | 92 | 51 | 51 | false | [Q1 Quality] WearOS - Improve wear-related logging on phone side | 4,955 | Automattic/pocket-casts-android | 1,688 | Kotlin | geekygecko | sztomek |
@Mock
private lateinit var playbackManager: PlaybackManager
@Mock
private lateinit var podcastManager: PodcastManager
@Mock
private lateinit var upNextQueue: UpNextQueue
private lateinit var viewModel: WatchListScreenViewModel
@Before
fun setup() {
MockitoAnnotations.open... | This `@After` uses `runTest { testScheduler.advanceUntilIdle() }`, but that scheduler belongs to the new `runTest` scope, not the dispatcher installed by `MainCoroutineRule`, so it won’t drain any pending work from the test’s `Dispatchers.Main`. If the intent is to flush coroutines started during the test, advance `cor... | private lateinit var episodeManager: EpisodeManager
@Mock
private lateinit var playbackManager: PlaybackManager
@Mock
private lateinit var podcastManager: PodcastManager
@Mock
private lateinit var upNextQueue: UpNextQueue
private lateinit var viewModel: WatchListScreenViewModel
... | @@ -48,6 +50,11 @@ class WatchListScreenViewModelTest {
viewModel = WatchListScreenViewModel(analyticsTracker, episodeManager, playbackManager, podcastManager)
}
+ @After
+ fun tearDown() = runTest {
+ testScheduler.advanceUntilIdle()
+ } | wear/src/test/kotlin/au/com/shiftyjelly/pocketcasts/wear/ui/WatchListScreenViewModelTest.kt | 26 | Kotlin | 0.643 | refactor | 393 | 51 | 51 | false | [Q1 Quality] WearOS - monitor connectivity changes | 4,959 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
private lateinit var settings: Settings
@Mock
private lateinit var syncManager: SyncManager
private lateinit var testSubject: LoggingInScreenViewModel
private val refreshStateFlow = MutableStateFlow<RefreshState>(RefreshState.Never)
@Before
fun setup() {
MockitoAnnotations.openMo... | This `@After` uses `runTest { testScheduler.advanceUntilIdle() }`, but that scheduler is local to the `runTest` block and won’t affect coroutines scheduled on the `Dispatchers.Main` test dispatcher from `MainCoroutineRule`. Consider advancing `coroutineRule.testDispatcher.scheduler` instead, or remove this teardown if ... |
@Mock
private lateinit var settings: Settings
@Mock
private lateinit var syncManager: SyncManager
private lateinit var testSubject: LoggingInScreenViewModel
private val refreshStateFlow = MutableStateFlow<RefreshState>(RefreshState.Never)
@Before
fun setup() {
MockitoAnnotat... | @@ -41,6 +43,11 @@ class LoggingInScreenViewModelTest {
)
}
+ @After
+ fun tearDown() = runTest {
+ testScheduler.advanceUntilIdle()
+ } | wear/src/test/kotlin/au/com/shiftyjelly/pocketcasts/wear/ui/LoggingInScreenViewModelTest.kt | 26 | Kotlin | 0.786 | refactor | 361 | 51 | 51 | false | [Q1 Quality] WearOS - monitor connectivity changes | 4,959 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | sztomek |
package au.com.shiftyjelly.pocketcasts.models.db
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import au.com.shiftyjelly.pocketcasts.models.db.dao.UserEpisodeDao
import au.com.shiftyjelly.pocketcasts.models.di.ModelModule
import... | Unused imports (`UUID`, `assertNotNull`) will typically fail ktlint/spotless and should be removed.
```suggestion
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertEquals
``` | package au.com.shiftyjelly.pocketcasts.models.db
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import au.com.shiftyjelly.pocketcasts.models.db.dao.UserEpisodeDao
import au.com.shiftyjelly.pocketcasts.models.di.ModelModule
import... | @@ -0,0 +1,133 @@
+package au.com.shiftyjelly.pocketcasts.models.db
+
+import androidx.room.Room
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import au.com.shiftyjelly.pocketcasts.models.db.dao.UserEpisodeDao
+import au.com.shiftyjelly.pocketcasts.mod... | app/src/androidTest/java/au/com/shiftyjelly/pocketcasts/models/db/UserEpisodeDaoDownloadStatusTest.kt | 20 | Kotlin | 1 | bug | 254 | 45 | 45 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
abstract suspend fun updateUploadError(uuid: String, uploadError: String?)
@Query("SELECT * FROM user_episodes WHERE (playing_status_modified IS NOT NULL OR played_up_to_modified IS NOT NULL) AND uuid IS NOT NULL LIMIT 2000")
abstract fun findUserEpisodesToSyncBlocking(): List<UserEpisode>
@Query("UPD... | `updateDownloadStatuses` performs three separate UPDATE statements per episode. Even though it’s wrapped in `@Transaction`, this still increases DB write overhead and can be significantly slower for large batches. Consider replacing the per-field updates with a single `@Query` that updates `episode_status`, `downloaded... | abstract fun findUserEpisodesToSyncBlocking(): List<UserEpisode>
@Query("UPDATE user_episodes SET played_up_to_modified = NULL, playing_status_modified = NULL")
abstract fun markAllSyncedBlocking()
@Query("UPDATE user_episodes SET upload_task_id = :uploadTaskId WHERE uuid = :uuid")
abstract suspen... | @@ -152,4 +156,13 @@ abstract class UserEpisodeDao {
@Query("UPDATE user_episodes SET playing_status = :playingStatus, playing_status_modified = :modified, played_up_to = 0, played_up_to_modified = :modified WHERE uuid IN (:episodesUUIDs)")
abstract suspend fun markAllUnplayed(episodesUUIDs: List<String>, m... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/UserEpisodeDao.kt | 26 | Kotlin | 1 | performance | 1,388 | 30 | 34 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
@Query("SELECT * FROM podcast_episodes LIMIT :limit OFFSET :offset")
abstract suspend fun getAllPodcastEpisodes(limit: Int, offset: Int): List<PodcastEpisode>
@Query("SELECT uuid, title FROM podcast_episodes WHERE cleanTitle != :title LIMIT 50000")
abstract suspend fun getEpisodesWithCleanTitleNotEqual... | `updateDownloadStatuses` issues three separate UPDATEs per row. Within a transaction this is consistent, but it’s still 3x the SQL work and can be a bottleneck when updating many episodes. Prefer a single UPDATE statement that sets `episode_status`, `downloaded_file_path`, and `downloaded_error_details` together for ea... | @Query("SELECT uuid, title FROM podcast_episodes WHERE cleanTitle = :title LIMIT 50000")
abstract suspend fun getEpisodesWithCleanTitleEqual(title: String): List<EpisodeWithTitle>
@Query("UPDATE OR IGNORE podcast_episodes SET cleanTitle = :title WHERE uuid = :uuid")
protected abstract suspend fun updat... | @@ -499,4 +506,13 @@ abstract class EpisodeDao {
@Query("SELECT NOT EXISTS(SELECT * FROM podcast_episodes WHERE cleanTitle IS NULL OR TRIM(cleanTitle) = '' OR cleanTitle = :normalizationToken)")
abstract fun hasNormalizedEpisodeTitles(normalizationToken: String): Flow<Boolean>
+
+ @Transaction
+ open ... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/EpisodeDao.kt | 26 | Kotlin | 1 | performance | 1,264 | 30 | 28 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
abstract suspend fun updateUploadTaskId(uuid: String, uploadTaskId: String?)
@Query("SELECT * FROM user_episodes WHERE upload_task_id = :uploadTaskId")
abstract suspend fun findByUploadTaskId(uploadTaskId: String): UserEpisode?
@Query("UPDATE user_episodes SET playing_status = :playingStatus, playing_... | `updateDownloadStatuses` is `suspend`, but it calls a non-suspending Room `@Query` method. This increases the risk of Room throwing a “cannot access database on the main thread” exception if the caller invokes `updateDownloadStatuses` from `Dispatchers.Main` (since nothing here forces the work off-main). Prefer making ... | abstract suspend fun updateUploadTaskId(uuid: String, uploadTaskId: String?)
@Query("SELECT * FROM user_episodes WHERE upload_task_id = :uploadTaskId")
abstract suspend fun findByUploadTaskId(uploadTaskId: String): UserEpisode?
@Query("UPDATE user_episodes SET playing_status = :playingStatus, playing_... | @@ -152,4 +153,20 @@ abstract class UserEpisodeDao {
@Query("UPDATE user_episodes SET playing_status = :playingStatus, playing_status_modified = :modified, played_up_to = 0, played_up_to_modified = :modified WHERE uuid IN (:episodesUUIDs)")
abstract suspend fun markAllUnplayed(episodesUUIDs: List<String>, m... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/UserEpisodeDao.kt | 26 | Kotlin | 0.786 | suggestion | 482 | 28 | 28 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
@Query("SELECT uuid, title FROM podcast_episodes WHERE cleanTitle = :title LIMIT 50000")
abstract suspend fun getEpisodesWithCleanTitleEqual(title: String): List<EpisodeWithTitle>
@Query("UPDATE OR IGNORE podcast_episodes SET cleanTitle = :title WHERE uuid = :uuid")
protected abstract suspend fun updat... | Same issue as in `UserEpisodeDao`: a `suspend` transactional method is calling a non-suspending Room `@Query` method, which can still trip Room’s main-thread check if the coroutine is running on the main dispatcher. Mark `updateDownloadStatus` as `suspend` (or otherwise ensure this path always runs on a Room/background... | @Query("SELECT uuid, title FROM podcast_episodes WHERE cleanTitle = :title LIMIT 50000")
abstract suspend fun getEpisodesWithCleanTitleEqual(title: String): List<EpisodeWithTitle>
@Query("UPDATE OR IGNORE podcast_episodes SET cleanTitle = :title WHERE uuid = :uuid")
protected abstract suspend fun updat... | @@ -496,4 +497,23 @@ abstract class EpisodeDao {
open suspend fun updateAllCleanTitles(episodes: Collection<EpisodeWithTitle>) {
episodes.forEach { episode -> updateCleanTitle(episode.uuid, episode.title) }
}
+
+ @Query("SELECT NOT EXISTS(SELECT * FROM podcast_episodes WHERE cleanTitle IS NULL OR ... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/EpisodeDao.kt | 26 | Kotlin | 0.786 | suggestion | 331 | 31 | 28 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
podcast_episodes
WHERE
episode_status IS 3;
""",
)
abstract suspend fun getFailedDownloadsStatistics(): EpisodeDownloadFailureStatistics
@Query("SELECT * FROM podcast_episodes LIMIT :limit OFFSET :offset")
abstract suspend fun getAllPodcastEpisodes(limit: Int, offset... | This new `hasNormalizedEpisodeTitles` query appears unrelated to the PR’s stated purpose (atomic download status updates). Consider moving it into a separate PR to keep the change focused and reduce review/rollback scope. | podcast_episodes
WHERE
episode_status IS 3;
""",
)
abstract suspend fun getFailedDownloadsStatistics(): EpisodeDownloadFailureStatistics
@Query("SELECT * FROM podcast_episodes LIMIT :limit OFFSET :offset")
abstract suspend fun getAllPodcastEpisodes(limit: Int, offset... | @@ -496,4 +497,23 @@ abstract class EpisodeDao {
open suspend fun updateAllCleanTitles(episodes: Collection<EpisodeWithTitle>) {
episodes.forEach { episode -> updateCleanTitle(episode.uuid, episode.title) }
}
+
+ @Query("SELECT NOT EXISTS(SELECT * FROM podcast_episodes WHERE cleanTitle IS NULL OR ... | modules/services/model/src/main/java/au/com/shiftyjelly/pocketcasts/models/db/dao/EpisodeDao.kt | 26 | Kotlin | 0.643 | suggestion | 221 | 44 | 41 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.models.db
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import au.com.shiftyjelly.pocketcasts.models.db.dao.EpisodeDao
import au.com.shiftyjelly.pocketcasts.models.di.ModelModule
import au.... | `UserEpisode` is imported but not used in this test file. This will likely fail spotless/ktlint (unused import) and should be removed.
```suggestion
``` | package au.com.shiftyjelly.pocketcasts.models.db
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import au.com.shiftyjelly.pocketcasts.models.db.dao.EpisodeDao
import au.com.shiftyjelly.pocketcasts.models.di.ModelModule
import au.... | @@ -0,0 +1,172 @@
+package au.com.shiftyjelly.pocketcasts.models.db
+
+import androidx.room.Room
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import au.com.shiftyjelly.pocketcasts.models.db.dao.EpisodeDao
+import au.com.shiftyjelly.pocketcasts.models.... | app/src/androidTest/java/au/com/shiftyjelly/pocketcasts/models/db/EpisodeDaoDownloadStatusTest.kt | 10 | Kotlin | 0.786 | bug | 153 | 35 | 35 | false | Update download status atomically | 4,967 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
}
is DownloadResult.UnsuccessfulHttpCall -> {
context.getString(LR.string.error_download_http_failure, result.code)
}
is DownloadResult.ExceptionFailure -> {
val throwable = result.throwable
// Order of checks here is impo... | `ConnectException` is currently mapped to `error_download_socket_timeout`, but there’s a dedicated `error_download_connection_error` string added in this PR. This will surface the wrong failure reason (timeout vs connection error) and leaves the new string resource unused. Map `ConnectException` to `LR.string.error_dow... | }
is DownloadResult.UnsuccessfulHttpCall -> {
context.getString(LR.string.error_download_http_failure, result.code)
}
is DownloadResult.ExceptionFailure -> {
val throwable = result.throwable
// Order of checks here is impo... | @@ -86,55 +122,87 @@ class DownloadEpisodeWorker @AssistedInject constructor(
notificationJob?.cancel()
}
- private fun processFailure(result: DownloadResult.Failure) {
- val message = when (result) {
+ private fun getEpisodeOrThrow() = runBlocking {
+ requireNotNull(episodeManager.f... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 1 | bug | 455 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
prepareForegroundNotification(episode)
episode = refreshDownloadUrl(episode)
val downloadFile = getDownloadFileOrThrow(episode)
val tempFile = File(DownloadHelper.tempPathForEpisode(episode, fileStorage))
val downloadResult = downloader.download(
... | The failure path no longer logs the underlying throwable/stack trace (previously logged in the `ExceptionFailure` branch). Only a formatted message is logged now, which will make diagnosing download failures (SSL issues, IO errors, etc.) much harder in production. Consider logging `result.throwable` as well when handli... | prepareForegroundNotification(episode)
episode = refreshDownloadUrl(episode)
val downloadFile = getDownloadFileOrThrow(episode)
val tempFile = File(DownloadHelper.tempPathForEpisode(episode, fileStorage))
val downloadResult = downloader.download(
... | @@ -46,37 +83,36 @@ class DownloadEpisodeWorker @AssistedInject constructor(
) : Worker(context, params) {
private val args = inputData.toArgs()
private val downloader = EpisodeDownloader(httpClient, progressCache)
- private var notificationJob: Job? = null
+ private var notificationJob: NotificationJo... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.786 | bug | 357 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
private val fileStorage: FileStorage,
private val progressCache: DownloadProgressCache,
private val notificationObserver: DownloadNotificationObserver,
) : Worker(context, params) {
private val args = inputData.toArgs()
private val downloader = EpisodeDownloader(httpClient, progressCache)
privat... | `doWork()` catches `Throwable` and converts it into `ExceptionFailure`, which also swallows cancellation/interrupt signals (e.g., `CancellationException` / `InterruptedException`). This can cause cancelled work to be reported as a failure and may delay stopping. Consider catching `Exception` (not `Throwable`) and rethr... | private val fileStorage: FileStorage,
private val progressCache: DownloadProgressCache,
private val notificationObserver: DownloadNotificationObserver,
) : Worker(context, params) {
private val args = inputData.toArgs()
private val downloader = EpisodeDownloader(httpClient, progressCache)
privat... | @@ -46,37 +83,36 @@ class DownloadEpisodeWorker @AssistedInject constructor(
) : Worker(context, params) {
private val args = inputData.toArgs()
private val downloader = EpisodeDownloader(httpClient, progressCache)
- private var notificationJob: Job? = null
+ private var notificationJob: NotificationJo... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.786 | bug | 468 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
private fun refreshDownloadUrl(episode: BaseEpisode) = runBlocking<BaseEpisode> {
when (episode) {
is PodcastEpisode -> {
val freshDownloadUrl = episodeManager.updateDownloadUrl(episode)
episode.copy(downloadUrl = freshDownloadUrl)
}
is U... | For `InvalidDownloadUrl`, the returned/logged message no longer includes the actual URL value. Even if the user-facing string should be generic, it’s useful to include the URL in logs for debugging/support (e.g., add it to the Timber log fields/message). |
private fun refreshDownloadUrl(episode: BaseEpisode) = runBlocking<BaseEpisode> {
when (episode) {
is PodcastEpisode -> {
val freshDownloadUrl = episodeManager.updateDownloadUrl(episode)
episode.copy(downloadUrl = freshDownloadUrl)
}
is U... | @@ -86,55 +122,87 @@ class DownloadEpisodeWorker @AssistedInject constructor(
notificationJob?.cancel()
}
- private fun processFailure(result: DownloadResult.Failure) {
- val message = when (result) {
+ private fun getEpisodeOrThrow() = runBlocking {
+ requireNotNull(episodeManager.f... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.786 | bug | 254 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
import au.com.shiftyjelly.pocketcasts.servers.di.Downloads
import au.com.shiftyjelly.pocketcasts.utils.extensions.anyMessageContains
import dagger.Lazy
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.io.File
import java.io.IOException
import java.io.InterruptedIOException
import java.n... | Grammar: the sentence reads awkwardly as "ensure requirements".
```suggestion
* work completes. This worker relies on that contract to ensure that these requirements are met.
``` | import au.com.shiftyjelly.pocketcasts.servers.di.Downloads
import au.com.shiftyjelly.pocketcasts.utils.extensions.anyMessageContains
import dagger.Lazy
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.io.File
import java.io.IOException
import java.io.InterruptedIOException
import java.n... | @@ -25,18 +29,51 @@ import dagger.assisted.AssistedInject
import java.io.File
import java.io.IOException
import java.io.InterruptedIOException
+import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException
-import kotlinx.coroutines.... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.714 | suggestion | 179 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
import androidx.work.Data
import androidx.work.ForegroundInfo
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.Worker
import androidx.work.WorkerParameters
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import a... | This file imports `kotlin.coroutines.cancellation.CancellationException`, while most of the codebase appears to use `kotlinx.coroutines.CancellationException` (e.g., `ServerPurchaseApprover.kt:13`, `TranscriptManagerImpl.kt:14`). Consider switching to the consistent import to avoid confusion about which cancellation ty... | import androidx.work.Data
import androidx.work.ForegroundInfo
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.Worker
import androidx.work.WorkerParameters
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import a... | @@ -25,18 +29,51 @@ import dagger.assisted.AssistedInject
import java.io.File
import java.io.IOException
import java.io.InterruptedIOException
+import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException
-import kotlinx.coroutines.... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.786 | suggestion | 340 | 51 | 51 | false | Download worker improvements | 4,972 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
val cardCornerRadius: Float = 4.dpToPx(view.resources.displayMetrics).toFloat()
val isListLayout: Boolean = podcastGridLayout == PodcastGridLayoutType.LIST_VIEW
val unplayedCountBadgeView = view.findViewById<ComposeView>(R.id.badge_view)
fun bind(podcast: Podcast, badgeType: BadgeType, ... | In grid layout you always set the card background to transparent and you always show a white `podcastTitle` initially, but you only apply a colored background in the image `onError` callback. This can render the title unreadable (e.g., light theme) while the image is loading and until the failure callback runs. Conside... | val cardCornerRadius: Float = 4.dpToPx(view.resources.displayMetrics).toFloat()
val isListLayout: Boolean = podcastGridLayout == PodcastGridLayoutType.LIST_VIEW
val unplayedCountBadgeView = view.findViewById<ComposeView>(R.id.badge_view)
fun bind(podcast: Podcast, badgeType: BadgeType, ... | @@ -201,15 +202,40 @@ class FolderAdapter(
}
podcastCardView?.cardElevation = cardElevation
podcastCardView?.radius = cardCornerRadius
+ podcastCardView?.setCardBackgroundColor(Color.TRANSPARENT)
+ podcastOverlay?.hide() | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/podcasts/FolderAdapter.kt | 26 | Kotlin | 1 | bug | 1,282 | 51 | 51 | false | Improve the design of podcasts missing artwork on the podcasts tab | 4,976 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | Copilot |
tempFile = tempFile,
)
downloadResult
} catch (e: Throwable) {
DownloadResult.ExceptionFailure(e)
}
notificationJob?.cancel()
return when (result) {
is DownloadResult.Success -> {
val data = Data.Builder()
... | The retry mechanism uses Result.retry() but doesn't configure a backoff policy. Without setting backoff criteria using setBackoffCriteria() in createWorkRequest(), WorkManager will use the default exponential backoff starting at 10 seconds with a maximum of 5 hours. Consider explicitly configuring the backoff policy to... | val downloadResult = downloader.download(
episode = episode,
downloadFile = downloadFile,
tempFile = tempFile,
)
downloadResult
} catch (e: Throwable) {
DownloadResult.ExceptionFailure(e)
}
notificat... | @@ -115,20 +120,29 @@ class DownloadEpisodeWorker @AssistedInject constructor(
}
is DownloadResult.Failure -> {
- val data = Data.Builder()
- .putString(ERROR_MESSAGE_KEY, processFailure(result))
- .build()
- Result.failure(... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.5 | bug | 476 | 51 | 51 | false | Improve download episode worker | 4,981 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
override fun doWork(): Result {
val result = try {
dispatchWorkStarted()
var episode = getEpisodeOrThrow()
prepareForegroundNotification(episode)
episode = refreshDownloadUrl(episode)
val downloadFile = getDownloadFileOrThrow(episode)
... | The dispatchProgressData(isWorkExecuting = false) call on line 112 does not block waiting for the result (missing .get()), unlike the initial dispatch on line 92. This means the doWork() method might return before the progress data is fully updated, potentially causing race conditions where observers see inconsistent s... |
override fun doWork(): Result {
val result = try {
// Block the work until the state is dispatched
// to keep the state consistent
dispatchProgressData(isWorkExecuting = true).get()
var episode = getEpisodeOrThrow()
prepareForegroundNotification(... | @@ -104,7 +107,9 @@ class DownloadEpisodeWorker @AssistedInject constructor(
} catch (e: Throwable) {
DownloadResult.ExceptionFailure(e)
}
+
notificationJob?.cancel()
+ dispatchProgressData(isWorkExecuting = false) | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 1 | bug | 557 | 51 | 51 | false | Improve download episode worker | 4,981 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
.build()
Result.success(data)
}
is DownloadResult.Failure -> {
val data = Data.Builder()
.putString(ERROR_MESSAGE_KEY, processFailure(result))
.build()
Result.failure(data)
}
... | Similar to line 112, the dispatchProgressData(isWorkExecuting = false) call here does not block waiting for the result (missing .get()). In the onStopped() callback, this could cause the progress data update to not complete before the worker is cleaned up. Consider blocking on this call: dispatchProgressData(isWorkExec... |
return when (result) {
is DownloadResult.Success -> {
val data = Data.Builder()
.putString(DOWNLOAD_FILE_PATH_KEY, result.file.path)
.build()
Result.success(data)
}
is DownloadResult.Failure -> {
... | @@ -115,20 +120,29 @@ class DownloadEpisodeWorker @AssistedInject constructor(
}
is DownloadResult.Failure -> {
- val data = Data.Builder()
- .putString(ERROR_MESSAGE_KEY, processFailure(result))
- .build()
- Result.failure(... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.857 | suggestion | 418 | 51 | 51 | false | Improve download episode worker | 4,981 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.repositories.download
import android.app.Notification
import android.content.Context
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Build
import android.system.ErrnoException
import android.system.OsConstants
import androidx.hilt.work.Hi... | It looks like the max retries used to be 5 is there a reason it's now 3? https://github.com/Automattic/pocket-casts-android/blob/b76b1f59812ad1ba23f600e9b0d38c24f30d33be/modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/task/DownloadEpisodeTask.kt#L83 | private fun Data.toArgs() = DownloadEpisodeWorker.Args(
episodeUuid = requireNotNull(getString(EPISODE_UUID_KEY)),
waitForWifi = getBoolean(WAIT_FOR_WIFI_KEY, true),
waitForPower = getBoolean(WAIT_FOR_POWER_KEY, true),
)
private fun DownloadEpisodeWorker.Args.toData() = Data.Builder()
.putString(EPISOD... | @@ -419,11 +440,11 @@ private const val WAIT_FOR_WIFI_KEY = "wait_for_wifi"
private const val WAIT_FOR_POWER_KEY = "wait_for_power"
// Progress keys
-internal const val IS_WORK_STARTED_KEY = "is_work_started"
+internal const val IS_WORK_EXECUTING = "is_work_executing"
// Output keys
internal const val DOWNLOAD_... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.643 | suggestion | 298 | 430 | 27 | false | Improve download episode worker | 4,981 | Automattic/pocket-casts-android | 1,688 | Kotlin | geekygecko | MiSikora |
import kotlinx.coroutines.launch
import au.com.shiftyjelly.pocketcasts.localization.R as LR
@Singleton
class DownloadManager2 @Inject constructor(
appDatabase: AppDatabase,
settings: Settings,
@ApplicationContext context: Context,
@ApplicationScope private val scope: CoroutineScope,
) : DownloadQueue,
... | This line appears to be a no-op statement. It references `Dispatchers.Default` but doesn't assign it or use it in any way. This has no effect on the code and should likely be removed. If the intent was to specify a dispatcher for the coroutine launched on line 72, it should be passed as an argument to `scope.launch(Dis... | import au.com.shiftyjelly.pocketcasts.localization.R as LR
@Singleton
class DownloadManager2 @Inject constructor(
appDatabase: AppDatabase,
settings: Settings,
@ApplicationContext context: Context,
@ApplicationScope private val scope: CoroutineScope,
) : DownloadQueue,
DownloadStatusObserver {
... | @@ -0,0 +1,301 @@
+package au.com.shiftyjelly.pocketcasts.repositories.download
+
+import android.annotation.SuppressLint
+import android.content.Context
+import androidx.lifecycle.asFlow
+import androidx.room.withTransaction
+import androidx.work.Constraints
+import androidx.work.ExistingWorkPolicy
+import androidx.wo... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadManager2.kt | 26 | Kotlin | 0.857 | suggestion | 358 | 51 | 51 | false | Add download queue entry point | 4,982 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
val constraintsFlow = if (impl != null) {
getWorkManagerConstraintsFlow(impl)
} else {
getInAppConstraintsFlow()
}
return constraintsFlow.distinctUntilChanged()
}
private fun getWorkManagerConstraintsFlow(workManager: WorkManagerImpl): Flow<DownloadConstr... | The callbackFlow implementation for constraint trackers may not emit an initial value when the flow is first collected. This could lead to the combine() on line 276 waiting indefinitely for the first emission from all three flows. Consider using addListener() followed by getting the current tracker state and emitting i... | ) {
fun getConstraintsFlow(): Flow<DownloadPrerequisites> {
// We intentionally try to use WorkManager's internal constraint trackers when available,
// because they encapsulate platform/version/device-specific edge cases (API-level quirks,
// OEM behavior, etc.). There is currently no publi... | @@ -0,0 +1,301 @@
+package au.com.shiftyjelly.pocketcasts.repositories.download
+
+import android.annotation.SuppressLint
+import android.content.Context
+import androidx.lifecycle.asFlow
+import androidx.room.withTransaction
+import androidx.work.Constraints
+import androidx.work.ExistingWorkPolicy
+import androidx.wo... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadManager2.kt | 26 | Kotlin | 1 | suggestion | 694 | 50 | 51 | false | Add download queue entry point | 4,982 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
override fun uploadImageToServerRxCompletable(
episode: UserEpisode,
imageFile: File,
): Completable = getCacheTokenOrLoginRxSingle { token ->
val imageData = FileImageUploadData(episode.uuid, imageFile.length(), "image/png")
syncServiceManager.getFileImageUploadUrl(imageData, t... | The inline comment reads as if this is checking whether the user is “signed in”, but the code is actually checking for an active subscription. Please fix the wording/grammar so it’s clear this is about free vs subscribed accounts (and correct the phrasing “isn't signed it”).
```suggestion
// If the user doesn't... |
override fun uploadImageToServerRxCompletable(
episode: UserEpisode,
imageFile: File,
): Completable = getCacheTokenOrLoginRxSingle { token ->
val imageData = FileImageUploadData(episode.uuid, imageFile.length(), "image/png")
syncServiceManager.getFileImageUploadUrl(imageData, t... | @@ -302,17 +302,24 @@ class SyncManagerImpl @Inject constructor(
syncServiceManager.getPlaybackUrl(episode, token)
}
- override fun getUserEpisodeRxMaybe(uuid: String): Maybe<ServerFile> = getCacheTokenOrLoginRxSingle { token ->
- syncServiceManager.getUserEpisode(uuid, token)
- }.flatMapMa... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/SyncManagerImpl.kt | 26 | Kotlin | 0.857 | suggestion | 385 | 51 | 51 | false | Do not fetch a custom file when user is unsigned | 4,991 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
imageFile: File,
): Completable = getCacheTokenOrLoginRxSingle { token ->
val imageData = FileImageUploadData(episode.uuid, imageFile.length(), "image/png")
syncServiceManager.getFileImageUploadUrl(imageData, token)
}.flatMapCompletable { uploadUrl ->
syncServiceManager.uploadIma... | There are existing unit tests for `SyncManagerImpl`, but this new behavior in `getUserEpisodeRxMaybe` isn’t covered. Please add tests that assert the expected behavior for free vs subscribed users (and/or for HTTP 401 handling, depending on the final approach) so Up Next sync regressions are caught. | imageFile: File,
): Completable = getCacheTokenOrLoginRxSingle { token ->
val imageData = FileImageUploadData(episode.uuid, imageFile.length(), "image/png")
syncServiceManager.getFileImageUploadUrl(imageData, token)
}.flatMapCompletable { uploadUrl ->
syncServiceManager.uploadIma... | @@ -302,17 +302,24 @@ class SyncManagerImpl @Inject constructor(
syncServiceManager.getPlaybackUrl(episode, token)
}
- override fun getUserEpisodeRxMaybe(uuid: String): Maybe<ServerFile> = getCacheTokenOrLoginRxSingle { token ->
- syncServiceManager.getUserEpisode(uuid, token)
- }.flatMapMa... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/SyncManagerImpl.kt | 26 | Kotlin | 0.643 | nitpick | 300 | 51 | 51 | false | Do not fetch a custom file when user is unsigned | 4,991 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteFromServer(episode, token)
}
override fun getPlaybackUrlRxSingle(episode: UserEpisode): Single<String> = getCacheTokenOrLoginRxSingle { token ->
... | The new early-return based on `settings.cachedMembership.value.subscription != null` can be incorrect when the membership cache hasn’t been populated yet (e.g., fresh install / cleared app data). In that case `Membership.Empty` is the default, so this will return `Maybe.empty()` even for paid users and can cause custom... | override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteFromServer(episode, token)
}
override fun getPlaybackUrlRxSingle(episode: UserEpisode): Single<String> = getCacheTokenOrLoginRxSingle { token ->
... | @@ -302,17 +302,24 @@ class SyncManagerImpl @Inject constructor(
syncServiceManager.getPlaybackUrl(episode, token)
}
- override fun getUserEpisodeRxMaybe(uuid: String): Maybe<ServerFile> = getCacheTokenOrLoginRxSingle { token ->
- syncServiceManager.getUserEpisode(uuid, token)
- }.flatMapMa... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/SyncManagerImpl.kt | 26 | Kotlin | 0.786 | bug | 643 | 51 | 51 | false | Do not fetch a custom file when user is unsigned | 4,991 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
}
override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteFromServer(episode, token)
}
override fun getPlaybackUrlRxSingle(episode: UserEpisode): Single<String> = getCacheTokenOrLoginRxSingle { token... | Please add unit tests for the new subscription-gated behavior (e.g., when `cachedSubscription`/membership indicates free, `getUserEpisodeRxMaybe` completes empty and does not call `syncServiceManager.getUserEpisode`; when subscribed, it calls through and maps 200/404/other codes correctly). There are existing unit test... | }
override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteFromServer(episode, token)
}
override fun getPlaybackUrlRxSingle(episode: UserEpisode): Single<String> = getCacheTokenOrLoginRxSingle { token... | @@ -302,17 +302,23 @@ class SyncManagerImpl @Inject constructor(
syncServiceManager.getPlaybackUrl(episode, token)
}
- override fun getUserEpisodeRxMaybe(uuid: String): Maybe<ServerFile> = getCacheTokenOrLoginRxSingle { token ->
- syncServiceManager.getUserEpisode(uuid, token)
- }.flatMapMa... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/SyncManagerImpl.kt | 26 | Kotlin | 0.643 | performance | 386 | 51 | 51 | false | Do not fetch a custom file when user is unsigned | 4,991 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
.ignoreElement()
}
override fun deleteImageFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteImageFromServer(episode, token)
}
override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Respo... | `Response.body()` is nullable; emitting it via `Maybe.just(it.body())` can crash at runtime because RxJava `Maybe`/`Single` do not allow `null` emissions. Consider using `it.body()?.let(Maybe::just) ?: Maybe.error(...)` (or `Maybe.empty()` depending on desired behavior) after verifying the API contract for this endpoin... | .ignoreElement()
}
override fun deleteImageFromServerRxSingle(episode: UserEpisode): Single<Response<Void>> = getCacheTokenOrLoginRxSingle { token ->
syncServiceManager.deleteImageFromServer(episode, token)
}
override fun deleteFromServerRxSingle(episode: UserEpisode): Single<Respo... | @@ -302,17 +302,23 @@ class SyncManagerImpl @Inject constructor(
syncServiceManager.getPlaybackUrl(episode, token)
}
- override fun getUserEpisodeRxMaybe(uuid: String): Maybe<ServerFile> = getCacheTokenOrLoginRxSingle { token ->
- syncServiceManager.getUserEpisode(uuid, token)
- }.flatMapMa... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/sync/SyncManagerImpl.kt | 26 | Kotlin | 1 | bug | 841 | 51 | 51 | false | Do not fetch a custom file when user is unsigned | 4,991 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.repositories.playlist
import androidx.room.util.copy
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.AUDIO_VIDEO_FILTER_VIDEO_ONLY
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.SYNC_STATUS_NOT_SYNCED
import au.com.shifty... | `androidx.room.util.copy` appears to be unused here (all usages are member `copy(...)` calls on data classes). Unused imports typically fail ktlint/spotless in this repo; please remove this import.
```suggestion
``` | package au.com.shiftyjelly.pocketcasts.repositories.playlist
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.AUDIO_VIDEO_FILTER_VIDEO_ONLY
import au.com.shiftyjelly.pocketcasts.models.entity.PlaylistEntity.Companion.SYNC_STATUS_NOT_SYNCED
import au.com.shiftyjelly.pocketcasts.models.type.E... | @@ -1,9 +1,11 @@
package au.com.shiftyjelly.pocketcasts.repositories.playlist
+import androidx.room.util.copy | app/src/androidTest/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerBaseTest.kt | 3 | Kotlin | 0.857 | bug | 216 | 28 | 28 | false | Move auto download playlist selection logic to provider | 4,992 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
clock = clock,
smartRules = playlist.smartRules,
sortType = playlist.settings.sortType,
limit = smartEpisodeLimit,
forcedEpisodeUuid = currentEpisodeUuid,
)
.fi... | This method opens a Room transaction and then does potentially expensive work inside it (switching context and collecting `manualPlaylistFlow`/`smartPlaylistFlow` via `first()` for each playlist). That can hold the DB transaction open longer than necessary and block writers. Consider limiting the transaction to just fe... | clock = clock,
smartRules = playlist.smartRules,
sortType = playlist.settings.sortType,
limit = smartEpisodeLimit,
forcedEpisodeUuid = currentEpisodeUuid,
)
.fi... | @@ -127,6 +127,22 @@ class PlaylistManagerImpl(
}
}
+ override suspend fun getAutoDownloadPlaylists(): List<Playlist> {
+ return appDatabase.withTransaction {
+ val playlists = playlistDao.getAllAutoDownloadPlaylists()
+ withContext(computationContext) {
+ ... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playlist/PlaylistManagerImpl.kt | 26 | Kotlin | 1 | performance | 922 | 51 | 51 | false | Move auto download playlist selection logic to provider | 4,992 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.repositories.download
import android.annotation.SuppressLint
import android.content.Context
import androidx.lifecycle.asFlow
import androidx.room.withTransaction
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.Operation
import android... | The import `androidx.work.await` is unused. The only `await` usage in this file is `awaitClose` from kotlinx.coroutines, which is already imported.
```suggestion
``` | package au.com.shiftyjelly.pocketcasts.repositories.download
import android.annotation.SuppressLint
import android.content.Context
import androidx.lifecycle.asFlow
import androidx.room.withTransaction
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.Operation
import android... | @@ -8,6 +8,7 @@ import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.Operation
import androidx.work.WorkManager
+import androidx.work.await | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadManager2.kt | 11 | Kotlin | 0.786 | suggestion | 166 | 36 | 36 | false | Move auto download playlist selection logic to provider | 4,992 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
binding.checkbox.setOnClickListener {
binding.episodeRow.performClick()
}
binding.checkbox.setOnCheckedChangeListener { _, isChecked ->
bindSelectedRow(isChecked)
}
swipeLayout.addOnSwipeActionListener { action -> onSwipeAction(episode, action) }
}
... | The issue happens when the episode is updated to have the status changed from uploading to uploaded. If it's excluded from the `bind`, then the row status condition never sees the new episode status. | binding.playButton.listener = playButtonListener
binding.checkbox.setOnClickListener {
binding.episodeRow.performClick()
}
binding.checkbox.setOnCheckedChangeListener { _, isChecked ->
bindSelectedRow(isChecked)
}
swipeLayout.addOnSwipeActionListen... | @@ -95,8 +95,8 @@ class UserEpisodeViewHolder(
if (previousUuid != episode.uuid || !isObservingRowData) {
observeRowData()
- observeFileStatus()
}
+ observeFileStatus() | modules/features/podcasts/src/main/java/au/com/shiftyjelly/pocketcasts/podcasts/view/podcast/UserEpisodeViewHolder.kt | 26 | Kotlin | 0.571 | suggestion | 199 | 51 | 51 | false | Fix user file status not updating | 4,998 | Automattic/pocket-casts-android | 1,688 | Kotlin | geekygecko | geekygecko |
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.isVisible
import androidx.core.widget.ImageViewCompat
import au.com.shiftyjelly.pocketcasts.localization.helper.TimeHelper
import au.com.shiftyjelly.pocketcasts.models.entity.UserEpisode
import au.com.shiftyjelly.pocketcasts.models.type.... | The `hideErrorDetails` property should be initialized with a default value (e.g., `= false`) to avoid potential issues if `update()` is called before `setup()`. While the current usage pattern ensures `setup()` is always called first, having a default value makes the code more defensive and aligns with Kotlin best prac... | import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.isVisible
import androidx.core.widget.ImageViewCompat
import au.com.shiftyjelly.pocketcasts.localization.helper.TimeHelper
import au.com.shiftyjelly.pocketcasts.models.entity.UserEpisode
import au.com.shiftyjelly.pocketcasts.models.type.... | @@ -33,8 +30,10 @@ class FileStatusIconsView @JvmOverloads constructor(
defStyleAttr: Int = 0,
) : LinearLayout(context, attrs, defStyleAttr) {
- private val disposables = CompositeDisposable()
var statusText: String? = null
+ private var captionWithAlpha: Int
+ private var iconColor: Int
+ pri... | modules/services/views/src/main/java/au/com/shiftyjelly/pocketcasts/views/component/FileStatusIconsView.kt | 26 | Kotlin | 0.786 | suggestion | 354 | 51 | 51 | false | Fix user file status not updating | 4,998 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | geekygecko |
if (result is Result.Failure) {
progressCache.clearProgress(episode.uuid)
runCatching { downloadFile.delete() }
}
return result
}
private fun downloadOrThrow(episode: BaseEpisode, downloadFile: File, tempFile: File): Result {
val downloadUrl = episode.do... | `isInvalidContentType()` only matches exact values like `application/json` and will miss common `Content-Type` values that include parameters (e.g. `application/json; charset=utf-8`), allowing error pages to be treated as valid media downloads. Consider parsing the media type (or splitting on `;`) before checking type/... | progressCache.clearProgress(episode.uuid)
runCatching { downloadFile.delete() }
}
return result
}
private fun downloadOrThrow(episode: BaseEpisode, downloadFile: File, tempFile: File): Result {
val downloadUrl = episode.downloadUrl?.toHttpUrlOrNull()
if ... | @@ -63,14 +79,26 @@ internal class EpisodeDownloader(
val call = httpClient.get().newCall(request)
progressCache.updateProgress(episode.uuid, downloadedByteCount = 0L, contentLength = null)
- return call.execute().use { response ->
- if (response.isSuccessful) {
- re... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/EpisodeDownloader.kt | 26 | Kotlin | 1 | suggestion | 493 | 51 | 51 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
data class UnsuccessfulHttpCall(val code: Int) : Failure
data class InvalidContentType(val contentType: String) : Failure
data class SuspiciousFileSize(val bytes: Long) : Failure
class ExceptionFailure(val throwable: Throwable) : Failure
}
}
/**
* Have to use enqueue for high b... | `blockingEnqueue()` resumes a `suspendCancellableCoroutine` continuation unconditionally. If the coroutine is cancelled (or the call is cancelled) before the callback fires, `resume/resumeWithException` can throw and/or leak the `Response`. Consider using `tryResume/completeResume` (or `resume(..., onCancellation = { r... | data class UnsuccessfulHttpCall(val code: Int) : Failure
data class InvalidContentType(val contentType: String) : Failure
data class SuspiciousFileSize(val bytes: Long) : Failure
class ExceptionFailure(val throwable: Throwable) : Failure
}
}
/**
* Have to use enqueue for high ba... | @@ -99,6 +127,57 @@ internal class EpisodeDownloader(
data class UnsuccessfulHttpCall(val code: Int) : Failure
+ data class InvalidContentType(val contentType: String) : Failure
+
+ data class SuspiciousFileSize(val bytes: Long) : Failure
+
class ExceptionFailure(val throwable: Throw... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/EpisodeDownloader.kt | 26 | Kotlin | 1 | bug | 1,336 | 51 | 51 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.repositories.download
import androidx.annotation.WorkerThread
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import dagger.Lazy
import java.io.File
import java.io.IOException
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import ko... | Unused import: `kotlin.coroutines.suspendCoroutine` is imported but not referenced in this file. Please remove it to avoid lint/build failures.
```suggestion
``` | package au.com.shiftyjelly.pocketcasts.repositories.download
import androidx.annotation.WorkerThread
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import dagger.Lazy
import java.io.File
import java.io.IOException
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import ko... | @@ -4,8 +4,17 @@ import androidx.annotation.WorkerThread
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import dagger.Lazy
import java.io.File
+import java.io.IOException
+import kotlin.contracts.ExperimentalContracts
+import kotlin.contracts.contract
+import kotlin.coroutines.resume
+import kotlin.... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/EpisodeDownloader.kt | 12 | Kotlin | 0.786 | bug | 162 | 37 | 37 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
responseBodyBytesReceived?.let { put(RESPONSE_BODY_BYTES_RECEIVED_KEY, it) }
fileSize?.let { put(FILE_SIZE_KEY, it) }
tlsCipherSuite?.let { put(TLS_CIPHER_SUITE_KEY, it) }
isCellular?.let { put(IS_CELLULAR_KEY, it) }
isProxy?.let { put(IS_PROXY_KEY, it) }
}
enum class Re... | `Reason.TooManyAttempts` is added, but there are no call sites setting this reason (repo-wide search shows only this enum entry). If you intend to track when downloads give up after `MAX_DOWNLOAD_ATTEMPT_COUNT`, update the worker/task code to set this reason in that terminal path; otherwise consider removing the enum v... | responseBodyBytesReceived?.let { put(RESPONSE_BODY_BYTES_RECEIVED_KEY, it) }
fileSize?.let { put(FILE_SIZE_KEY, it) }
tlsCipherSuite?.let { put(TLS_CIPHER_SUITE_KEY, it) }
isCellular?.let { put(IS_CELLULAR_KEY, it) }
isProxy?.let { put(IS_PROXY_KEY, it) }
}
enum class Re... | @@ -47,6 +47,7 @@ data class EpisodeDownloadError(
NotEnoughStorage("not_enough_storage"),
NoSavePath("no_save_path"),
StorageIssue("storage_issue"),
+ TooManyAttempts("too_many_attempts"), | modules/services/analytics/src/main/java/au/com/shiftyjelly/pocketcasts/analytics/EpisodeDownloadError.kt | 26 | Kotlin | 0.857 | suggestion | 402 | 51 | 51 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
package au.com.shiftyjelly.pocketcasts.repositories.download
import androidx.annotation.WorkerThread
import au.com.shiftyjelly.pocketcasts.models.entity.BaseEpisode
import dagger.Lazy
import java.io.File
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.... | This `blockingEnqueue()` helper duplicates a very similar implementation in `DownloadEpisodeTask` (same watch/horologist rationale) but with different cancellation behavior. To avoid future divergence/bugs, consider extracting a single shared OkHttp `Call.blockingEnqueue()` utility (or reusing the existing one) and usi... |
data class SuspiciousFileSize(val bytes: Long) : Failure
class ExceptionFailure(val throwable: Throwable) : Failure
}
}
/**
* Have to use enqueue for high bandwidth requests on the watch app
* See https://github.com/google/horologist/blob/7bd044a4766e379f85ee3f5a01272853eec3155d/network-awarene... | @@ -99,6 +126,57 @@ internal class EpisodeDownloader(
data class UnsuccessfulHttpCall(val code: Int) : Failure
+ data class InvalidContentType(val contentType: String) : Failure
+
+ data class SuspiciousFileSize(val bytes: Long) : Failure
+
class ExceptionFailure(val throwable: Throw... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/EpisodeDownloader.kt | 26 | Kotlin | 1 | bug | 362 | 105 | 51 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
private val episodeManager: EpisodeManager,
private val userEpisodeManager: UserEpisodeManager,
private val fileStorage: FileStorage,
private val progressCache: DownloadProgressCache,
private val notificationObserver: DownloadNotificationObserver,
) : Worker(context, params) {
private val args =... | `downloadError.tlsCipherSuite` is uppercased using `uppercase()` with the default locale. This can produce unexpected results in some locales (e.g., Turkish). Use locale-invariant casing (e.g., `uppercase(Locale.ROOT)`/`Locale.US`) or skip uppercasing if the cipher suite is already normalized. | class DownloadEpisodeWorker @AssistedInject constructor(
@Assisted private val context: Context,
@Assisted params: WorkerParameters,
@Downloads httpClient: Lazy<Call.Factory>,
private val episodeManager: EpisodeManager,
private val userEpisodeManager: UserEpisodeManager,
private val fileStorage:... | @@ -77,44 +81,68 @@ import au.com.shiftyjelly.pocketcasts.repositories.download.EpisodeDownloader.Re
class DownloadEpisodeWorker @AssistedInject constructor(
@Assisted private val context: Context,
@Assisted params: WorkerParameters,
- @Downloads httpClient: Lazy<OkHttpClient>,
+ @Downloads httpClient:... | modules/services/repositories/src/main/java/au/com/shiftyjelly/pocketcasts/repositories/download/DownloadEpisodeWorker.kt | 26 | Kotlin | 0.786 | suggestion | 294 | 51 | 51 | false | Surface more issues when downloading episodes | 5,002 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
PredefinedEventProperty.PLUS_HAS_LIFETIME to isPocketCastsChampion,
PredefinedEventProperty.PLUS_SUBSCRIPTION_TIER to subscriptionTier,
PredefinedEventProperty.PLUS_SUBSCRIPTION_PLATFORM to subscriptionPlatform,
PredefinedEventProperty.PLUS_SUBSCRIPTION_FREQUENCY to subsc... | `refreshMetadata()` now aliases the user on every call when `accountId` is non-empty, and then recreates the anon id. Because `getUserIds()` always returns a non-null `anonId`, this will repeatedly call `trackAliasUser()` and continuously churn anon IDs (including on app start), instead of only aliasing once when trans... | PredefinedEventProperty.PLUS_HAS_LIFETIME to isPocketCastsChampion,
PredefinedEventProperty.PLUS_SUBSCRIPTION_TIER to subscriptionTier,
PredefinedEventProperty.PLUS_SUBSCRIPTION_PLATFORM to subscriptionPlatform,
PredefinedEventProperty.PLUS_SUBSCRIPTION_FREQUENCY to subsc... | @@ -101,21 +100,11 @@ class TracksAnalyticsTracker @Inject constructor(
}
override fun refreshMetadata() {
- val uuid = accountStatusInfo.getUuid()
- if (!uuid.isNullOrEmpty()) {
- userId = uuid
- // Re-unify the user
- if (anonID != null) {
- tr... | modules/services/analytics/src/main/java/au/com/shiftyjelly/pocketcasts/analytics/TracksAnalyticsTracker.kt | 26 | Kotlin | 0.786 | suggestion | 605 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
fun setUp() {
repository = mock(VariationsRepository::class.java)
accountStatusInfo = mock(AccountStatusInfo::class.java)
experimentProvider = ExperimentProvider(repository, accountStatusInfo, coroutineRule.testDispatcher)
}
@Test
fun `should initialize with uuid`() {
Fe... | `AccountStatusInfo.getUserIds()` is non-nullable, but this test stubs it to return `null` (and twice in a row). This won’t compile and also doesn’t reflect production behavior. Stub it once with `UserIds(accountId = null, anonId = uuid)` for the anon-id case.
```suggestion
``` | fun setUp() {
repository = mock(VariationsRepository::class.java)
accountStatusInfo = mock(AccountStatusInfo::class.java)
experimentProvider = ExperimentProvider(repository, accountStatusInfo, coroutineRule.testDispatcher)
}
@Test
fun `should initialize with uuid`() {
Fe... | @@ -67,48 +64,21 @@ class ExperimentProviderTest {
val uuid = "test-anonID"
- `when`(accountStatusInfo.getUuid()).thenReturn(null)
- `when`(tracksAnalyticsTracker.anonID).thenReturn(uuid)
-
- experimentProvider.initialize()
-
- verify(repository).initialize(uuid)
- verify... | modules/services/analytics/src/test/kotlin/au/com/shiftyjelly/pocketcasts/analytics/experiments/ExperimentProviderTest.kt | 26 | Kotlin | 1 | suggestion | 278 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
private lateinit var accountStatusInfo: AccountStatusInfo
@get:Rule
val featureFlagRule = InMemoryFeatureFlagRule()
@get:Rule
val coroutineRule = MainCoroutineRule()
@Before
fun setUp() {
repository = mock(VariationsRepository::class.java)
accountStatusInfo = mock(AccountS... | The provider calls `repository.initialize(anonymousId = uuid, oAuthToken = null)`, but the test verifies `initialize(uuid)` with a single argument. This is inconsistent with the other verifications in this file that use the 2-arg signature and will likely not compile / will verify the wrong overload. Update these verif... | private lateinit var accountStatusInfo: AccountStatusInfo
@get:Rule
val featureFlagRule = InMemoryFeatureFlagRule()
@get:Rule
val coroutineRule = MainCoroutineRule()
@Before
fun setUp() {
repository = mock(VariationsRepository::class.java)
accountStatusInfo = mock(AccountS... | @@ -43,22 +41,21 @@ class ExperimentProviderTest {
@Before
fun setUp() {
repository = mock(VariationsRepository::class.java)
- tracksAnalyticsTracker = mock(TracksAnalyticsTracker::class.java)
accountStatusInfo = mock(AccountStatusInfo::class.java)
- experimentProvider = Experi... | modules/services/analytics/src/test/kotlin/au/com/shiftyjelly/pocketcasts/analytics/experiments/ExperimentProviderTest.kt | 26 | Kotlin | 0.786 | bug | 364 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
@Test
fun `should initialize with uuid`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, true)
val uuid = "test-uuid"
whenever(accountStatusInfo.getUserIds()).thenReturn(UserIds(accountId = uuid, anonId = "invalid"))
experimentProvider.initialize()
verify(reposit... | Same as above: this verification uses `initialize(uuid)` with a single argument, but `ExperimentProvider` calls `initialize(anonymousId = uuid, oAuthToken = null)`. Update the verification to match the invoked signature. |
@Test
fun `should initialize with uuid`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, true)
val uuid = "test-uuid"
whenever(accountStatusInfo.getUserIds()).thenReturn(UserIds(accountId = uuid, anonId = "invalid"))
experimentProvider.initialize()
verify(reposit... | @@ -67,48 +64,21 @@ class ExperimentProviderTest {
val uuid = "test-anonID"
- `when`(accountStatusInfo.getUuid()).thenReturn(null)
- `when`(tracksAnalyticsTracker.anonID).thenReturn(uuid)
-
- experimentProvider.initialize()
-
- verify(repository).initialize(uuid)
- verify... | modules/services/analytics/src/test/kotlin/au/com/shiftyjelly/pocketcasts/analytics/experiments/ExperimentProviderTest.kt | 26 | Kotlin | 0.786 | security | 220 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
verify(repository, never()).initialize(anyString(), eq(null))
}
@Test
fun `should return null variation when feature flag is disabled`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, false)
val experiment = DummyExperiment.DUMMY_EXPERIMENT
whenever(repository.getVaria... | Same as above: `refreshExperiments()` ends up calling `repository.initialize(anonymousId = uuid, oAuthToken = null)`, but the test verifies `initialize(uuid)` with a single argument. Update the verification to match the actual call signature.
```suggestion
verify(repository).initialize(uuid, null)
``` | @Test
fun `should return null variation when feature flag is disabled`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, false)
val experiment = DummyExperiment.DUMMY_EXPERIMENT
whenever(repository.getVariation(Experiment(experiment.identifier))).thenReturn(Variation.Control)
... | @@ -156,12 +126,12 @@ class ExperimentProviderTest {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, true)
val uuid = "test-uuid"
- `when`(accountStatusInfo.getUuid()).thenReturn(uuid)
+ whenever(accountStatusInfo.getUserIds()).thenReturn(UserIds(accountId = uuid, anonId = "invalid")... | modules/services/analytics/src/test/kotlin/au/com/shiftyjelly/pocketcasts/analytics/experiments/ExperimentProviderTest.kt | 26 | Kotlin | 0.929 | security | 310 | 43 | 40 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
whenever(repository.getVariation(Experiment(experiment.identifier))).thenReturn(Variation.Control)
val variation = experimentProvider.getVariation(experiment)
assertEquals(Control, variation)
}
@Test
fun `getVariation should return Treatment when repository returns Treatment`() {
... | This test stubs `accountStatusInfo.getUserIds()` to return `null`, but the method is non-nullable and `ExperimentProvider.initialize()` won’t call it when the feature flag is disabled anyway. Removing this stub avoids a compilation error and keeps the test focused on the feature-flag behavior.
```suggestion
``` |
val variation = experimentProvider.getVariation(experiment)
assertEquals(Control, variation)
}
@Test
fun `getVariation should return Treatment when repository returns Treatment`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, true)
val experiment = DummyExperiment.D... | @@ -132,7 +102,7 @@ class ExperimentProviderTest {
fun `should not initialize when feature flag is disabled`() {
FeatureFlag.setEnabled(Feature.EXPLAT_EXPERIMENT, false)
- `when`(accountStatusInfo.getUuid()).thenReturn(null)
+ whenever(accountStatusInfo.getUserIds()).thenReturn(null)
| modules/services/analytics/src/test/kotlin/au/com/shiftyjelly/pocketcasts/analytics/experiments/ExperimentProviderTest.kt | 26 | Kotlin | 1 | suggestion | 313 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
import android.accounts.AccountManager
import android.content.Context
import androidx.core.content.edit
import au.com.shiftyjelly.pocketcasts.preferences.AccountConstants
import au.com.shiftyjelly.pocketcasts.utils.extensions.getString
import java.util.UUID
import junit.framework.TestCase.assertEquals
import junit.fram... | `sharedPrefs` and `accountManagerStatusInfo` are initialized once for the whole test class, and the SharedPreferences file is reused across tests. Since `getUserIds()` persists anon IDs, test ordering can leak state and potentially hide regressions (e.g., a test could pass because a previous test already wrote the key)... | import android.accounts.AccountManager
import android.content.Context
import androidx.core.content.edit
import au.com.shiftyjelly.pocketcasts.preferences.AccountConstants
import au.com.shiftyjelly.pocketcasts.utils.extensions.getString
import java.util.UUID
import junit.framework.TestCase.assertEquals
import junit.fram... | @@ -2,64 +2,84 @@ package au.com.shiftyjelly.pocketcasts.repositories.sync
import android.accounts.Account
import android.accounts.AccountManager
-import au.com.shiftyjelly.pocketcasts.analytics.AccountStatusInfo
+import android.content.Context
+import androidx.core.content.edit
import au.com.shiftyjelly.pocketcas... | modules/services/repositories/src/test/java/au/com/shiftyjelly/pocketcasts/repositories/sync/AccountManagerStatusInfoTest.kt | 26 | Kotlin | 0.786 | suggestion | 436 | 51 | 51 | false | Extract user ID tracking from Tracks tracker | 5,010 | Automattic/pocket-casts-android | 1,688 | Kotlin | Copilot | MiSikora |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.