Convert some web repo and service classes to kotlin

This commit is contained in:
Ammar Githam 2021-05-29 01:30:01 +09:00
parent b179fb66c0
commit a19d16a26e
18 changed files with 561 additions and 569 deletions

View File

@ -60,7 +60,6 @@ import awais.instagrabber.viewmodels.AppStateViewModel
import awais.instagrabber.viewmodels.DirectInboxViewModel import awais.instagrabber.viewmodels.DirectInboxViewModel
import awais.instagrabber.webservices.GraphQLService import awais.instagrabber.webservices.GraphQLService
import awais.instagrabber.webservices.MediaService import awais.instagrabber.webservices.MediaService
import awais.instagrabber.webservices.RetrofitFactory
import awais.instagrabber.webservices.ServiceCallback import awais.instagrabber.webservices.ServiceCallback
import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior
@ -300,11 +299,11 @@ class MainActivity : BaseLanguageActivity(), FragmentManager.OnBackStackChangedL
Log.e(TAG, "onDestroy: ", e) Log.e(TAG, "onDestroy: ", e)
} }
unbindActivityCheckerService() unbindActivityCheckerService()
try { // try {
RetrofitFactory.getInstance().destroy() // RetrofitFactory.getInstance().destroy()
} catch (e: Exception) { // } catch (e: Exception) {
Log.e(TAG, "onDestroy: ", e) // Log.e(TAG, "onDestroy: ", e)
} // }
instance = null instance = null
} }

View File

