1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-11-22 14:47:29 +00:00

Migrate MediaService to object

This commit is contained in:
Ammar Githam 2021-06-06 09:43:19 +09:00
parent 3f09c7d173
commit e56e4c17c9
9 changed files with 104 additions and 83 deletions

View File

@ -93,7 +93,6 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL
private set private set
private var showBottomViewDestinations: List<Int> = emptyList() private var showBottomViewDestinations: List<Int> = emptyList()
private var graphQLService: GraphQLService? = null private var graphQLService: GraphQLService? = null
private var mediaService: MediaService? = null
private val serviceConnection: ServiceConnection = object : ServiceConnection { private val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) { override fun onServiceConnected(name: ComponentName, service: IBinder) {
@ -635,9 +634,6 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL
.setView(R.layout.dialog_opening_post) .setView(R.layout.dialog_opening_post)
.create() .create()
if (graphQLService == null) graphQLService = GraphQLService.getInstance() if (graphQLService == null) graphQLService = GraphQLService.getInstance()
if (mediaService == null) {
mediaService = deviceUuid?.let { csrfToken?.let { it1 -> MediaService.getInstance(it, it1, userId) } }
}
val postCb: ServiceCallback<Media> = object : ServiceCallback<Media> { val postCb: ServiceCallback<Media> = object : ServiceCallback<Media> {
override fun onSuccess(feedModel: Media?) { override fun onSuccess(feedModel: Media?) {
if (feedModel != null) { if (feedModel != null) {
@ -662,7 +658,7 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL
if (isLoggedIn) { if (isLoggedIn) {
lifecycleScope.launch(Dispatchers.IO) { lifecycleScope.launch(Dispatchers.IO) {
try { try {
val media = mediaService?.fetch(shortcodeToId(shortCode)) val media = MediaService.fetch(shortcodeToId(shortCode))
postCb.onSuccess(media) postCb.onSuccess(media)
} catch (e: Exception) { } catch (e: Exception) {
postCb.onFailure(e) postCb.onFailure(e)

View File

@ -109,10 +109,10 @@ public final class LikesViewerFragment extends BottomSheetDialogFragment impleme
final String cookie = settingsHelper.getString(Constants.COOKIE); final String cookie = settingsHelper.getString(Constants.COOKIE);
final long userId = CookieUtils.getUserIdFromCookie(cookie); final long userId = CookieUtils.getUserIdFromCookie(cookie);
isLoggedIn = !TextUtils.isEmpty(cookie) && userId != 0; 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); final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie);
if (csrfToken == null) return; if (csrfToken == null) return;
mediaService = isLoggedIn ? MediaService.getInstance(deviceUuid, csrfToken, userId) : null; mediaService = isLoggedIn ? MediaService.INSTANCE : null;
graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); graphQLService = isLoggedIn ? null : GraphQLService.getInstance();
// setHasOptionsMenu(true); // setHasOptionsMenu(true);
} }

View File

@ -223,7 +223,7 @@ public final class NotificationsViewerFragment extends Fragment implements Swipe
deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID);
csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie);
friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, userId); friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, userId);
mediaService = MediaService.getInstance(deviceUuid, csrfToken, userId); mediaService = MediaService.INSTANCE;
newsService = NewsService.getInstance(); newsService = NewsService.getInstance();
} }

View File

@ -161,7 +161,7 @@ public class StoryViewerFragment extends Fragment {
final String deviceId = settingsHelper.getString(Constants.DEVICE_UUID); final String deviceId = settingsHelper.getString(Constants.DEVICE_UUID);
fragmentActivity = (AppCompatActivity) requireActivity(); fragmentActivity = (AppCompatActivity) requireActivity();
storiesService = StoriesService.getInstance(csrfToken, userIdFromCookie, deviceId); storiesService = StoriesService.getInstance(csrfToken, userIdFromCookie, deviceId);
mediaService = MediaService.getInstance(deviceId, csrfToken, userIdFromCookie); mediaService = MediaService.INSTANCE;
directMessagesService = DirectMessagesService.getInstance(csrfToken, userIdFromCookie, deviceId); directMessagesService = DirectMessagesService.getInstance(csrfToken, userIdFromCookie, deviceId);
setHasOptionsMenu(true); setHasOptionsMenu(true);
} }

View File

@ -31,8 +31,6 @@ import awais.instagrabber.repositories.responses.Media;
import awais.instagrabber.repositories.responses.discover.TopicCluster; import awais.instagrabber.repositories.responses.discover.TopicCluster;
import awais.instagrabber.repositories.responses.discover.TopicalExploreFeedResponse; import awais.instagrabber.repositories.responses.discover.TopicalExploreFeedResponse;
import awais.instagrabber.utils.AppExecutors; import awais.instagrabber.utils.AppExecutors;
import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.CoroutineUtilsKt; import awais.instagrabber.utils.CoroutineUtilsKt;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.TopicClusterViewModel; import awais.instagrabber.viewmodels.TopicClusterViewModel;
@ -57,11 +55,11 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
fragmentActivity = (MainActivity) requireActivity(); fragmentActivity = (MainActivity) requireActivity();
discoverService = DiscoverService.getInstance(); discoverService = DiscoverService.getInstance();
final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID); // final String deviceUuid = Utils.settingsHelper.getString(Constants.DEVICE_UUID);
final String cookie = Utils.settingsHelper.getString(Constants.COOKIE); // final String cookie = Utils.settingsHelper.getString(Constants.COOKIE);
final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie); // final String csrfToken = CookieUtils.getCsrfTokenFromCookie(cookie);
final long userId = CookieUtils.getUserIdFromCookie(cookie); // final long userId = CookieUtils.getUserIdFromCookie(cookie);
mediaService = MediaService.getInstance(deviceUuid, csrfToken, userId); mediaService = MediaService.INSTANCE;
} }
@Override @Override

