Skip to content

Commit

Permalink
Merge pull request #5238 from wikimedia/mediaListRevIssues
Browse files Browse the repository at this point in the history
Fix a couple of issues when invoking Gallery from Suggested Edits.
  • Loading branch information
cooltey authored Jan 17, 2025
2 parents 1225d5a + e9a5d1a commit a24d953
Show file tree
Hide file tree
Showing 15 changed files with 66 additions and 76 deletions.
35 changes: 19 additions & 16 deletions app/src/main/java/org/wikipedia/dataclient/RestService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,25 @@ interface RestService {

@Headers("x-analytics: preview=1", "Accept: $ACCEPT_HEADER_SUMMARY")
@GET("page/summary/{title}")
suspend fun getSummaryResponse(
suspend fun getPageSummary(
@Path("title") title: String,
@Header("Referer") referrerUrl: String? = null,
@Header("Cache-Control") cacheControl: String? = null,
@Header(OfflineCacheInterceptor.SAVE_HEADER) saveHeader: String? = null,
@Header(OfflineCacheInterceptor.LANG_HEADER) langHeader: String? = null,
@Header(OfflineCacheInterceptor.TITLE_HEADER) titleHeader: String? = null
): Response<PageSummary>
): PageSummary

@Headers("x-analytics: preview=1", "Accept: $ACCEPT_HEADER_SUMMARY")
@GET("page/summary/{title}")
suspend fun getPageSummary(
@Header("Referer") referrerUrl: String?,
@Path("title") title: String
): PageSummary
suspend fun getSummaryResponse(
@Path("title") title: String,
@Header("Referer") referrerUrl: String? = null,
@Header("Cache-Control") cacheControl: String? = null,
@Header(OfflineCacheInterceptor.SAVE_HEADER) saveHeader: String? = null,
@Header(OfflineCacheInterceptor.LANG_HEADER) langHeader: String? = null,
@Header(OfflineCacheInterceptor.TITLE_HEADER) titleHeader: String? = null
): Response<PageSummary>

@Headers("Accept: $ACCEPT_HEADER_DEFINITION")
@GET("page/definition/{title}")
Expand All @@ -56,21 +60,20 @@ interface RestService {
@Headers("Accept: $ACCEPT_HEADER_SUMMARY")
suspend fun getRandomSummary(): PageSummary

@GET("page/media-list/{title}/{revision}")
@GET("page/media-list/{title}")
suspend fun getMediaList(
@Path("title") title: String,
@Path("revision") revision: Long
@Header("Cache-Control") cacheControl: String? = null,
@Header(OfflineCacheInterceptor.SAVE_HEADER) saveHeader: String? = null,
@Header(OfflineCacheInterceptor.LANG_HEADER) langHeader: String? = null,
@Header(OfflineCacheInterceptor.TITLE_HEADER) titleHeader: String? = null
): MediaList

@GET("page/media-list/{title}/{revision}")
suspend fun getMediaListResponse(
@Path("title") title: String?,
@Path("revision") revision: Long,
@Header("Cache-Control") cacheControl: String?,
@Header(OfflineCacheInterceptor.SAVE_HEADER) saveHeader: String?,
@Header(OfflineCacheInterceptor.LANG_HEADER) langHeader: String?,
@Header(OfflineCacheInterceptor.TITLE_HEADER) titleHeader: String?
): Response<MediaList>
suspend fun getMediaList(
@Path("title") title: String,
@Path("revision") revision: Long
): MediaList

@GET("feed/onthisday/events/{mm}/{dd}")
suspend fun getOnThisDay(@Path("mm") month: Int,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class DescriptionEditViewModel(savedStateHandle: SavedStateHandle) : ViewModel()
}) {
_loadPageSummaryState.value = Resource.Loading()
editingAllowed = false
val summaryResponse = async { ServiceFactory.getRest(pageTitle.wikiSite).getPageSummary(null, pageTitle.prefixedText) }
val summaryResponse = async { ServiceFactory.getRest(pageTitle.wikiSite).getPageSummary(pageTitle.prefixedText) }
val infoResponse = async { ServiceFactory.get(pageTitle.wikiSite).getWikiTextForSectionWithInfo(pageTitle.prefixedText, 0) }

val editError = infoResponse.await().query?.firstPage()?.getErrorForAction("edit")
Expand Down Expand Up @@ -145,8 +145,8 @@ class DescriptionEditViewModel(savedStateHandle: SavedStateHandle) : ViewModel()
var revision = -1L
while (revision < newRevision && retry < 10) {
delay(2000)
val pageSummaryResponse = ServiceFactory.getRest(pageTitle.wikiSite).getSummaryResponse(pageTitle.prefixedText, cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString())
revision = pageSummaryResponse.body()?.revision ?: -1L
val pageSummary = ServiceFactory.getRest(pageTitle.wikiSite).getPageSummary(pageTitle.prefixedText, cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString())
revision = pageSummary.revision
retry++
}
_waitForRevisionState.value = Resource.Success(true)
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/org/wikipedia/edit/EditSectionViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ class EditSectionViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
while (revision < newRevision && retry < 10) {
delay(2000)
val pageSummaryResponse = ServiceFactory.getRest(pageTitle.wikiSite)
.getSummaryResponse(pageTitle.prefixedText, cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString())
revision = pageSummaryResponse.body()?.revision ?: -1L
.getPageSummary(pageTitle.prefixedText, cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString())
revision = pageSummaryResponse.revision
retry++
}
_waitForRevisionState.value = Resource.Success(revision)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import org.wikipedia.descriptions.DescriptionEditActivity.Action.TRANSLATE_CAPTI
import org.wikipedia.descriptions.DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION
import org.wikipedia.descriptions.DescriptionEditReviewView.Companion.ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE
import org.wikipedia.descriptions.DescriptionEditReviewView.Companion.ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE
import org.wikipedia.gallery.GalleryActivity
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
Expand Down Expand Up @@ -93,7 +92,7 @@ class SuggestedEditsCardItemFragment : Fragment() {
}
val pageTitle = viewModel.sourceSummaryForEdit!!.pageTitle
if (viewModel.cardActionType === ADD_CAPTION || viewModel.cardActionType === TRANSLATE_CAPTION) {
it.context.startActivity(GalleryActivity.newIntent(it.context, pageTitle, pageTitle.prefixedText, pageTitle.wikiSite, 0))
it.context.startActivity(FilePageActivity.newIntent(it.context, pageTitle))
} else {
it.context.startActivity(PageActivity.newIntentForNewTab(it.context, HistoryEntry(pageTitle, HistoryEntry.SOURCE_SUGGESTED_EDITS), pageTitle))
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/org/wikipedia/gallery/GalleryActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ class GalleryActivity : BaseActivity(), LinkPreviewDialog.LoadPageCallback, Gall
const val EXTRA_FILENAME = "filename"
const val EXTRA_REVISION = "revision"

fun newIntent(context: Context, pageTitle: PageTitle?, filename: String, wiki: WikiSite, revision: Long): Intent {
fun newIntent(context: Context, pageTitle: PageTitle?, filename: String, wiki: WikiSite, revision: Long? = null): Intent {
return Intent(context, GalleryActivity::class.java)
.putExtra(Constants.ARG_WIKISITE, wiki)
.putExtra(Constants.ARG_TITLE, pageTitle)
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/org/wikipedia/gallery/GalleryViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import org.wikipedia.util.Resource
class GalleryViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
val pageTitle = savedStateHandle.get<PageTitle>(Constants.ARG_TITLE)
val wikiSite = savedStateHandle.get<WikiSite>(Constants.ARG_WIKISITE)!!
val revision = savedStateHandle[GalleryActivity.EXTRA_REVISION] ?: 0L
val revision = savedStateHandle[GalleryActivity.EXTRA_REVISION] as Long?
var initialFilename = savedStateHandle.get<String>(GalleryActivity.EXTRA_FILENAME)

private val _uiState = MutableStateFlow(Resource<MediaList>())
Expand All @@ -34,7 +34,7 @@ class GalleryViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
_uiState.value = Resource.Error(throwable)
}) {
pageTitle?.let {
val response = ServiceFactory.getRest(it.wikiSite).getMediaList(it.prefixedText, revision)
val response = if (revision != null) ServiceFactory.getRest(it.wikiSite).getMediaList(it.prefixedText, revision) else ServiceFactory.getRest(it.wikiSite).getMediaList(it.prefixedText)
_uiState.value = Resource.Success(response)
}
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/org/wikipedia/page/PageActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class PageActivity : BaseActivity(), PageFragment.Callback, LinkPreviewDialog.Lo
startActivity(FilePageActivity.newIntent(this, imageTitle))
} else if (action === DescriptionEditActivity.Action.ADD_CAPTION || action === DescriptionEditActivity.Action.TRANSLATE_CAPTION) {
pageFragment.title?.let { pageTitle ->
startActivity(GalleryActivity.newIntent(this, pageTitle, imageTitle.prefixedText, wikiSite, 0))
startActivity(GalleryActivity.newIntent(this, pageTitle, imageTitle.prefixedText, wikiSite))
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions app/src/main/java/org/wikipedia/page/PageFragmentLoadState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ class PageFragmentLoadState(private var model: PageViewModel,
}

val pageSummaryRequest = async {
ServiceFactory.getRest(title.wikiSite).getSummaryResponse(title.prefixedText, null, model.cacheControl.toString(),
if (model.isInReadingList) OfflineCacheInterceptor.SAVE_HEADER_SAVE else null, title.wikiSite.languageCode, UriUtil.encodeURL(title.prefixedText))
ServiceFactory.getRest(title.wikiSite).getSummaryResponse(title.prefixedText, cacheControl = model.cacheControl.toString(),
saveHeader = if (model.isInReadingList) OfflineCacheInterceptor.SAVE_HEADER_SAVE else null,
langHeader = title.wikiSite.languageCode, titleHeader = UriUtil.encodeURL(title.prefixedText))
}
val watchedRequest = async {
if (WikipediaApp.instance.isOnline && AccountUtil.isLoggedIn) {
Expand All @@ -155,8 +156,8 @@ class PageFragmentLoadState(private var model: PageViewModel,

val pageSummaryResponse = pageSummaryRequest.await()
val watchedResponse = watchedRequest.await()
val isWatched = watchedResponse.query?.firstPage()?.watched ?: false
val hasWatchlistExpiry = watchedResponse.query?.firstPage()?.hasWatchlistExpiry() ?: false
val isWatched = watchedResponse.query?.firstPage()?.watched == true
val hasWatchlistExpiry = watchedResponse.query?.firstPage()?.hasWatchlistExpiry() == true
if (pageSummaryResponse.body() == null) {
throw RuntimeException("Summary response was invalid.")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ class LinkPreviewDialog : ExtendedBottomSheetDialogFragment(), LinkPreviewErrorV
private var linkPreviewInteraction: ArticleLinkPreviewInteraction? = null
private var overlayView: LinkPreviewOverlayView? = null
private var navigateSuccess = false
private var revision: Long = 0
private val viewModel: LinkPreviewViewModel by viewModels()

private val menuListener = PopupMenu.OnMenuItemClickListener { item ->
Expand Down Expand Up @@ -142,7 +141,7 @@ class LinkPreviewDialog : ExtendedBottomSheetDialogFragment(), LinkPreviewErrorV
options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), view, requireActivity().getString(R.string.transition_page_gallery))
}
requestGalleryLauncher.launch(GalleryActivity.newIntent(requireContext(), viewModel.pageTitle,
imageName, viewModel.pageTitle.wikiSite, revision), options)
imageName, viewModel.pageTitle.wikiSite), options)
}

private val requestGalleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
Expand Down Expand Up @@ -238,8 +237,6 @@ class LinkPreviewDialog : ExtendedBottomSheetDialogFragment(), LinkPreviewErrorV
)
linkPreviewInteraction?.logLinkClick()

revision = summary.revision

binding.linkPreviewTitle.text = StringUtil.fromHtml(summary.displayTitle)
if (viewModel.fromPlaces) {
viewModel.location?.let { startLocation ->
Expand Down Expand Up @@ -374,7 +371,7 @@ class LinkPreviewDialog : ExtendedBottomSheetDialogFragment(), LinkPreviewErrorV
}

private fun showPreview(contents: LinkPreviewContents) {
viewModel.loadGallery(revision)
viewModel.loadGallery()
setPreviewContents(contents)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ class LinkPreviewViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
}
}

fun loadGallery(revision: Long) {
fun loadGallery() {
if (Prefs.isImageDownloadEnabled && !pageTitle.isFilePage) {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
L.w("Failed to fetch gallery collection.", throwable)
}) {
val mediaList = ServiceFactory.getRest(pageTitle.wikiSite)
.getMediaList(pageTitle.prefixedText, revision)
.getMediaList(pageTitle.prefixedText)
val maxImages = 10
val items = mediaList.getItems("image", "video").asReversed()
val titleList =
Expand Down
52 changes: 21 additions & 31 deletions app/src/main/java/org/wikipedia/savedpages/SavedPageSyncService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.Request
import okio.Buffer
Expand All @@ -23,9 +24,7 @@ import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.okhttp.HttpStatusException
import org.wikipedia.dataclient.okhttp.OfflineCacheInterceptor
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.events.PageDownloadEvent
import org.wikipedia.gallery.MediaList
import org.wikipedia.page.PageTitle
import org.wikipedia.pageimages.db.PageImage
import org.wikipedia.readinglist.database.ReadingListPage
Expand All @@ -35,7 +34,6 @@ import org.wikipedia.settings.Prefs
import org.wikipedia.util.*
import org.wikipedia.util.log.L
import org.wikipedia.views.CircularProgressBar
import retrofit2.Response
import java.io.IOException
import java.util.concurrent.TimeUnit

Expand Down Expand Up @@ -158,11 +156,21 @@ class SavedPageSyncService(context: Context, params: WorkerParameters) : Corouti
return withContext(Dispatchers.IO) {
val pageTitle = ReadingListPage.toPageTitle(page)

// API calls
val summaryResponse = reqPageSummary(pageTitle)
val revision = summaryResponse.body()?.revision ?: 0
val mediaListResponse = reqMediaList(pageTitle, revision)
val mobileHTMLResponse = reqMobileHTML(pageTitle)
val summaryCall = async { ServiceFactory.getRest(pageTitle.wikiSite).getPageSummary(pageTitle.prefixedText,
cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString(),
saveHeader = OfflineCacheInterceptor.SAVE_HEADER_SAVE, langHeader = pageTitle.wikiSite.languageCode,
titleHeader = UriUtil.encodeURL(pageTitle.prefixedText)) }

val mediaListCall = async { ServiceFactory.getRest(pageTitle.wikiSite).getMediaList(pageTitle.prefixedText,
cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString(),
saveHeader = OfflineCacheInterceptor.SAVE_HEADER_SAVE, langHeader = pageTitle.wikiSite.languageCode,
titleHeader = UriUtil.encodeURL(pageTitle.prefixedText)) }

val mobileHTMLCall = async { reqMobileHTML(pageTitle) }

val summaryResponse = summaryCall.await()
val mediaListResponse = mediaListCall.await()
val mobileHTMLResponse = mobileHTMLCall.await()

page.downloadProgress = MEDIA_LIST_PROGRESS
FlowEventBus.post(PageDownloadEvent(page))
Expand All @@ -175,22 +183,22 @@ class SavedPageSyncService(context: Context, params: WorkerParameters) : Corouti
}
if (Prefs.isImageDownloadEnabled) {
// download thumbnail and lead image
if (!summaryResponse.body()?.thumbnailUrl.isNullOrEmpty()) {
page.thumbUrl = UriUtil.resolveProtocolRelativeUrl(pageTitle.wikiSite, summaryResponse.body()?.thumbnailUrl.orEmpty())
if (!summaryResponse.thumbnailUrl.isNullOrEmpty()) {
page.thumbUrl = UriUtil.resolveProtocolRelativeUrl(pageTitle.wikiSite, summaryResponse.thumbnailUrl.orEmpty())
AppDatabase.instance.pageImagesDao().insertPageImageSync(PageImage(pageTitle, page.thumbUrl.orEmpty()))
fileUrls.add(UriUtil.resolveProtocolRelativeUrl(
ImageUrlUtil.getUrlForPreferredSize(page.thumbUrl.orEmpty(), DimenUtil.calculateLeadImageWidth())))
}

// download article images
for (item in mediaListResponse.body()?.getItems("image").orEmpty()) {
for (item in mediaListResponse.getItems("image")) {
item.srcSets.let {
fileUrls.add(item.getImageUrl(DimenUtil.densityScalar))
}
}
}
page.displayTitle = summaryResponse.body()?.displayTitle.orEmpty()
page.description = summaryResponse.body()?.description.orEmpty()
page.displayTitle = summaryResponse.displayTitle.orEmpty()
page.description = summaryResponse.description.orEmpty()

reqSaveFiles(page, pageTitle, fileUrls)

Expand All @@ -202,24 +210,6 @@ class SavedPageSyncService(context: Context, params: WorkerParameters) : Corouti
}
}

private suspend fun reqPageSummary(pageTitle: PageTitle): Response<PageSummary> {
return withContext(Dispatchers.IO) {
ServiceFactory.getRest(pageTitle.wikiSite).getSummaryResponse(pageTitle.prefixedText,
null, OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString(),
OfflineCacheInterceptor.SAVE_HEADER_SAVE, pageTitle.wikiSite.languageCode,
UriUtil.encodeURL(pageTitle.prefixedText))
}
}

private suspend fun reqMediaList(pageTitle: PageTitle, revision: Long): Response<MediaList> {
return withContext(Dispatchers.IO) {
ServiceFactory.getRest(pageTitle.wikiSite).getMediaListResponse(pageTitle.prefixedText,
revision, OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString(),
OfflineCacheInterceptor.SAVE_HEADER_SAVE, pageTitle.wikiSite.languageCode,
UriUtil.encodeURL(pageTitle.prefixedText))
}
}

private suspend fun reqMobileHTML(pageTitle: PageTitle): okhttp3.Response {
val request = makeUrlRequest(pageTitle.wikiSite,
ServiceFactory.getRestBasePath(pageTitle.wikiSite) +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class SuggestedEditsImageRecsFragmentViewModel(savedStateHandle: SavedStateHandl

recommendation = page?.growthimagesuggestiondata?.first()!!
val wikiSite = WikiSite.forLanguageCode(langCode)
summary = ServiceFactory.getRest(wikiSite).getPageSummary(null, page.title)
summary = ServiceFactory.getRest(wikiSite).getPageSummary(page.title)
pageTitle = summary.getPageTitle(wikiSite)

val thumbUrl = UriUtil.resolveProtocolRelativeUrl(ImageUrlUtil.getUrlForPreferredSize(recommendation.images[0].metadata!!.thumbUrl, Constants.PREFERRED_CARD_THUMBNAIL_SIZE))
Expand Down
Loading

0 comments on commit a24d953

Please sign in to comment.