@ -1,155 +1,182 @@
package awais.instagrabber.repositories; package awais.instagrabber.repositories
import java.util.Map; import awais.instagrabber.repositories.responses.directmessages.*
import retrofit2.Call
import awais.instagrabber.repositories.responses.directmessages.DirectBadgeCount; import retrofit2.http.*
import awais.instagrabber.repositories.responses.directmessages.DirectInboxResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectItemSeenResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThread;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadBroadcastResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadDetailsChangeResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadFeedResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadParticipantRequestsResponse;
import awais.instagrabber.repositories.responses.directmessages.RankedRecipientsResponse;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
public interface DirectMessagesRepository {
interface DirectMessagesRepository {
@GET("/api/v1/direct_v2/inbox/") @GET("/api/v1/direct_v2/inbox/")
Call<DirectInboxResponse> fetchInbox(@QueryMap Map<String, Object> queryMap); fun fetchInbox(@QueryMap queryMap: Map<String, String>): Call<DirectInboxResponse?>
@GET("/api/v1/direct_v2/pending_inbox/") @GET("/api/v1/direct_v2/pending_inbox/")
Call<DirectInboxResponse> fetchPendingInbox(@QueryMap Map<String, Object> queryMap); fun fetchPendingInbox(@QueryMap queryMap: Map<String, String>): Call<DirectInboxResponse?>
@GET("/api/v1/direct_v2/threads/{threadId}/") @GET("/api/v1/direct_v2/threads/{threadId}/")
Call<DirectThreadFeedResponse> fetchThread(@Path("threadId") String threadId, fun fetchThread(
@QueryMap Map<String, Object> queryMap); @Path("threadId") threadId: String,
@QueryMap queryMap: Map<String, String>,
): Call<DirectThreadFeedResponse?>
@GET("/api/v1/direct_v2/get_badge_count/?no_raven=1") @GET("/api/v1/direct_v2/get_badge_count/?no_raven=1")
Call<DirectBadgeCount> fetchUnseenCount(); fun fetchUnseenCount(): Call<DirectBadgeCount?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/broadcast/{item}/") @POST("/api/v1/direct_v2/threads/broadcast/{item}/")
Call<DirectThreadBroadcastResponse> broadcast(@Path("item") String item, fun broadcast(
@FieldMap final Map<String, String> signedForm); @Path("item") item: String,
@FieldMap signedForm: Map<String, String>,
): Call<DirectThreadBroadcastResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/add_user/") @POST("/api/v1/direct_v2/threads/{threadId}/add_user/")
Call<DirectThreadDetailsChangeResponse> addUsers(@Path("threadId") String threadId, fun addUsers(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/remove_users/") @POST("/api/v1/direct_v2/threads/{threadId}/remove_users/")
Call<String> removeUsers(@Path("threadId") String threadId, fun removeUsers(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/update_title/") @POST("/api/v1/direct_v2/threads/{threadId}/update_title/")
Call<DirectThreadDetailsChangeResponse> updateTitle(@Path("threadId") String threadId, fun updateTitle(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/add_admins/") @POST("/api/v1/direct_v2/threads/{threadId}/add_admins/")
Call<String> addAdmins(@Path("threadId") String threadId, fun addAdmins(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/remove_admins/") @POST("/api/v1/direct_v2/threads/{threadId}/remove_admins/")
Call<String> removeAdmins(@Path("threadId") String threadId, fun removeAdmins(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/items/{itemId}/delete/") @POST("/api/v1/direct_v2/threads/{threadId}/items/{itemId}/delete/")
Call<String> deleteItem(@Path("threadId") String threadId, fun deleteItem(
@Path("itemId") String itemId, @Path("threadId") threadId: String,
@FieldMap final Map<String, String> form); @Path("itemId") itemId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@GET("/api/v1/direct_v2/ranked_recipients/") @GET("/api/v1/direct_v2/ranked_recipients/")
Call<RankedRecipientsResponse> rankedRecipients(@QueryMap Map<String, String> queryMap); fun rankedRecipients(@QueryMap queryMap: Map<String, String>): Call<RankedRecipientsResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/broadcast/forward/") @POST("/api/v1/direct_v2/threads/broadcast/forward/")
Call<DirectThreadBroadcastResponse> forward(@FieldMap final Map<String, String> form); fun forward(@FieldMap form: Map<String, String>): Call<DirectThreadBroadcastResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/create_group_thread/") @POST("/api/v1/direct_v2/create_group_thread/")
Call<DirectThread> createThread(@FieldMap final Map<String, String> signedForm); fun createThread(@FieldMap signedForm: Map<String, String>): Call<DirectThread?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/mute/") @POST("/api/v1/direct_v2/threads/{threadId}/mute/")
Call<String> mute(@Path("threadId") String threadId, fun mute(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/unmute/") @POST("/api/v1/direct_v2/threads/{threadId}/unmute/")
Call<String> unmute(@Path("threadId") String threadId, fun unmute(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/mute_mentions/") @POST("/api/v1/direct_v2/threads/{threadId}/mute_mentions/")
Call<String> muteMentions(@Path("threadId") String threadId, fun muteMentions(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String?>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/unmute_mentions/") @POST("/api/v1/direct_v2/threads/{threadId}/unmute_mentions/")
Call<String> unmuteMentions(@Path("threadId") String threadId, fun unmuteMentions(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@GET("/api/v1/direct_v2/threads/{threadId}/participant_requests/") @GET("/api/v1/direct_v2/threads/{threadId}/participant_requests/")
Call<DirectThreadParticipantRequestsResponse> participantRequests(@Path("threadId") String threadId, fun participantRequests(
@Query("page_size") int pageSize, @Path("threadId") threadId: String,
@Query("cursor") String cursor); @Query("page_size") pageSize: Int,
@Query("cursor") cursor: String?,
): Call<DirectThreadParticipantRequestsResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/approve_participant_requests/") @POST("/api/v1/direct_v2/threads/{threadId}/approve_participant_requests/")
Call<DirectThreadDetailsChangeResponse> approveParticipantRequests(@Path("threadId") String threadId, fun approveParticipantRequests(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/deny_participant_requests/") @POST("/api/v1/direct_v2/threads/{threadId}/deny_participant_requests/")
Call<DirectThreadDetailsChangeResponse> declineParticipantRequests(@Path("threadId") String threadId, fun declineParticipantRequests(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/approval_required_for_new_members/") @POST("/api/v1/direct_v2/threads/{threadId}/approval_required_for_new_members/")
Call<DirectThreadDetailsChangeResponse> approvalRequired(@Path("threadId") String threadId, fun approvalRequired(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/approval_not_required_for_new_members/") @POST("/api/v1/direct_v2/threads/{threadId}/approval_not_required_for_new_members/")
Call<DirectThreadDetailsChangeResponse> approvalNotRequired(@Path("threadId") String threadId, fun approvalNotRequired(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/leave/") @POST("/api/v1/direct_v2/threads/{threadId}/leave/")
Call<DirectThreadDetailsChangeResponse> leave(@Path("threadId") String threadId, fun leave(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/remove_all_users/") @POST("/api/v1/direct_v2/threads/{threadId}/remove_all_users/")
Call<DirectThreadDetailsChangeResponse> end(@Path("threadId") String threadId, fun end(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<DirectThreadDetailsChangeResponse?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/approve/") @POST("/api/v1/direct_v2/threads/{threadId}/approve/")
Call<String> approveRequest(@Path("threadId") String threadId, fun approveRequest(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/decline/") @POST("/api/v1/direct_v2/threads/{threadId}/decline/")
Call<String> declineRequest(@Path("threadId") String threadId, fun declineRequest(
@FieldMap final Map<String, String> form); @Path("threadId") threadId: String,
@FieldMap form: Map<String, String>,
): Call<String?>
@FormUrlEncoded @FormUrlEncoded
@POST("/api/v1/direct_v2/threads/{threadId}/items/{itemId}/seen/") @POST("/api/v1/direct_v2/threads/{threadId}/items/{itemId}/seen/")
Call<DirectItemSeenResponse> markItemSeen(@Path("threadId") String threadId, fun markItemSeen(
@Path("itemId") String itemId, @Path("threadId") threadId: String,
@FieldMap final Map<String, String> form); @Path("itemId") itemId: String,
@FieldMap form: Map<String, String>,
): Call<DirectItemSeenResponse?>
} }

View File

@ -32,7 +32,7 @@ public class CollectionService extends BaseService {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
this.csrfToken = csrfToken; this.csrfToken = csrfToken;
this.userId = userId; this.userId = userId;
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(CollectionRepository.class); .create(CollectionRepository.class);
} }

View File

@ -1,476 +1,483 @@
package awais.instagrabber.webservices; package awais.instagrabber.webservices
import androidx.annotation.NonNull; import awais.instagrabber.repositories.DirectMessagesRepository
import androidx.annotation.Nullable; import awais.instagrabber.repositories.requests.directmessages.*
import awais.instagrabber.repositories.responses.directmessages.*
import awais.instagrabber.repositories.responses.giphy.GiphyGif
import awais.instagrabber.utils.TextUtils.extractUrls
import awais.instagrabber.utils.TextUtils.isEmpty
import awais.instagrabber.utils.Utils
import org.json.JSONArray
import retrofit2.Call
import java.util.*
import com.google.common.collect.ImmutableMap; class DirectMessagesService private constructor(
val csrfToken: String,
val userId: Long,
val deviceUuid: String,
) : BaseService() {
private val repository: DirectMessagesRepository = RetrofitFactory.retrofit.create(DirectMessagesRepository::class.java)
import org.json.JSONArray; fun fetchInbox(
cursor: String?,
import java.util.Collection; seqId: Long,
import java.util.HashMap; ): Call<DirectInboxResponse?> {
import java.util.List; val queryMap = mutableMapOf(
import java.util.Map; "visual_message_return_type" to "unseen",
import java.util.Objects; "thread_message_limit" to 10.toString(),
import java.util.UUID; "persistentBadging" to true.toString(),
import java.util.stream.Collectors; "limit" to 10.toString(),
)
import awais.instagrabber.repositories.DirectMessagesRepository; if (!cursor.isNullOrBlank()) {
import awais.instagrabber.repositories.requests.directmessages.AnimatedMediaBroadcastOptions; queryMap["cursor"] = cursor
import awais.instagrabber.repositories.requests.directmessages.BroadcastOptions; queryMap["direction"] = "older"
import awais.instagrabber.repositories.requests.directmessages.LinkBroadcastOptions; }
import awais.instagrabber.repositories.requests.directmessages.MediaShareBroadcastOptions; if (seqId != 0L) {
import awais.instagrabber.repositories.requests.directmessages.PhotoBroadcastOptions; queryMap["seq_id"] = seqId.toString()
import awais.instagrabber.repositories.requests.directmessages.ReactionBroadcastOptions; }
import awais.instagrabber.repositories.requests.directmessages.StoryReplyBroadcastOptions; return repository.fetchInbox(queryMap)
import awais.instagrabber.repositories.requests.directmessages.TextBroadcastOptions;
import awais.instagrabber.repositories.requests.directmessages.ThreadIdOrUserIds;
import awais.instagrabber.repositories.requests.directmessages.VideoBroadcastOptions;
import awais.instagrabber.repositories.requests.directmessages.VoiceBroadcastOptions;
import awais.instagrabber.repositories.responses.directmessages.DirectBadgeCount;
import awais.instagrabber.repositories.responses.directmessages.DirectInboxResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectItem;
import awais.instagrabber.repositories.responses.directmessages.DirectItemSeenResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThread;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadBroadcastResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadDetailsChangeResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadFeedResponse;
import awais.instagrabber.repositories.responses.directmessages.DirectThreadParticipantRequestsResponse;
import awais.instagrabber.repositories.responses.directmessages.RankedRecipientsResponse;
import awais.instagrabber.repositories.responses.giphy.GiphyGif;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils;
import retrofit2.Call;
public class DirectMessagesService extends BaseService {
private static final String TAG = "DiscoverService";
private static DirectMessagesService instance;
private final DirectMessagesRepository repository;
private final String csrfToken;
private final long userId;
private final String deviceUuid;
private DirectMessagesService(@NonNull final String csrfToken,
final long userId,
@NonNull final String deviceUuid) {
this.csrfToken = csrfToken;
this.userId = userId;
this.deviceUuid = deviceUuid;
repository = RetrofitFactory.getInstance()
.getRetrofit()
.create(DirectMessagesRepository.class);
} }
public String getCsrfToken() { fun fetchThread(
return csrfToken; threadId: String,
cursor: String?,
): Call<DirectThreadFeedResponse?> {
val queryMap = mutableMapOf(
"visual_message_return_type" to "unseen",
"limit" to 20.toString(),
"direction" to "older",
)
if (!cursor.isNullOrBlank()) {
queryMap["cursor"] = cursor
}
return repository.fetchThread(threadId, queryMap)
} }
public long getUserId() { fun fetchUnseenCount(): Call<DirectBadgeCount?> {
return userId; return repository.fetchUnseenCount()
} }
public String getDeviceUuid() { fun broadcastText(
return deviceUuid; clientContext: String,
threadIdOrUserIds: ThreadIdOrUserIds,
text: String,
repliedToItemId: String?,
repliedToClientContext: String?,
): Call<DirectThreadBroadcastResponse?> {
val urls = extractUrls(text)
if (urls.isNotEmpty()) {
return broadcastLink(clientContext, threadIdOrUserIds, text, urls, repliedToItemId, repliedToClientContext)
}
val broadcastOptions = TextBroadcastOptions(clientContext, threadIdOrUserIds, text)
if (!repliedToItemId.isNullOrBlank() && !repliedToClientContext.isNullOrBlank()) {
broadcastOptions.repliedToItemId = repliedToItemId
broadcastOptions.repliedToClientContext = repliedToClientContext
}
return broadcast(broadcastOptions)
} }
public static DirectMessagesService getInstance(@NonNull final String csrfToken, private fun broadcastLink(
final long userId, clientContext: String,
@NonNull final String deviceUuid) { threadIdOrUserIds: ThreadIdOrUserIds,
if (instance == null linkText: String,
|| !Objects.equals(instance.getCsrfToken(), csrfToken) urls: List<String>,
|| !Objects.equals(instance.getUserId(), userId) repliedToItemId: String?,
|| !Objects.equals(instance.getDeviceUuid(), deviceUuid)) { repliedToClientContext: String?,
instance = new DirectMessagesService(csrfToken, userId, deviceUuid); ): Call<DirectThreadBroadcastResponse?> {
val broadcastOptions = LinkBroadcastOptions(clientContext, threadIdOrUserIds, linkText, urls)
if (!repliedToItemId.isNullOrBlank() && !repliedToClientContext.isNullOrBlank()) {
broadcastOptions.repliedToItemId = repliedToItemId
broadcastOptions.repliedToClientContext = repliedToClientContext
} }
return instance; return broadcast(broadcastOptions)
} }
public Call<DirectInboxResponse> fetchInbox(final String cursor, fun broadcastPhoto(
final long seqId) { clientContext: String,
final ImmutableMap.Builder<String, Object> queryMapBuilder = ImmutableMap.<String, Object>builder() threadIdOrUserIds: ThreadIdOrUserIds,
.put("visual_message_return_type", "unseen") uploadId: String,
.put("thread_message_limit", 10) ): Call<DirectThreadBroadcastResponse?> {
.put("persistentBadging", true) return broadcast(PhotoBroadcastOptions(clientContext, threadIdOrUserIds, true, uploadId))
.put("limit", 10);
if (!TextUtils.isEmpty(cursor)) {
queryMapBuilder.put("cursor", cursor);
queryMapBuilder.put("direction", "older");
}
if (seqId != 0) {
queryMapBuilder.put("seq_id", seqId);
}
return repository.fetchInbox(queryMapBuilder.build());
} }
public Call<DirectThreadFeedResponse> fetchThread(final String threadId, fun broadcastVideo(
final String cursor) { clientContext: String,
final ImmutableMap.Builder<String, Object> queryMapBuilder = ImmutableMap.<String, Object>builder() threadIdOrUserIds: ThreadIdOrUserIds,
.put("visual_message_return_type", "unseen") uploadId: String,
.put("limit", 20) videoResult: String,
.put("direction", "older"); sampled: Boolean,
if (!TextUtils.isEmpty(cursor)) { ): Call<DirectThreadBroadcastResponse?> {
queryMapBuilder.put("cursor", cursor); return broadcast(VideoBroadcastOptions(clientContext, threadIdOrUserIds, videoResult, uploadId, sampled))
}
return repository.fetchThread(threadId, queryMapBuilder.build());
} }
public Call<DirectBadgeCount> fetchUnseenCount() { fun broadcastVoice(
return repository.fetchUnseenCount(); clientContext: String,
threadIdOrUserIds: ThreadIdOrUserIds,
uploadId: String,
waveform: List<Float>,
samplingFreq: Int,
): Call<DirectThreadBroadcastResponse?> {
return broadcast(VoiceBroadcastOptions(clientContext, threadIdOrUserIds, uploadId, waveform, samplingFreq))
} }
public Call<DirectThreadBroadcastResponse> broadcastText(@NonNull final String clientContext, fun broadcastStoryReply(
@NonNull final ThreadIdOrUserIds threadIdOrUserIds, threadIdOrUserIds: ThreadIdOrUserIds,
@NonNull final String text, text: String,
@Nullable final String repliedToItemId, mediaId: String,
@Nullable final String repliedToClientContext) { reelId: String,
final List<String> urls = TextUtils.extractUrls(text); ): Call<DirectThreadBroadcastResponse?> {
if (!urls.isEmpty()) { return broadcast(StoryReplyBroadcastOptions(UUID.randomUUID().toString(), threadIdOrUserIds, text, mediaId, reelId))
return broadcastLink(clientContext, threadIdOrUserIds, text, urls, repliedToItemId, repliedToClientContext);
}
final TextBroadcastOptions broadcastOptions = new TextBroadcastOptions(clientContext, threadIdOrUserIds, text);
if (repliedToItemId != null && repliedToClientContext != null) {
broadcastOptions.setRepliedToItemId(repliedToItemId);
broadcastOptions.setRepliedToClientContext(repliedToClientContext);
}
return broadcast(broadcastOptions);
} }
public Call<DirectThreadBroadcastResponse> broadcastLink(@NonNull final String clientContext, fun broadcastReaction(
@NonNull final ThreadIdOrUserIds threadIdOrUserIds, clientContext: String,
@NonNull final String linkText, threadIdOrUserIds: ThreadIdOrUserIds,
@NonNull final List<String> urls, itemId: String,
@Nullable final String repliedToItemId, emoji: String?,
@Nullable final String repliedToClientContext) { delete: Boolean,
final LinkBroadcastOptions broadcastOptions = new LinkBroadcastOptions(clientContext, threadIdOrUserIds, linkText, urls); ): Call<DirectThreadBroadcastResponse?> {
if (repliedToItemId != null && repliedToClientContext != null) { return broadcast(ReactionBroadcastOptions(clientContext, threadIdOrUserIds, itemId, emoji, delete))
broadcastOptions.setRepliedToItemId(repliedToItemId);
broadcastOptions.setRepliedToClientContext(repliedToClientContext);
}
return broadcast(broadcastOptions);
} }
public Call<DirectThreadBroadcastResponse> broadcastPhoto(@NonNull final String clientContext, fun broadcastAnimatedMedia(
@NonNull final ThreadIdOrUserIds threadIdOrUserIds, clientContext: String,
@NonNull final String uploadId) { threadIdOrUserIds: ThreadIdOrUserIds,
return broadcast(new PhotoBroadcastOptions(clientContext, threadIdOrUserIds, true, uploadId)); giphyGif: GiphyGif,
): Call<DirectThreadBroadcastResponse?> {
return broadcast(AnimatedMediaBroadcastOptions(clientContext, threadIdOrUserIds, giphyGif))
} }
public Call<DirectThreadBroadcastResponse> broadcastVideo(@NonNull final String clientContext, fun broadcastMediaShare(
@NonNull final ThreadIdOrUserIds threadIdOrUserIds, clientContext: String,
@NonNull final String uploadId, threadIdOrUserIds: ThreadIdOrUserIds,
@NonNull final String videoResult, mediaId: String,
final boolean sampled) { ): Call<DirectThreadBroadcastResponse?> {
return broadcast(new VideoBroadcastOptions(clientContext, threadIdOrUserIds, videoResult, uploadId, sampled)); return broadcast(MediaShareBroadcastOptions(clientContext, threadIdOrUserIds, mediaId))
} }
public Call<DirectThreadBroadcastResponse> broadcastVoice(@NonNull final String clientContext, private fun broadcast(broadcastOptions: BroadcastOptions): Call<DirectThreadBroadcastResponse?> {
@NonNull final ThreadIdOrUserIds threadIdOrUserIds, require(!isEmpty(broadcastOptions.clientContext)) { "Broadcast requires a valid client context value" }
@NonNull final String uploadId, val form = mutableMapOf<String, Any>()
@NonNull final List<Float> waveform, val threadId = broadcastOptions.threadId
final int samplingFreq) { if (!threadId.isNullOrBlank()) {
return broadcast(new VoiceBroadcastOptions(clientContext, threadIdOrUserIds, uploadId, waveform, samplingFreq)); form["thread_id"] = threadId
}
public Call<DirectThreadBroadcastResponse> broadcastStoryReply(@NonNull final ThreadIdOrUserIds threadIdOrUserIds,
@NonNull final String text,
@NonNull final String mediaId,
@NonNull final String reelId) {
return broadcast(new StoryReplyBroadcastOptions(UUID.randomUUID().toString(), threadIdOrUserIds, text, mediaId, reelId));
}
public Call<DirectThreadBroadcastResponse> broadcastReaction(@NonNull final String clientContext,
@NonNull final ThreadIdOrUserIds threadIdOrUserIds,
@NonNull final String itemId,
@Nullable final String emoji,
final boolean delete) {
return broadcast(new ReactionBroadcastOptions(clientContext, threadIdOrUserIds, itemId, emoji, delete));
}
public Call<DirectThreadBroadcastResponse> broadcastAnimatedMedia(@NonNull final String clientContext,
@NonNull final ThreadIdOrUserIds threadIdOrUserIds,
@NonNull final GiphyGif giphyGif) {
return broadcast(new AnimatedMediaBroadcastOptions(clientContext, threadIdOrUserIds, giphyGif));
}
public Call<DirectThreadBroadcastResponse> broadcastMediaShare(@NonNull final String clientContext,
@NonNull final ThreadIdOrUserIds threadIdOrUserIds,
@NonNull final String mediaId) {
return broadcast(new MediaShareBroadcastOptions(clientContext, threadIdOrUserIds, mediaId));
}
private Call<DirectThreadBroadcastResponse> broadcast(@NonNull final BroadcastOptions broadcastOptions) {
if (TextUtils.isEmpty(broadcastOptions.getClientContext())) {
throw new IllegalArgumentException("Broadcast requires a valid client context value");
}
final Map<String, Object> form = new HashMap<>();
if (!TextUtils.isEmpty(broadcastOptions.getThreadId())) {
form.put("thread_id", broadcastOptions.getThreadId());
} else { } else {
form.put("recipient_users", new JSONArray(broadcastOptions.getUserIds()).toString()); val userIds = broadcastOptions.userIds
require(!userIds.isNullOrEmpty()) {
"Either provide a thread id or pass a list of user ids"
} }
form.put("_csrftoken", csrfToken); form["recipient_users"] = JSONArray(userIds).toString()
form.put("_uid", userId);
form.put("__uuid", deviceUuid);
form.put("client_context", broadcastOptions.getClientContext());
form.put("mutation_token", broadcastOptions.getClientContext());
if (!TextUtils.isEmpty(broadcastOptions.getRepliedToItemId()) && !TextUtils.isEmpty(broadcastOptions.getRepliedToClientContext())) {
form.put("replied_to_item_id", broadcastOptions.getRepliedToItemId());
form.put("replied_to_client_context", broadcastOptions.getRepliedToClientContext());
} }
form.putAll(broadcastOptions.getFormMap()); form["_csrftoken"] = csrfToken
form.put("action", "send_item"); form["_uid"] = userId
final Map<String, String> signedForm = Utils.sign(form); form["__uuid"] = deviceUuid
return repository.broadcast(broadcastOptions.getItemType().getValue(), signedForm); form["client_context"] = broadcastOptions.clientContext
form["mutation_token"] = broadcastOptions.clientContext
val repliedToItemId = broadcastOptions.repliedToItemId
val repliedToClientContext = broadcastOptions.repliedToClientContext
if (!repliedToItemId.isNullOrBlank() && !repliedToClientContext.isNullOrBlank()) {
form["replied_to_item_id"] = repliedToItemId
form["replied_to_client_context"] = repliedToClientContext
}
form.putAll(broadcastOptions.formMap)
form["action"] = "send_item"
val signedForm = Utils.sign(form)
return repository.broadcast(broadcastOptions.itemType.value, signedForm)
} }
public Call<DirectThreadDetailsChangeResponse> addUsers(final String threadId, fun addUsers(
final Collection<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: Collection<Long>,
"_csrftoken", csrfToken, ): Call<DirectThreadDetailsChangeResponse?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.addUsers(threadId, form); "user_ids" to JSONArray(userIds).toString(),
)
return repository.addUsers(threadId, form)
} }
public Call<String> removeUsers(final String threadId, fun removeUsers(
final Collection<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: Collection<Long>,
"_csrftoken", csrfToken, ): Call<String?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.removeUsers(threadId, form); "user_ids" to JSONArray(userIds).toString(),
)
return repository.removeUsers(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> updateTitle(final String threadId, fun updateTitle(
final String title) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( title: String,
"_csrftoken", csrfToken, ): Call<DirectThreadDetailsChangeResponse?> {
"_uuid", deviceUuid, val form = mapOf(
"title", title "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.updateTitle(threadId, form); "title" to title,
)
return repository.updateTitle(threadId, form)
} }
public Call<String> addAdmins(final String threadId, fun addAdmins(
final Collection<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: Collection<Long>,
"_csrftoken", csrfToken, ): Call<String?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.addAdmins(threadId, form); "user_ids" to JSONArray(userIds).toString(),
)
return repository.addAdmins(threadId, form)
} }
public Call<String> removeAdmins(final String threadId, fun removeAdmins(
final Collection<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: Collection<Long>,
"_csrftoken", csrfToken, ): Call<String?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.removeAdmins(threadId, form); "user_ids" to JSONArray(userIds).toString(),
)
return repository.removeAdmins(threadId, form)
} }
public Call<String> deleteItem(final String threadId, fun deleteItem(
final String itemId) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( itemId: String,
"_csrftoken", csrfToken, ): Call<String?> {
"_uuid", deviceUuid val form = mapOf(
); "_csrftoken" to csrfToken,
return repository.deleteItem(threadId, itemId, form); "_uuid" to deviceUuid,
)
return repository.deleteItem(threadId, itemId, form)
} }
public Call<RankedRecipientsResponse> rankedRecipients(@Nullable final String mode, fun rankedRecipients(
@Nullable final Boolean showThreads, mode: String?,
@Nullable final String query) { showThreads: Boolean?,
query: String?,
): Call<RankedRecipientsResponse?> {
// String correctedMode = mode; // String correctedMode = mode;
// if (TextUtils.isEmpty(mode) || (!mode.equals("raven") && !mode.equals("reshare"))) { // if (TextUtils.isEmpty(mode) || (!mode.equals("raven") && !mode.equals("reshare"))) {
// correctedMode = "raven"; // correctedMode = "raven";
// } // }
final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); val queryMap = mutableMapOf<String, String>()
if (mode != null) { if (!mode.isNullOrBlank()) {
builder.put("mode", mode); queryMap["mode"] = mode
} }
if (query != null) { if (!query.isNullOrBlank()) {
builder.put("query", query); queryMap["query"] = query
} }
if (showThreads != null) { if (showThreads != null) {
builder.put("showThreads", String.valueOf(showThreads)); queryMap["showThreads"] = showThreads.toString()
} }
return repository.rankedRecipients(builder.build()); return repository.rankedRecipients(queryMap)
} }
public Call<DirectThreadBroadcastResponse> forward(@NonNull final String toThreadId, fun forward(
@NonNull final String itemType, toThreadId: String,
@NonNull final String fromThreadId, itemType: String,
@NonNull final String itemId) { fromThreadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( itemId: String,
"action", "forward_item", ): Call<DirectThreadBroadcastResponse?> {
"thread_id", toThreadId, val form = mapOf(
"item_type", itemType, "action" to "forward_item",
"forwarded_from_thread_id", fromThreadId, "thread_id" to toThreadId,
"forwarded_from_thread_item_id", itemId "item_type" to itemType,
); "forwarded_from_thread_id" to fromThreadId,
return repository.forward(form); "forwarded_from_thread_item_id" to itemId,
)
return repository.forward(form)
} }
public Call<DirectThread> createThread(@NonNull final List<Long> userIds, fun createThread(
@Nullable final String threadTitle) { userIds: List<Long>,
final List<String> userIdStringList = userIds.stream() threadTitle: String?,
.filter(Objects::nonNull) ): Call<DirectThread?> {
.map(String::valueOf) val userIdStringList = userIds.asSequence()
.collect(Collectors.toList()); .filterNotNull()
final ImmutableMap.Builder<String, Object> formBuilder = ImmutableMap.<String, Object>builder() .map { it.toString() }
.put("_csrftoken", csrfToken) val form = mutableMapOf<String, Any>(
.put("_uuid", deviceUuid) "_csrftoken" to csrfToken,
.put("_uid", userId) "_uuid" to deviceUuid,
.put("recipient_users", new JSONArray(userIdStringList).toString()); "_uid" to userId,
if (threadTitle != null) { "recipient_users" to JSONArray(userIdStringList).toString(),
formBuilder.put("thread_title", threadTitle); )
if (!threadTitle.isNullOrBlank()) {
form["thread_title"] = threadTitle
} }
final Map<String, String> signedForm = Utils.sign(formBuilder.build()); val signedForm = Utils.sign(form)
return repository.createThread(signedForm); return repository.createThread(signedForm)
} }
public Call<String> mute(@NonNull final String threadId) { fun mute(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid
); )
return repository.mute(threadId, form); return repository.mute(threadId, form)
} }
public Call<String> unmute(@NonNull final String threadId) { fun unmute(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.unmute(threadId, form); return repository.unmute(threadId, form)
} }
public Call<String> muteMentions(@NonNull final String threadId) { fun muteMentions(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.muteMentions(threadId, form); return repository.muteMentions(threadId, form)
} }
public Call<String> unmuteMentions(@NonNull final String threadId) { fun unmuteMentions(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.unmuteMentions(threadId, form); return repository.unmuteMentions(threadId, form)
} }
public Call<DirectThreadParticipantRequestsResponse> participantRequests(@NonNull final String threadId, fun participantRequests(
final int pageSize, threadId: String,
@Nullable final String cursor) { pageSize: Int,
return repository.participantRequests(threadId, pageSize, cursor); cursor: String?,
): Call<DirectThreadParticipantRequestsResponse?> {
return repository.participantRequests(threadId, pageSize, cursor)
} }
public Call<DirectThreadDetailsChangeResponse> approveParticipantRequests(@NonNull final String threadId, fun approveParticipantRequests(
@NonNull final List<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: List<Long>,
"_csrftoken", csrfToken, ): Call<DirectThreadDetailsChangeResponse?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
// , "share_join_chat_story", String.valueOf(true) "_uuid" to deviceUuid,
); "user_ids" to JSONArray(userIds).toString(),
return repository.approveParticipantRequests(threadId, form); // "share_join_chat_story" to String.valueOf(true)
)
return repository.approveParticipantRequests(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> declineParticipantRequests(@NonNull final String threadId, fun declineParticipantRequests(
@NonNull final List<Long> userIds) { threadId: String,
final ImmutableMap<String, String> form = ImmutableMap.of( userIds: List<Long>,
"_csrftoken", csrfToken, ): Call<DirectThreadDetailsChangeResponse?> {
"_uuid", deviceUuid, val form = mapOf(
"user_ids", new JSONArray(userIds).toString() "_csrftoken" to csrfToken,
); "_uuid" to deviceUuid,
return repository.declineParticipantRequests(threadId, form); "user_ids" to JSONArray(userIds).toString(),
)
return repository.declineParticipantRequests(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> approvalRequired(@NonNull final String threadId) { fun approvalRequired(threadId: String): Call<DirectThreadDetailsChangeResponse?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.approvalRequired(threadId, form); return repository.approvalRequired(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> approvalNotRequired(@NonNull final String threadId) { fun approvalNotRequired(threadId: String): Call<DirectThreadDetailsChangeResponse?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.approvalNotRequired(threadId, form); return repository.approvalNotRequired(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> leave(@NonNull final String threadId) { fun leave(threadId: String): Call<DirectThreadDetailsChangeResponse?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.leave(threadId, form); return repository.leave(threadId, form)
} }
public Call<DirectThreadDetailsChangeResponse> end(@NonNull final String threadId) { fun end(threadId: String): Call<DirectThreadDetailsChangeResponse?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.end(threadId, form); return repository.end(threadId, form)
} }
public Call<DirectInboxResponse> fetchPendingInbox(final String cursor, final long seqId) { fun fetchPendingInbox(cursor: String?, seqId: Long): Call<DirectInboxResponse?> {
final ImmutableMap.Builder<String, Object> queryMapBuilder = ImmutableMap.<String, Object>builder() val queryMap = mutableMapOf(
.put("visual_message_return_type", "unseen") "visual_message_return_type" to "unseen",
.put("thread_message_limit", 20) "thread_message_limit" to 20.toString(),
.put("persistentBadging", true) "persistentBadging" to true.toString(),
.put("limit", 10); "limit" to 10.toString(),
if (!TextUtils.isEmpty(cursor)) { )
queryMapBuilder.put("cursor", cursor); if (!cursor.isNullOrBlank()) {
queryMapBuilder.put("direction", "older"); queryMap["cursor"] = cursor
queryMap["direction"] = "older"
} }
if (seqId != 0) { if (seqId != 0L) {
queryMapBuilder.put("seq_id", seqId); queryMap["seq_id"] = seqId.toString()
} }
return repository.fetchPendingInbox(queryMapBuilder.build()); return repository.fetchPendingInbox(queryMap)
} }
public Call<String> approveRequest(@NonNull final String threadId) { fun approveRequest(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.approveRequest(threadId, form); return repository.approveRequest(threadId, form)
} }
public Call<String> declineRequest(@NonNull final String threadId) { fun declineRequest(threadId: String): Call<String?> {
final ImmutableMap<String, String> form = ImmutableMap.of( val form = mapOf(
"_csrftoken", csrfToken, "_csrftoken" to csrfToken,
"_uuid", deviceUuid "_uuid" to deviceUuid,
); )
return repository.declineRequest(threadId, form); return repository.declineRequest(threadId, form)
} }
@Nullable fun markAsSeen(
public Call<DirectItemSeenResponse> markAsSeen(@NonNull final String threadId, threadId: String,
@NonNull final DirectItem directItem) { directItem: DirectItem,
if (directItem.getItemId() == null) return null; ): Call<DirectItemSeenResponse?>? {
final ImmutableMap<String, String> form = ImmutableMap.<String, String>builder() val itemId = directItem.itemId ?: return null
.put("_csrftoken", csrfToken) val form = mapOf(
.put("_uuid", deviceUuid) "_csrftoken" to csrfToken,
.put("use_unified_inbox", "true") "_uuid" to deviceUuid,
.put("action", "mark_seen") "use_unified_inbox" to "true",
.put("thread_id", threadId) "action" to "mark_seen",
.put("item_id", directItem.getItemId()) "thread_id" to threadId,
.build(); "item_id" to itemId,
return repository.markItemSeen(threadId, directItem.getItemId(), form); )
return repository.markItemSeen(threadId, itemId, form)
}
companion object {
private lateinit var instance: DirectMessagesService
@JvmStatic
fun getInstance(
csrfToken: String,
userId: Long,
deviceUuid: String,
): DirectMessagesService {
if (!this::instance.isInitialized
|| instance.csrfToken != csrfToken
|| instance.userId != userId
|| instance.deviceUuid != deviceUuid
) {
instance = DirectMessagesService(csrfToken, userId, deviceUuid)
}
return instance
} }
} }
}

View File

@ -22,7 +22,7 @@ public class DiscoverService extends BaseService {
private static DiscoverService instance; private static DiscoverService instance;
private DiscoverService() { private DiscoverService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(DiscoverRepository.class); .create(DiscoverRepository.class);
} }

View File

@ -31,7 +31,7 @@ public class FeedService extends BaseService {
private static FeedService instance; private static FeedService instance;
private FeedService() { private FeedService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(FeedRepository.class); .create(FeedRepository.class);
} }

View File

@ -41,7 +41,7 @@ public class FriendshipService extends BaseService {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
this.csrfToken = csrfToken; this.csrfToken = csrfToken;
this.userId = userId; this.userId = userId;
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(FriendshipRepository.class); .create(FriendshipRepository.class);
} }

View File

@ -11,7 +11,7 @@ public class GifService extends BaseService {
private static GifService instance; private static GifService instance;
private GifService() { private GifService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(GifRepository.class); .create(GifRepository.class);
} }

View File

@ -40,7 +40,7 @@ public class GraphQLService extends BaseService {
private static GraphQLService instance; private static GraphQLService instance;
private GraphQLService() { private GraphQLService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofitWeb() .getRetrofitWeb()
.create(GraphQLRepository.class); .create(GraphQLRepository.class);
} }

View File

@ -22,7 +22,7 @@ public class LocationService extends BaseService {
private static LocationService instance; private static LocationService instance;
private LocationService() { private LocationService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(LocationRepository.class); .create(LocationRepository.class);
} }

View File

@ -54,7 +54,7 @@ public class MediaService extends BaseService {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
this.csrfToken = csrfToken; this.csrfToken = csrfToken;
this.userId = userId; this.userId = userId;
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(MediaRepository.class); .create(MediaRepository.class);
} }

View File

@ -31,7 +31,7 @@ public class NewsService extends BaseService {
private static NewsService instance; private static NewsService instance;
private NewsService() { private NewsService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(NewsRepository.class); .create(NewsRepository.class);
} }

View File

@ -32,7 +32,7 @@ public class ProfileService extends BaseService {
private static ProfileService instance; private static ProfileService instance;
private ProfileService() { private ProfileService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(ProfileRepository.class); .create(ProfileRepository.class);
} }

View File

@ -1,98 +1,57 @@
package awais.instagrabber.webservices; package awais.instagrabber.webservices
import com.google.gson.FieldNamingPolicy; import awais.instagrabber.BuildConfig
import com.google.gson.Gson; import awais.instagrabber.repositories.responses.Caption
import com.google.gson.GsonBuilder; import awais.instagrabber.repositories.serializers.CaptionDeserializer
import awais.instagrabber.utils.Utils
import awais.instagrabber.webservices.interceptors.AddCookiesInterceptor
import awais.instagrabber.webservices.interceptors.IgErrorsInterceptor
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.io.File; object RetrofitFactory {
private const val cacheSize: Long = 10 * 1024 * 1024 // 10 MB
private val cache = Cache(File(Utils.cacheDir), cacheSize)
private val igErrorsInterceptor: IgErrorsInterceptor by lazy { IgErrorsInterceptor() }
import awais.instagrabber.BuildConfig; private val retrofitBuilder: Retrofit.Builder by lazy {
import awais.instagrabber.repositories.responses.Caption; val clientBuilder = OkHttpClient.Builder().apply {
import awais.instagrabber.repositories.serializers.CaptionDeserializer; followRedirects(false)
import awais.instagrabber.utils.Utils; followSslRedirects(false)
import awais.instagrabber.webservices.interceptors.AddCookiesInterceptor; cache(cache)
import awais.instagrabber.webservices.interceptors.IgErrorsInterceptor; addInterceptor(AddCookiesInterceptor())
import okhttp3.Cache; addInterceptor(igErrorsInterceptor)
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public final class RetrofitFactory {
private static final Object LOCK = new Object();
private static RetrofitFactory instance;
private final int cacheSize = 10 * 1024 * 1024; // 10 MB
private final Cache cache = new Cache(new File(Utils.cacheDir), cacheSize);
private IgErrorsInterceptor igErrorsInterceptor;
private Retrofit.Builder builder;
private Retrofit retrofit;
private Retrofit retrofitWeb;
public static RetrofitFactory getInstance() {
if (instance == null) {
synchronized (LOCK) {
if (instance == null) {
instance = new RetrofitFactory();
}
}
}
return instance;
}
private Retrofit.Builder getRetrofitBuilder() {
if (builder == null) {
igErrorsInterceptor = new IgErrorsInterceptor();
final OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
.cache(cache);
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
// clientBuilder.addInterceptor(new LoggingInterceptor()); // addInterceptor(new LoggingInterceptor());
} }
clientBuilder.addInterceptor(new AddCookiesInterceptor())
.addInterceptor(igErrorsInterceptor);
final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Caption.class, new CaptionDeserializer())
.setLenient()
.create();
builder = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(clientBuilder.build());
} }
return builder; val gson = GsonBuilder().apply {
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
registerTypeAdapter(Caption::class.java, CaptionDeserializer())
setLenient()
}.create()
Retrofit.Builder().apply {
addConverterFactory(ScalarsConverterFactory.create())
addConverterFactory(GsonConverterFactory.create(gson))
client(clientBuilder.build())
}
} }
public Retrofit getRetrofit() { val retrofit: Retrofit by lazy {
if (retrofit == null) { retrofitBuilder
retrofit = getRetrofitBuilder()
.baseUrl("https://i.instagram.com") .baseUrl("https://i.instagram.com")
.build(); .build()
}
return retrofit;
} }
public Retrofit getRetrofitWeb() { val retrofitWeb: Retrofit by lazy {
if (retrofitWeb == null) { retrofitBuilder
retrofitWeb = getRetrofitBuilder()
.baseUrl("https://www.instagram.com") .baseUrl("https://www.instagram.com")
.build(); .build()
}
return retrofitWeb;
}
public void destroy() {
if (igErrorsInterceptor != null) {
igErrorsInterceptor.destroy();
}
igErrorsInterceptor = null;
retrofit = null;
retrofitWeb = null;
builder = null;
instance = null;
} }
} }

View File

@ -14,7 +14,7 @@ public class SearchService extends BaseService {
private static SearchService instance; private static SearchService instance;
private SearchService() { private SearchService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofitWeb() .getRetrofitWeb()
.create(SearchRepository.class); .create(SearchRepository.class);
} }

View File

@ -49,7 +49,7 @@ public class StoriesService extends BaseService {
this.csrfToken = csrfToken; this.csrfToken = csrfToken;
this.userId = userId; this.userId = userId;
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(StoriesRepository.class); .create(StoriesRepository.class);
} }

View File

@ -31,7 +31,7 @@ public class TagsService extends BaseService {
private final TagsRepository repository; private final TagsRepository repository;
private TagsService() { private TagsService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(TagsRepository.class); .create(TagsRepository.class);
} }

View File

@ -21,7 +21,7 @@ public class UserService extends BaseService {
private static UserService instance; private static UserService instance;
private UserService() { private UserService() {
repository = RetrofitFactory.getInstance() repository = RetrofitFactory.INSTANCE
.getRetrofit() .getRetrofit()
.create(UserRepository.class); .create(UserRepository.class);
} }