Skip to content

Commit

Permalink
Merge pull request #19506 from wordpress-mobile/analysis/use-updated-…
Browse files Browse the repository at this point in the history
…and-null-proof-media-model-class

[Nullability Annotations to Java Classes] Use Updated and Null Proof `MediaModel` Class (`breaking`)
  • Loading branch information
ParaskP7 authored Nov 8, 2023
2 parents 73d4204 + 5a9a89b commit 1f1ba95
Show file tree
Hide file tree
Showing 36 changed files with 185 additions and 173 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -804,17 +804,15 @@ public void onMediaChanged(OnMediaChanged event) {

switch (event.cause) {
case DELETE_MEDIA:
if (event.mediaList != null) {
// If the media was deleted, remove it from multi select if it was selected
for (MediaModel mediaModel : event.mediaList) {
int localMediaId = mediaModel.getId();
mMediaGridFragment.removeFromMultiSelect(localMediaId);
}
// If the media was deleted, remove it from multi select if it was selected
for (MediaModel mediaModel : event.mediaList) {
int localMediaId = mediaModel.getId();
mMediaGridFragment.removeFromMultiSelect(localMediaId);
}
break;
}

if (event.mediaList != null && event.mediaList.size() == 1) {
if (event.mediaList.size() == 1) {
updateMediaGridItem(event.mediaList.get(0), true);
} else {
reloadMediaGrid();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,21 +409,23 @@ private boolean loadMedia(MediaModel media) {
return true;
}

@NonNull
private MediaModel getMediaModelFromEditorImageMetaData() {
MediaModel mediaModel = new MediaModel();
mediaModel.setUrl(mEditorImageMetaData.getSrc());
mediaModel.setTitle(mEditorImageMetaData.getTitle());
mediaModel.setCaption(mEditorImageMetaData.getCaption());
mediaModel.setAlt(mEditorImageMetaData.getAlt());
if (!TextUtils.isEmpty(mEditorImageMetaData.getSrc())) {
mediaModel.setFileName(
mEditorImageMetaData.getSrc().substring(mEditorImageMetaData.getSrc().lastIndexOf("/") + 1));
String source = mEditorImageMetaData.getSrc();
String filename = null;
if (!TextUtils.isEmpty(source)) {
filename = source.substring(source.lastIndexOf("/") + 1);
}
mediaModel.setFileExtension(
org.wordpress.android.fluxc.utils.MediaUtils.getExtension(mEditorImageMetaData.getSrc()));
mediaModel.setWidth(mEditorImageMetaData.getWidthInt());
mediaModel.setHeight(mEditorImageMetaData.getHeightInt());
return mediaModel;
return new MediaModel(
source,
filename,
org.wordpress.android.fluxc.utils.MediaUtils.getExtension(source),
mEditorImageMetaData.getTitle(),
mEditorImageMetaData.getCaption(),
mEditorImageMetaData.getAlt(),
mEditorImageMetaData.getWidthInt(),
mEditorImageMetaData.getHeightInt()
);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMediaChanged(OnMediaChanged event) {
// event for unknown media, ignoring
if (event.mediaList == null || event.mediaList.isEmpty() || !matchesInProgressMedia(event.mediaList.get(0))) {
if (event.mediaList.isEmpty() || !matchesInProgressMedia(event.mediaList.get(0))) {
AppLog.w(T.MEDIA, "Media event not recognized: " + event.mediaList);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,8 +420,8 @@ class MediaPickerViewModel @Inject constructor(
is Identifier.RemoteId -> {
site?.let {
launch {
val media: MediaModel = mediaStore.getSiteMediaWithId(it, identifier.value)
_onNavigate.postValue(Event(PreviewMedia(media)))
val media: MediaModel? = mediaStore.getSiteMediaWithId(it, identifier.value)
media?.let { _onNavigate.postValue(Event(PreviewMedia(it))) }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class StockMediaInsertUseCase(
})
emit(
when {
result.error != null -> InsertModel.Error(result.error.message)
result.error != null -> InsertModel.Error(result.error.message ?: "")
else -> {
trackUploadedStockMediaEvent(result.mediaList)
InsertModel.Success(result.mediaList.mapNotNull { Identifier.RemoteId(it.mediaId) })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,14 @@ class MediaLibraryDataSource(
}

private fun List<MediaModel>.toMediaItems(mediaType: MediaType): List<MediaItem> {
return this.filter { it.url != null }.map { mediaModel ->
return this.filter { it.url.isNotBlank() }.map { mediaModel ->
MediaItem(
RemoteId(mediaModel.mediaId),
mediaModel.url,
mediaModel.title,
mediaType,
mediaModel.mimeType,
dateTimeUtilsWrapper.dateFromIso8601(mediaModel.uploadDate).time
mediaModel.uploadDate?.let { dateTimeUtilsWrapper.dateFromIso8601(it).time } ?: 0L
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2876,7 +2876,9 @@ postId, getSite(), mediaUri,
int postId = getImmutablePost().getId();
for (int localId : localIds) {
MediaModel media = mMediaStore.getMediaWithLocalId(localId);
mFeaturedImageHelper.queueFeaturedImageForUpload(postId, media);
if (media != null) {
mFeaturedImageHelper.queueFeaturedImageForUpload(postId, media);
}
}
if (mEditPostSettingsFragment != null) {
mEditPostSettingsFragment.refreshViews();
Expand Down Expand Up @@ -3312,7 +3314,7 @@ public boolean onMediaRetryClicked(final String mediaId) {
return false;
}

if (media.getUrl() != null && media.getUploadState().equals(MediaUploadState.UPLOADED.toString())) {
if (!TextUtils.isEmpty(media.getUrl()) && media.getUploadState().equals(MediaUploadState.UPLOADED.toString())) {
// Note: we should actually do this when the editor fragment starts instead of waiting for user input.
// Notify the editor fragment upload was successful and it should replace the local url by the remote url.
if (mEditorMediaUploadListener != null) {
Expand Down Expand Up @@ -3447,17 +3449,19 @@ private void onEditorFinalTouchesBeforeShowing() {
// probably here is best for Gutenberg to start interacting with
if (mShowGutenbergEditor && mEditorFragment instanceof GutenbergEditorFragment) {
refreshEditorTheme();
List<MediaModel> failedMedia =
mMediaStore.getMediaForPostWithState(mEditPostRepository.getPost(), MediaUploadState.FAILED);
if (failedMedia != null && !failedMedia.isEmpty()) {
HashSet<Integer> mediaIds = new HashSet<>();
for (MediaModel media : failedMedia) {
// featured image isn't in the editor but in the Post Settings fragment, so we want to skip it
if (!media.getMarkedLocallyAsFeatured()) {
mediaIds.add(media.getId());
PostImmutableModel post = mEditPostRepository.getPost();
if (post != null) {
List<MediaModel> failedMedia = mMediaStore.getMediaForPostWithState(post, MediaUploadState.FAILED);
if (!failedMedia.isEmpty()) {
HashSet<Integer> mediaIds = new HashSet<>();
for (MediaModel media : failedMedia) {
// featured image isn't in the editor but in the Post Settings fragment, so we want to skip it
if (!media.getMarkedLocallyAsFeatured()) {
mediaIds.add(media.getId());
}
}
((GutenbergEditorFragment) mEditorFragment).resetUploadingMediaToFailed(mediaIds);
}
((GutenbergEditorFragment) mEditorFragment).resetUploadingMediaToFailed(mediaIds);
}
} else if (mShowAztecEditor && mEditorFragment instanceof AztecEditorFragment) {
final EntryPoint entryPoint = (EntryPoint) getIntent().getSerializableExtra(EXTRA_ENTRY_POINT);
Expand Down Expand Up @@ -3672,7 +3676,7 @@ public void onMediaUploaded(OnMediaUploaded event) {
mEditorMedia.onMediaUploadError(mEditorMediaUploadListener, event.media, event.error);
} else if (event.completed) {
// if the remote url on completed is null, we consider this upload wasn't successful
if (event.media.getUrl() == null) {
if (TextUtils.isEmpty(event.media.getUrl())) {
MediaError error = new MediaError(MediaErrorType.GENERIC_ERROR);
mEditorMedia.onMediaUploadError(mEditorMediaUploadListener, event.media, error);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1344,7 +1344,7 @@ public void onPostFormatsChanged(OnPostFormatsChanged event) {

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMediaUploaded(OnMediaUploaded event) {
if (event.media.getMarkedLocallyAsFeatured()) {
if (event.media != null && event.media.getMarkedLocallyAsFeatured()) {
refreshViews();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,10 @@ class PostListEventListener(
}
}

@Suppress("unused")
@Suppress("unused", "SpreadOperator")
@Subscribe(threadMode = BACKGROUND)
fun onMediaChanged(event: OnMediaChanged) {
if (!event.isError && event.mediaList != null) {
if (!event.isError) {
featuredMediaChanged(*event.mediaList.map { it.mediaId }.toLongArray())
uploadStatusChanged(*event.mediaList.map { it.localPostId }.toIntArray())
}
Expand Down Expand Up @@ -214,12 +214,12 @@ class PostListEventListener(
if (event.isError || event.canceled) {
return
}
if (event.media == null || event.media.localPostId == 0 || site.id != event.media.localSiteId) {
// Not interested in media not attached to posts or not belonging to the current site
return
val media = event.media
if (media != null && media.localPostId != 0 && site.id == media.localSiteId) {
featuredMediaChanged(media.mediaId)
uploadStatusChanged(media.localPostId)
}
featuredMediaChanged(event.media.mediaId)
uploadStatusChanged(event.media.localPostId)
// Not interested in media not attached to posts or not belonging to the current site
}

// EventBus Events
Expand Down Expand Up @@ -283,7 +283,7 @@ class PostListEventListener(
uploadStatusChanged(event.media.localPostId)
}

@Suppress("unused")
@Suppress("unused", "SpreadOperator")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: UploadService.UploadMediaRetryEvent) {
if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,16 @@ class PostListFeaturedImageTracker(private val dispatcher: Dispatcher, private v
featuredImageMap[featuredImageId]?.let { return it }
mediaStore.getSiteMediaWithId(site, featuredImageId)?.let { media ->
// This should be a pretty rare case, but some media seems to be missing url
return if (media.url != null) {
return if (media.url.isNotBlank()) {
featuredImageMap[featuredImageId] = media.url
media.url
} else null
}
// Media is not in the Store, we need to download it
val mediaToDownload = MediaModel()
mediaToDownload.mediaId = featuredImageId
mediaToDownload.localSiteId = site.id
val mediaToDownload = MediaModel(
site.id,
featuredImageId
)
val payload = MediaPayload(site, mediaToDownload)
dispatcher.dispatch(MediaActionBuilder.newFetchMediaAction(payload))
return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ class StoriesEventListener @Inject constructor(
dialog.show()
return
}
if (media.url != null && media.uploadState == UPLOADED.toString()) {
if (media.url.isNotBlank() && media.uploadState == UPLOADED.toString()) {
// Note: we should actually do this when the editor fragment starts instead of waiting for user
// input.
// Notify the editor fragment upload was successful and it should replace the local url by the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ class AppendMediaToEditorUseCase @Inject constructor(private val fluxCUtilsWrapp
}

private val MediaModel.urlToUse
get() = if (url.isNullOrBlank()) filePath else url
get() = url.ifBlank { filePath }
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ class RemoveMediaUseCase @Inject constructor(

// also make sure it's not being uploaded anywhere else (maybe on some other Post,
// simultaneously)
if (mediaModel.uploadState != null &&
mediaUtils.isLocalFile(mediaModel.uploadState.lowercase(Locale.ROOT)) &&
val uploadState = mediaModel.uploadState
if (uploadState != null &&
mediaUtils.isLocalFile(uploadState.lowercase(Locale.ROOT)) &&
!uploadService.isPendingOrInProgressMediaUpload(mediaModel)
) {
dispatcher.dispatch(MediaActionBuilder.newRemoveMediaAction(mediaModel))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -664,18 +664,20 @@ class StoryComposerActivity : ComposeLoopFrameActivity(),
)
storyMediaFileDataList.add(storyMediaFileData)
} else {
val mediaModel = mediaStore.getSiteMediaWithId(site, it.toLong())
val mediaFile = fluxCUtilsWrapper.mediaFileFromMediaModel(mediaModel)
mediaFile?.let { mediafile ->
mediaFile.alt = StoryFrameItem.getAltTextFromFrameAddedViews(frame)
mediaModel.alt = mediaFile.alt
val storyMediaFileData =
saveStoryGutenbergBlockUseCase.buildMediaFileDataWithTemporaryId(
mediaFile = mediafile,
temporaryId = assignedTempId
)
frame.id = storyMediaFileData.id
storyMediaFileDataList.add(storyMediaFileData)
site?.let { site ->
val mediaModel = mediaStore.getSiteMediaWithId(site, it.toLong())
val mediaFile = fluxCUtilsWrapper.mediaFileFromMediaModel(mediaModel)
mediaFile?.let { mediafile ->
mediaFile.alt = StoryFrameItem.getAltTextFromFrameAddedViews(frame)
mediaModel?.alt = mediaFile.alt
val storyMediaFileData =
saveStoryGutenbergBlockUseCase.buildMediaFileDataWithTemporaryId(
mediaFile = mediafile,
temporaryId = assignedTempId
)
frame.id = storyMediaFileData.id
storyMediaFileDataList.add(storyMediaFileData)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,40 +171,44 @@ static float getOverallProgressForVideo(int videoId, float uploadProgress) {
}

private void handleOnMediaUploadedSuccess(@NonNull OnMediaUploaded event) {
if (event.canceled) {
AppLog.i(T.MEDIA, "MediaUploadHandler > Upload successfully canceled");
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_CANCELED,
getMediaFromInProgressQueueById(event.media.getId()), null);
completeUploadWithId(event.media.getId());
uploadNextInQueue();
} else if (event.completed) {
AppLog.i(T.MEDIA, "MediaUploadHandler > Upload completed - localId=" + event.media.getId() + " title="
+ event.media.getTitle());
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_SUCCESS,
getMediaFromInProgressQueueById(event.media.getId()), null);
completeUploadWithId(event.media.getId());
uploadNextInQueue();
} else {
AppLog.i(T.MEDIA, "MediaUploadHandler > " + event.media.getId() + " - progress: " + event.progress);
if (event.media != null) {
if (event.canceled) {
AppLog.i(T.MEDIA, "MediaUploadHandler > Upload successfully canceled");
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_CANCELED,
getMediaFromInProgressQueueById(event.media.getId()), null);
completeUploadWithId(event.media.getId());
uploadNextInQueue();
} else if (event.completed) {
AppLog.i(T.MEDIA, "MediaUploadHandler > Upload completed - localId=" + event.media.getId() + " title="
+ event.media.getTitle());
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_SUCCESS,
getMediaFromInProgressQueueById(event.media.getId()), null);
completeUploadWithId(event.media.getId());
uploadNextInQueue();
} else {
AppLog.i(T.MEDIA, "MediaUploadHandler > " + event.media.getId() + " - progress: " + event.progress);
}
}
}

private void handleOnMediaUploadedError(@NonNull OnMediaUploaded event) {
AppLog.w(T.MEDIA, "MediaUploadHandler > Error uploading media: " + event.error.message);
MediaModel media = getMediaFromInProgressQueueById(event.media.getId());
if (media != null) {
mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media));
}
if (event.media != null) {
MediaModel media = getMediaFromInProgressQueueById(event.media.getId());
if (media != null) {
mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media));
}

Map<String, Object> properties = new HashMap<>();
properties.put("error_type", event.error.type.name());
properties.put("error_message", event.error.message);
properties.put("error_log", event.error.logMessage);
properties.put("error_status_code", event.error.statusCode);
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_ERROR, media, properties);
Map<String, Object> properties = new HashMap<>();
properties.put("error_type", event.error.type.name());
properties.put("error_message", event.error.message);
properties.put("error_log", event.error.logMessage);
properties.put("error_status_code", event.error.statusCode);
trackUploadMediaEvents(AnalyticsTracker.Stat.MEDIA_UPLOAD_ERROR, media, properties);

completeUploadWithId(event.media.getId());
uploadNextInQueue();
completeUploadWithId(event.media.getId());
uploadNextInQueue();
}
}

private synchronized void uploadNextInQueue() {
Expand Down
Loading

0 comments on commit 1f1ba95

Please sign in to comment.