View File

@ -337,7 +337,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
friendshipService = isLoggedIn ? FriendshipService.getInstance(deviceUuid, csrfToken, myId) : null; friendshipService = isLoggedIn ? FriendshipService.getInstance(deviceUuid, csrfToken, myId) : null;
directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null; directMessagesService = isLoggedIn ? DirectMessagesService.getInstance(csrfToken, myId, deviceUuid) : null;
storiesService = isLoggedIn ? StoriesService.getInstance(null, 0L, null) : 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; userService = isLoggedIn ? UserService.getInstance() : null;
graphQLService = isLoggedIn ? null : GraphQLService.getInstance(); graphQLService = isLoggedIn ? null : GraphQLService.getInstance();
final Context context = getContext(); final Context context = getContext();

View File

@ -54,8 +54,8 @@ class ThreadManager private constructor(
currentUser: User, currentUser: User,
contentResolver: ContentResolver, contentResolver: ContentResolver,
viewerId: Long, viewerId: Long,
csrfToken: String, private val csrfToken: String,
deviceUuid: String, private val deviceUuid: String,
) { ) {
private val _fetching = MutableLiveData<Resource<Any?>>() private val _fetching = MutableLiveData<Resource<Any?>>()
val fetching: LiveData<Resource<Any?>> = _fetching val fetching: LiveData<Resource<Any?>> = _fetching
@ -69,7 +69,6 @@ class ThreadManager private constructor(
private val currentUser: User? private val currentUser: User?
private val contentResolver: ContentResolver private val contentResolver: ContentResolver
private val service: DirectMessagesService private val service: DirectMessagesService
private val mediaService: MediaService
private val friendshipService: FriendshipService private val friendshipService: FriendshipService
val thread: LiveData<DirectThread?> by lazy { val thread: LiveData<DirectThread?> by lazy {
@ -455,7 +454,7 @@ class ThreadManager private constructor(
"4", "4",
null null
) )
mediaService.uploadFinish(uploadFinishOptions) MediaService.uploadFinish(csrfToken, userId, deviceUuid, uploadFinishOptions)
val broadcastResponse = service.broadcastVoice( val broadcastResponse = service.broadcastVoice(
clientContext, clientContext,
threadIdOrUserIds, threadIdOrUserIds,
@ -779,7 +778,7 @@ class ThreadManager private constructor(
"2", "2",
VideoOptions(duration / 1000f, emptyList(), 0, false) VideoOptions(duration / 1000f, emptyList(), 0, false)
) )
mediaService.uploadFinish(uploadFinishOptions) MediaService.uploadFinish(csrfToken, userId, deviceUuid, uploadFinishOptions)
val broadcastResponse = service.broadcastVideo( val broadcastResponse = service.broadcastVideo(
clientContext, clientContext,
threadIdOrUserIds, threadIdOrUserIds,
@ -1416,7 +1415,6 @@ class ThreadManager private constructor(
this.contentResolver = contentResolver this.contentResolver = contentResolver
this.viewerId = viewerId this.viewerId = viewerId
service = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid) service = DirectMessagesService.getInstance(csrfToken, viewerId, deviceUuid)
mediaService = MediaService.getInstance(deviceUuid, csrfToken, viewerId)
friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, viewerId) friendshipService = FriendshipService.getInstance(deviceUuid, csrfToken, viewerId)
// fetchChats(); // fetchChats();
} }

View File

@ -40,12 +40,15 @@ class PostViewV2ViewModel : ViewModel() {
private val liked = MutableLiveData(false) private val liked = MutableLiveData(false)
private val saved = MutableLiveData(false) private val saved = MutableLiveData(false)
private val options = MutableLiveData<List<Int>>(ArrayList()) private val options = MutableLiveData<List<Int>>(ArrayList())
private val viewerId: Long private var messageManager: DirectMessagesManager? = null
val isLoggedIn: Boolean 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 lateinit var media: Media
private set private set
private var mediaService: MediaService? = null val isLoggedIn = cookie.isNotBlank() && !csrfToken.isNullOrBlank() && viewerId != 0L
private var messageManager: DirectMessagesManager? = null
fun setMedia(media: Media) { fun setMedia(media: Media) {
this.media = media this.media = media
@ -125,11 +128,15 @@ class PostViewV2ViewModel : ViewModel() {
fun like(): LiveData<Resource<Any?>> { fun like(): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val mediaId = media.pk ?: return@launch val mediaId = media.pk ?: return@launch
val liked = mediaService?.like(mediaId) val liked = MediaService.like(csrfToken!!, viewerId, deviceUuid, mediaId)
updateMediaLikeUnlike(data, liked ?: false) updateMediaLikeUnlike(data, liked)
} catch (e: Exception) { } catch (e: Exception) {
data.postValue(error(e.message, null)) data.postValue(error(e.message, null))
} }
@ -140,11 +147,15 @@ class PostViewV2ViewModel : ViewModel() {
fun unlike(): LiveData<Resource<Any?>> { fun unlike(): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val mediaId = media.pk ?: return@launch val mediaId = media.pk ?: return@launch
val unliked = mediaService?.unlike(mediaId) val unliked = MediaService.unlike(csrfToken!!, viewerId, deviceUuid, mediaId)
updateMediaLikeUnlike(data, unliked ?: false) updateMediaLikeUnlike(data, unliked)
} catch (e: Exception) { } catch (e: Exception) {
data.postValue(error(e.message, null)) data.postValue(error(e.message, null))
} }
@ -185,11 +196,15 @@ class PostViewV2ViewModel : ViewModel() {
fun save(collection: String?, ignoreSaveState: Boolean): LiveData<Resource<Any?>> { fun save(collection: String?, ignoreSaveState: Boolean): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val mediaId = media.pk ?: return@launch val mediaId = media.pk ?: return@launch
val saved = mediaService?.save(mediaId, collection) val saved = MediaService.save(csrfToken!!, viewerId, deviceUuid, mediaId, collection)
getSaveUnsaveCallback(data, saved ?: false, ignoreSaveState) getSaveUnsaveCallback(data, saved, ignoreSaveState)
} catch (e: Exception) { } catch (e: Exception) {
data.postValue(error(e.message, null)) data.postValue(error(e.message, null))
} }
@ -200,10 +215,14 @@ class PostViewV2ViewModel : ViewModel() {
fun unsave(): LiveData<Resource<Any?>> { fun unsave(): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val mediaId = media.pk ?: return@launch val mediaId = media.pk ?: return@launch
val unsaved = mediaService?.unsave(mediaId) val unsaved = MediaService.unsave(csrfToken!!, viewerId, deviceUuid, mediaId)
getSaveUnsaveCallback(data, unsaved ?: false, false) getSaveUnsaveCallback(data, unsaved, false)
} }
return data return data
} }
@ -225,11 +244,15 @@ class PostViewV2ViewModel : ViewModel() {
fun updateCaption(caption: String): LiveData<Resource<Any?>> { fun updateCaption(caption: String): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val postId = media.pk ?: return@launch val postId = media.pk ?: return@launch
val result = mediaService?.editCaption(postId, caption) val result = MediaService.editCaption(csrfToken!!, viewerId, deviceUuid, postId, caption)
if (result != null && result) { if (result) {
data.postValue(success("")) data.postValue(success(""))
media.setPostCaption(caption) media.setPostCaption(caption)
this@PostViewV2ViewModel.caption.postValue(media.caption) this@PostViewV2ViewModel.caption.postValue(media.caption)
@ -255,8 +278,8 @@ class PostViewV2ViewModel : ViewModel() {
} }
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val result = mediaService?.translate(pk, "1") val result = MediaService.translate(pk, "1")
if (result.isNullOrBlank()) { if (result.isBlank()) {
data.postValue(error("", null)) data.postValue(error("", null))
return@launch return@launch
} }
@ -280,6 +303,10 @@ class PostViewV2ViewModel : ViewModel() {
fun delete(): LiveData<Resource<Any?>> { fun delete(): LiveData<Resource<Any?>> {
val data = MutableLiveData<Resource<Any?>>() val data = MutableLiveData<Resource<Any?>>()
data.postValue(loading(null)) data.postValue(loading(null))
if (!isLoggedIn) {
data.postValue(error("Not logged in!", null))
return data
}
val mediaId = media.id val mediaId = media.id
val mediaType = media.mediaType val mediaType = media.mediaType
if (mediaId == null || mediaType == null) { if (mediaId == null || mediaType == null) {
@ -288,7 +315,7 @@ class PostViewV2ViewModel : ViewModel() {
} }
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
val response = mediaService?.delete(mediaId, mediaType) val response = MediaService.delete(csrfToken!!, viewerId, deviceUuid, mediaId, mediaType)
if (response == null) { if (response == null) {
data.postValue(success(Any())) data.postValue(success(Any()))
return@launch return@launch
@ -317,15 +344,4 @@ class PostViewV2ViewModel : ViewModel() {
val mediaId = media.id ?: return val mediaId = media.id ?: return
messageManager?.sendMedia(recipients, mediaId, viewModelScope) 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)
}
}
} }

View File

@ -12,11 +12,12 @@ import awais.instagrabber.utils.retryContextString
import awais.instagrabber.webservices.RetrofitFactory.retrofit import awais.instagrabber.webservices.RetrofitFactory.retrofit
import org.json.JSONObject import org.json.JSONObject
class MediaService private constructor( object MediaService : BaseService() {
val deviceUuid: String, private val DELETABLE_ITEMS_TYPES = listOf(
val csrfToken: String, MediaItemType.MEDIA_TYPE_IMAGE,
val userId: Long, MediaItemType.MEDIA_TYPE_VIDEO,
) : BaseService() { MediaItemType.MEDIA_TYPE_SLIDER
)
private val repository: MediaRepository = retrofit.create(MediaRepository::class.java) private val repository: MediaRepository = retrofit.create(MediaRepository::class.java)
suspend fun fetch( suspend fun fetch(
@ -28,15 +29,38 @@ class MediaService private constructor(
} else response.items[0] } 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( private suspend fun action(
csrfToken: String,
userId: Long,
deviceUuid: String,
mediaId: String, mediaId: String,
action: String, action: String,
collection: String?, collection: String?,
@ -60,6 +84,9 @@ class MediaService private constructor(
} }
suspend fun editCaption( suspend fun editCaption(
csrfToken: String,
userId: Long,
deviceUuid: String,
postId: String, postId: String,
newCaption: String, newCaption: String,
): Boolean { ): Boolean {
@ -99,7 +126,12 @@ class MediaService private constructor(
return jsonObject.optString("translation") 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) { if (options.videoOptions != null) {
val videoOptions = options.videoOptions val videoOptions = options.videoOptions
if (videoOptions.clips.isEmpty()) { if (videoOptions.clips.isEmpty()) {
@ -124,6 +156,9 @@ class MediaService private constructor(
} }
suspend fun delete( suspend fun delete(
csrfToken: String,
userId: Long,
deviceUuid: String,
postId: String, postId: String,
type: MediaItemType, type: MediaItemType,
): String? { ): String? {
@ -144,26 +179,4 @@ class MediaService private constructor(
} }
return repository.delete(postId, mediaType, signedForm) 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
}
}
} }