From e56e4c17c9adfb205c238ccf46bd9650cfbf8679 Mon Sep 17 00:00:00 2001 From: Ammar Githam Date: Sun, 6 Jun 2021 09:43:19 +0900 Subject: [PATCH] Migrate MediaService to object --- .../instagrabber/activities/MainActivity.kt | 6 +- .../fragments/LikesViewerFragment.java | 4 +- .../NotificationsViewerFragment.java | 2 +- .../fragments/StoryViewerFragment.java | 2 +- .../fragments/main/DiscoverFragment.java | 12 ++- .../fragments/main/ProfileFragment.java | 2 +- .../instagrabber/managers/ThreadManager.kt | 10 +-- .../viewmodels/PostViewV2ViewModel.kt | 72 ++++++++++------- .../instagrabber/webservices/MediaService.kt | 77 +++++++++++-------- 9 files changed, 104 insertions(+), 83 deletions(-) diff --git a/app/src/main/java/awais/instagrabber/activities/MainActivity.kt b/app/src/main/java/awais/instagrabber/activities/MainActivity.kt index 1c185133..c72be55e 100644 --- a/app/src/main/java/awais/instagrabber/activities/MainActivity.kt +++ b/app/src/main/java/awais/instagrabber/activities/MainActivity.kt @@ -93,7 +93,6 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL private set private var showBottomViewDestinations: List = emptyList() private var graphQLService: GraphQLService? = null - private var mediaService: MediaService? = null private val serviceConnection: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { @@ -635,9 +634,6 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL .setView(R.layout.dialog_opening_post) .create() if (graphQLService == null) graphQLService = GraphQLService.getInstance() - if (mediaService == null) { - mediaService = deviceUuid?.let { csrfToken?.let { it1 -> MediaService.getInstance(it, it1, userId) } } - } val postCb: ServiceCallback = object : ServiceCallback { override fun onSuccess(feedModel: Media?) { if (feedModel != null) { @@ -662,7 +658,7 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL if (isLoggedIn) { lifecycleScope.launch(Dispatchers.IO) { try { - val media = mediaService?.fetch(shortcodeToId(shortCode)) + val media = MediaService.fetch(shortcodeToId(shortCode)) postCb.onSuccess(media) } catch (e: Exception) { postCb.onFailure(e) diff --git a/app/src/main/java/awais/instagrabber/fragments/LikesViewerFragment.java b/app/src/main/java/awais/instagrabber/fragments/LikesViewerFragment.java index a58016f3..38daa085 100644 --- a/app/src/main/java/awais/instagrabber/fragments/LikesViewerFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/LikesViewerFragment.java @@ -109,10 +109,10 @@ public final class LikesViewerFragment extends BottomSheetDialogFragment impleme final String cookie = settingsHelper.getString(Constants.COOKIE); final long userId = CookieUtils.getUserIdFromCookie(cookie); isLoggedIn = !TextUtils.isEmpty(cookie) && userId != 0; - final String deviceUuid = settingsHelper.getString(Constants.DEVICE_UUID); + // final String deviceUuid = settingsHelper.getString(Constants.DEVICE_UUID); final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); if (csrfToken == null) return; - mediaService = isLoggedIn ? MediaService.getInstance(deviceUuid, csrfToken, userId) : null; + mediaService = isLoggedIn ? MediaService.INSTANCE : null; graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); // setHasOptionsMenu(true); } diff --git a/app/src/main/java/awais/instagrabber/fragments/NotificationsViewerFragment.java b/app/src/main/java/awais/instagrabber/fragments/NotificationsViewerFragment.java index 8271f9af..f0a8f30f 100644 --- a/app/src/main/java/awais/instagrabber/fragments/NotificationsViewerFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/NotificationsViewerFragment.java @@ -223,7 +223,7 @@ public final class NotificationsViewerFragment extends Fragment implements Swipe deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, userId); - mediaService = MediaService.getInstance(deviceUuid, csrfToken, userId); + mediaService = MediaService.INSTANCE; newsService = NewsService.getInstance(); } diff --git a/app/src/main/java/awais/instagrabber/fragments/StoryViewerFragment.java b/app/src/main/java/awais/instagrabber/fragments/StoryViewerFragment.java index 4d5488f4..c56438d0 100644 --- a/app/src/main/java/awais/instagrabber/fragments/StoryViewerFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/StoryViewerFragment.java @@ -161,7 +161,7 @@ public class StoryViewerFragment extends Fragment { final String deviceId = settingsHelper.getString(Constants.DEVICE_UUID); fragmentActivity = (AppCompatActivity) requireActivity(); storiesService = StoriesService.getInstance(csrfToken, userIdFromCookie, deviceId); - mediaService = MediaService.getInstance(deviceId, csrfToken, userIdFromCookie); + mediaService = MediaService.INSTANCE; directMessagesService = DirectMessagesService.getInstance(csrfToken, userIdFromCookie, deviceId); setHasOptionsMenu(true); } diff --git a/app/src/main/java/awais/instagrabber/fragments/main/DiscoverFragment.java b/app/src/main/java/awais/instagrabber/fragments/main/DiscoverFragment.java index 6e115d70..16e12d5d 100644 --- a/app/src/main/java/awais/instagrabber/fragments/main/DiscoverFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/main/DiscoverFragment.java @@ -31,8 +31,6 @@ import awais.instagrabber.repositories.responses.Media; import awais.instagrabber.repositories.responses.discover.TopicCluster; import awais.instagrabber.repositories.responses.discover.TopicalExploreFeedResponse; import awais.instagrabber.utils.AppExecutors; -import awais.instagrabber.utils.Constants; -import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CoroutineUtilsKt; import awais.instagrabber.utils.Utils; import awais.instagrabber.viewmodels.TopicClusterViewModel; @@ -57,11 +55,11 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR super.onCreate(savedInstanceState); fragmentActivity = (MainActivity) requireActivity(); discoverService = DiscoverService.getInstance(); - final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); - final String cookie = Utils.settingsHelper.getString(Constants.COOKIE); - final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); - final long userId = CookieUtils.getUserIdFromCookie(cookie); - mediaService = MediaService.getInstance(deviceUuid, csrfToken, userId); + // final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); + // final String cookie = Utils.settingsHelper.getString(Constants.COOKIE); + // final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); + // final long userId = CookieUtils.getUserIdFromCookie(cookie); + mediaService = MediaService.INSTANCE; } @Override diff --git a/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java b/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java index 1fd246cb..8b4186a8 100644 --- a/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java +++ b/app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java @@ -337,7 +337,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe friendshipService = isLoggedIn ? FriendshipService.getInstance(deviceUuid, csrfToken, myId) : null; directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null; storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : null; - mediaService = isLoggedIn ? MediaService.getInstance(deviceUuid, csrfToken, myId) : null; + mediaService = isLoggedIn ? MediaService.INSTANCE : null; userService = isLoggedIn ? UserService.getInstance() : null; graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); final Context context = getContext(); diff --git a/app/src/main/java/awais/instagrabber/managers/ThreadManager.kt b/app/src/main/java/awais/instagrabber/managers/ThreadManager.kt index c23707f4..647fb243 100644 --- a/app/src/main/java/awais/instagrabber/managers/ThreadManager.kt +++ b/app/src/main/java/awais/instagrabber/managers/ThreadManager.kt @@ -54,8 +54,8 @@ class ThreadManager private constructor( currentUser: User, contentResolver: ContentResolver, viewerId: Long, - csrfToken: String, - deviceUuid: String, + private val csrfToken: String, + private val deviceUuid: String, ) { private val _fetching = MutableLiveData>() val fetching: LiveData> = _fetching @@ -69,7 +69,6 @@ class ThreadManager private constructor( private val currentUser: User? private val contentResolver: ContentResolver private val service: DirectMessagesService - private val mediaService: MediaService private val friendshipService: FriendshipService val thread: LiveData by lazy { @@ -455,7 +454,7 @@ class ThreadManager private constructor( "4", null ) - mediaService.uploadFinish(uploadFinishOptions) + MediaService.uploadFinish(csrfToken, userId, deviceUuid, uploadFinishOptions) val broadcastResponse = service.broadcastVoice( clientContext, threadIdOrUserIds, @@ -779,7 +778,7 @@ class ThreadManager private constructor( "2", VideoOptions(duration / 1000f, emptyList(), 0, false) ) - mediaService.uploadFinish(uploadFinishOptions) + MediaService.uploadFinish(csrfToken, userId, deviceUuid, uploadFinishOptions) val broadcastResponse = service.broadcastVideo( clientContext, threadIdOrUserIds, @@ -1416,7 +1415,6 @@ class ThreadManager private constructor( this.contentResolver = contentResolver this.viewerId = viewerId service = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid) - mediaService = MediaService.getInstance(deviceUuid, csrfToken, viewerId) friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, viewerId) // fetchChats(); } diff --git a/app/src/main/java/awais/instagrabber/viewmodels/PostViewV2ViewModel.kt b/app/src/main/java/awais/instagrabber/viewmodels/PostViewV2ViewModel.kt index 543c9db0..4261a64f 100644 --- a/app/src/main/java/awais/instagrabber/viewmodels/PostViewV2ViewModel.kt +++ b/app/src/main/java/awais/instagrabber/viewmodels/PostViewV2ViewModel.kt @@ -40,12 +40,15 @@ class PostViewV2ViewModel : ViewModel() { private val liked = MutableLiveData(false) private val saved = MutableLiveData(false) private val options = MutableLiveData>(ArrayList()) - private val viewerId: Long - val isLoggedIn: Boolean + private var messageManager: DirectMessagesManager? = null + private val cookie = Utils.settingsHelper.getString(Constants.COOKIE) + private val deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID) + private val csrfToken = getCsrfTokenFromCookie(cookie) + private val viewerId = getUserIdFromCookie(cookie) + lateinit var media: Media private set - private var mediaService: MediaService? = null - private var messageManager: DirectMessagesManager? = null + val isLoggedIn = cookie.isNotBlank() && !csrfToken.isNullOrBlank() && viewerId != 0L fun setMedia(media: Media) { this.media = media @@ -125,11 +128,15 @@ class PostViewV2ViewModel : ViewModel() { fun like(): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } viewModelScope.launch(Dispatchers.IO) { try { val mediaId = media.pk ?: return@launch - val liked = mediaService?.like(mediaId) - updateMediaLikeUnlike(data, liked ?: false) + val liked = MediaService.like(csrfToken!!, viewerId, deviceUuid, mediaId) + updateMediaLikeUnlike(data, liked) } catch (e: Exception) { data.postValue(error(e.message, null)) } @@ -140,11 +147,15 @@ class PostViewV2ViewModel : ViewModel() { fun unlike(): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } viewModelScope.launch(Dispatchers.IO) { try { val mediaId = media.pk ?: return@launch - val unliked = mediaService?.unlike(mediaId) - updateMediaLikeUnlike(data, unliked ?: false) + val unliked = MediaService.unlike(csrfToken!!, viewerId, deviceUuid, mediaId) + updateMediaLikeUnlike(data, unliked) } catch (e: Exception) { data.postValue(error(e.message, null)) } @@ -185,11 +196,15 @@ class PostViewV2ViewModel : ViewModel() { fun save(collection: String?, ignoreSaveState: Boolean): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } viewModelScope.launch(Dispatchers.IO) { try { val mediaId = media.pk ?: return@launch - val saved = mediaService?.save(mediaId, collection) - getSaveUnsaveCallback(data, saved ?: false, ignoreSaveState) + val saved = MediaService.save(csrfToken!!, viewerId, deviceUuid, mediaId, collection) + getSaveUnsaveCallback(data, saved, ignoreSaveState) } catch (e: Exception) { data.postValue(error(e.message, null)) } @@ -200,10 +215,14 @@ class PostViewV2ViewModel : ViewModel() { fun unsave(): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } viewModelScope.launch(Dispatchers.IO) { val mediaId = media.pk ?: return@launch - val unsaved = mediaService?.unsave(mediaId) - getSaveUnsaveCallback(data, unsaved ?: false, false) + val unsaved = MediaService.unsave(csrfToken!!, viewerId, deviceUuid, mediaId) + getSaveUnsaveCallback(data, unsaved, false) } return data } @@ -225,11 +244,15 @@ class PostViewV2ViewModel : ViewModel() { fun updateCaption(caption: String): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } viewModelScope.launch(Dispatchers.IO) { try { val postId = media.pk ?: return@launch - val result = mediaService?.editCaption(postId, caption) - if (result != null && result) { + val result = MediaService.editCaption(csrfToken!!, viewerId, deviceUuid, postId, caption) + if (result) { data.postValue(success("")) media.setPostCaption(caption) this@PostViewV2ViewModel.caption.postValue(media.caption) @@ -255,8 +278,8 @@ class PostViewV2ViewModel : ViewModel() { } viewModelScope.launch(Dispatchers.IO) { try { - val result = mediaService?.translate(pk, "1") - if (result.isNullOrBlank()) { + val result = MediaService.translate(pk, "1") + if (result.isBlank()) { data.postValue(error("", null)) return@launch } @@ -280,6 +303,10 @@ class PostViewV2ViewModel : ViewModel() { fun delete(): LiveData> { val data = MutableLiveData>() data.postValue(loading(null)) + if (!isLoggedIn) { + data.postValue(error("Not logged in!", null)) + return data + } val mediaId = media.id val mediaType = media.mediaType if (mediaId == null || mediaType == null) { @@ -288,7 +315,7 @@ class PostViewV2ViewModel : ViewModel() { } viewModelScope.launch(Dispatchers.IO) { try { - val response = mediaService?.delete(mediaId, mediaType) + val response = MediaService.delete(csrfToken!!, viewerId, deviceUuid, mediaId, mediaType) if (response == null) { data.postValue(success(Any())) return@launch @@ -317,15 +344,4 @@ class PostViewV2ViewModel : ViewModel() { val mediaId = media.id ?: return messageManager?.sendMedia(recipients, mediaId, viewModelScope) } - - init { - val cookie = Utils.settingsHelper.getString(Constants.COOKIE) - val deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID) - val csrfToken: String? = getCsrfTokenFromCookie(cookie) - viewerId = getUserIdFromCookie(cookie) - isLoggedIn = cookie.isNotBlank() && viewerId != 0L - if (!csrfToken.isNullOrBlank()) { - mediaService = MediaService.getInstance(deviceUuid, csrfToken, viewerId) - } - } } \ No newline at end of file diff --git a/app/src/main/java/awais/instagrabber/webservices/MediaService.kt b/app/src/main/java/awais/instagrabber/webservices/MediaService.kt index ee128d73..a08747af 100644 --- a/app/src/main/java/awais/instagrabber/webservices/MediaService.kt +++ b/app/src/main/java/awais/instagrabber/webservices/MediaService.kt @@ -12,11 +12,12 @@ import awais.instagrabber.utils.retryContextString import awais.instagrabber.webservices.RetrofitFactory.retrofit import org.json.JSONObject -class MediaService private constructor( - val deviceUuid: String, - val csrfToken: String, - val userId: Long, -) : BaseService() { +object MediaService : BaseService() { + private val DELETABLE_ITEMS_TYPES = listOf( + MediaItemType.MEDIA_TYPE_IMAGE, + MediaItemType.MEDIA_TYPE_VIDEO, + MediaItemType.MEDIA_TYPE_SLIDER + ) private val repository: MediaRepository = retrofit.create(MediaRepository::class.java) suspend fun fetch( @@ -28,15 +29,38 @@ class MediaService private constructor( } else response.items[0] } - suspend fun like(mediaId: String): Boolean = action(mediaId, "like", null) + suspend fun like( + csrfToken: String, + userId: Long, + deviceUuid: String, + mediaId: String, + ): Boolean = action(csrfToken, userId, deviceUuid, mediaId, "like", null) - suspend fun unlike(mediaId: String): Boolean = action(mediaId, "unlike", null) + suspend fun unlike( + csrfToken: String, + userId: Long, + deviceUuid: String, + mediaId: String, + ): Boolean = action(csrfToken, userId, deviceUuid, mediaId, "unlike", null) - suspend fun save(mediaId: String, collection: String?): Boolean = action(mediaId, "save", collection) + suspend fun save( + csrfToken: String, + userId: Long, + deviceUuid: String, + mediaId: String, collection: String?, + ): Boolean = action(csrfToken, userId, deviceUuid, mediaId, "save", collection) - suspend fun unsave(mediaId: String): Boolean = action(mediaId, "unsave", null) + suspend fun unsave( + csrfToken: String, + userId: Long, + deviceUuid: String, + mediaId: String, + ): Boolean = action(csrfToken, userId, deviceUuid, mediaId, "unsave", null) private suspend fun action( + csrfToken: String, + userId: Long, + deviceUuid: String, mediaId: String, action: String, collection: String?, @@ -60,6 +84,9 @@ class MediaService private constructor( } suspend fun editCaption( + csrfToken: String, + userId: Long, + deviceUuid: String, postId: String, newCaption: String, ): Boolean { @@ -99,7 +126,12 @@ class MediaService private constructor( return jsonObject.optString("translation") } - suspend fun uploadFinish(options: UploadFinishOptions): String { + suspend fun uploadFinish( + csrfToken: String, + userId: Long, + deviceUuid: String, + options: UploadFinishOptions, + ): String { if (options.videoOptions != null) { val videoOptions = options.videoOptions if (videoOptions.clips.isEmpty()) { @@ -124,6 +156,9 @@ class MediaService private constructor( } suspend fun delete( + csrfToken: String, + userId: Long, + deviceUuid: String, postId: String, type: MediaItemType, ): String? { @@ -144,26 +179,4 @@ class MediaService private constructor( } return repository.delete(postId, mediaType, signedForm) } - - companion object { - private val DELETABLE_ITEMS_TYPES = listOf( - MediaItemType.MEDIA_TYPE_IMAGE, - MediaItemType.MEDIA_TYPE_VIDEO, - MediaItemType.MEDIA_TYPE_SLIDER - ) - private lateinit var instance: MediaService - - @JvmStatic - fun getInstance(deviceUuid: String, csrfToken: String, userId: Long): MediaService { - if (!this::instance.isInitialized - || instance.csrfToken != csrfToken - || instance.deviceUuid != deviceUuid - || instance.userId != userId - ) { - instance = MediaService(deviceUuid, csrfToken, userId) - } - return instance - } - } - } \ No newline at end of file