@@ -32,6 +32,7 @@ import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest
3232import org.wordpress.android.fluxc.store.MediaStore.FetchMediaListResponsePayload
3333import org.wordpress.android.fluxc.store.MediaStore.MediaError
3434import org.wordpress.android.fluxc.store.MediaStore.MediaErrorType
35+ import org.wordpress.android.fluxc.store.MediaStore.MediaPayload
3536import org.wordpress.android.fluxc.store.MediaStore.ProgressPayload
3637import org.wordpress.android.fluxc.tools.CoroutineEngine
3738import org.wordpress.android.fluxc.utils.MimeType
@@ -91,6 +92,16 @@ abstract class BaseWPV2MediaRestClient constructor(
9192 }
9293 }
9394
95+ fun fetchMedia (
96+ site : SiteModel ,
97+ media : MediaModel
98+ ) {
99+ coroutineEngine.launch(MEDIA , this , " Fetching Media using WPCom's v2 API" ) {
100+ val payload = syncFetchMedia(site, media.mediaId)
101+ dispatcher.dispatch(MediaActionBuilder .newFetchedMediaAction(payload))
102+ }
103+ }
104+
94105 @Suppress(" TooGenericExceptionCaught" , " SwallowedException" )
95106 private fun syncUploadMedia (site : SiteModel , media : MediaModel ): Flow <ProgressPayload > {
96107 fun ProducerScope<ProgressPayload>.handleFailure (media : MediaModel , error : MediaError ) {
@@ -172,6 +183,44 @@ abstract class BaseWPV2MediaRestClient constructor(
172183 }
173184 }
174185
186+ private suspend fun syncFetchMedia (site : SiteModel , mediaId : Long ): MediaPayload {
187+ val url = WPAPI .media.id(mediaId)
188+ val response = executeGetGsonRequest(
189+ site,
190+ url,
191+ emptyMap(),
192+ MediaWPRESTResponse ::class .java
193+ )
194+
195+ return when (response) {
196+ is WPAPIResponse .Error -> {
197+ val errorMessage = " Fail to fetch media. Response: $response "
198+ AppLog .w(MEDIA , errorMessage)
199+ val error = MediaError (MediaErrorType .fromBaseNetworkError(response.error))
200+ error.logMessage = errorMessage
201+ MediaPayload (site, null , error)
202+ }
203+
204+ is WPAPIResponse .Success -> {
205+ val fetchedMedia = response.data?.toMediaModel(site.id)
206+ when {
207+ fetchedMedia != null -> {
208+ AppLog .v(MEDIA , " Fetched media successfully for mediaId: $mediaId " )
209+ MediaPayload (site, fetchedMedia)
210+ }
211+
212+ else -> {
213+ AppLog .w(
214+ MEDIA ,
215+ " Request successful but fetched media is null for mediaId: $mediaId "
216+ )
217+ MediaPayload (site, null , MediaError (MediaErrorType .NULL_MEDIA_ARG ))
218+ }
219+ }
220+ }
221+ }
222+ }
223+
175224 private suspend fun syncFetchMediaList (
176225 site : SiteModel ,
177226 perPage : Int ,
@@ -202,6 +251,7 @@ abstract class BaseWPV2MediaRestClient constructor(
202251 error.logMessage = errorMessage
203252 FetchMediaListResponsePayload (site, error, mimeType)
204253 }
254+
205255 is WPAPIResponse .Success -> {
206256 val mediaList = response.data.orEmpty().map { it.toMediaModel(site.id) }
207257 AppLog .v(MEDIA , " Fetched media list for site with size: " + mediaList.size)
0 commit comments