/// <summary> /// Get following list by username asynchronously /// </summary> /// <param name="username">Username</param> /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param> /// <param name="searchQuery">Search string to locate specific followings</param> /// <returns> /// <see cref="InstaUserShortList" /> /// </returns> public async Task <IResult <InstaUserShortList> > GetUserFollowingAsync(string username, PaginationParameters paginationParameters, string searchQuery) { UserAuthValidator.Validate(_userAuthValidate); var following = new InstaUserShortList(); try { var user = await GetUserAsync(username); var uri = UriCreator.GetUserFollowingUri(user.Value.Pk, _user.RankToken, searchQuery, paginationParameters.NextId); var userListResponse = await GetUserListByUriAsync(uri); if (!userListResponse.Succeeded) { return(Result.Fail(userListResponse.Info, (InstaUserShortList)null)); } following.AddRange( userListResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter) .Select(converter => converter.Convert())); following.NextMaxId = userListResponse.Value.NextMaxId; var pages = 1; while (!string.IsNullOrEmpty(following.NextMaxId) && pages < paginationParameters.MaximumPagesToLoad) { var nextUri = UriCreator.GetUserFollowingUri(user.Value.Pk, _user.RankToken, searchQuery, userListResponse.Value.NextMaxId); userListResponse = await GetUserListByUriAsync(nextUri); if (!userListResponse.Succeeded) { return(Result.Fail(userListResponse.Info, following)); } following.AddRange( userListResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter) .Select(converter => converter.Convert())); pages++; following.NextMaxId = userListResponse.Value.NextMaxId; } return(Result.Success(following)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, following)); } }
/// <summary> /// Configure story photo /// </summary> /// <param name="image">Photo to configure</param> /// <param name="uploadId">Upload id</param> /// <param name="caption">Caption</param> private async Task <IResult <InstaStoryMedia> > ConfigureStoryPhotoAsync(Action <InstaUploaderProgress> progress, InstaUploaderProgress upProgress, InstaImage image, string uploadId, string caption) { try { upProgress.UploadState = InstaUploadState.Configuring; progress?.Invoke(upProgress); var instaUri = UriCreator.GetStoryConfigureUri(); var data = new JObject { { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "_uid", _user.LoggedInUser.Pk }, { "_csrftoken", _user.CsrfToken }, { "source_type", "1" }, { "caption", caption }, { "upload_id", uploadId }, { "edits", new JObject() }, { "disable_comments", false }, { "configure_mode", 1 }, { "camera_position", "unknown" } }; var request = HttpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var mediaResponse = JsonConvert.DeserializeObject <InstaStoryMediaResponse>(json); var converter = ConvertersFabric.Instance.GetStoryMediaConverter(mediaResponse); var obj = converter.Convert(); upProgress.UploadState = InstaUploadState.Configured; progress?.Invoke(upProgress); upProgress.UploadState = InstaUploadState.Completed; progress?.Invoke(upProgress); return(Result.Success(obj)); } upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } catch (Exception exception) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); _logger?.LogException(exception); return(Result.Fail <InstaStoryMedia>(exception.Message)); } }
/// <summary> /// Get user timeline feed (feed of recent posts from users you follow) asynchronously. /// </summary> /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param> /// <returns> /// <see cref="InstaFeed" /> /// </returns> public async Task <IResult <InstaFeed> > GetUserTimelineFeedAsync(PaginationParameters paginationParameters) { UserAuthValidator.Validate(_userAuthValidate); var feed = new InstaFeed(); try { var userFeedUri = UriCreator.GetUserFeedUri(paginationParameters.NextId); var request = _httpHelper.GetDefaultRequest(HttpMethod.Get, userFeedUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaFeed>(response, json)); } var feedResponse = JsonConvert.DeserializeObject <InstaFeedResponse>(json, new InstaFeedResponseDataConverter()); feed = ConvertersFabric.Instance.GetFeedConverter(feedResponse).Convert(); paginationParameters.NextId = feed.NextMaxId; paginationParameters.PagesLoaded++; while (feedResponse.MoreAvailable && !string.IsNullOrEmpty(paginationParameters.NextId) && paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextFeed = await GetUserTimelineFeedAsync(paginationParameters); if (!nextFeed.Succeeded) { return(Result.Fail(nextFeed.Info, feed)); } feed.Medias.AddRange(nextFeed.Value.Medias); feed.Stories.AddRange(nextFeed.Value.Stories); paginationParameters.NextId = nextFeed.Value.NextMaxId; paginationParameters.PagesLoaded++; } return(Result.Success(feed)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, feed)); } }
/// <summary> /// Get statistics of current account /// </summary> public async Task <IResult <InstaStatistics> > GetStatisticsAsync() { UserAuthValidator.Validate(_userAuthValidate); try { var instaUri = UriCreator.GetGraphStatisticsUri(InstaApiConstants.ACCEPT_LANGUAGE); var queryParamsData = new JObject { { "access_token", "" }, { "id", _user.LoggedInUser.Pk.ToString() } }; var variables = new JObject { { "query_params", queryParamsData }, { "timezone", InstaApiConstants.TIMEZONE }, { "activityTab", true }, { "audienceTab", true }, { "contentTab", true } }; var data = new Dictionary <string, string> { { "access_token", "undefined" }, { "fb_api_caller_class", "RelayModern" }, { "variables", variables.ToString(Formatting.None) }, { "doc_id", "1926322010754880" } }; var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaStatistics>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaStatisticsRootResponse>(json); return(Result.Success(ConvertersFabric.Instance.GetStatisticsConverter(obj).Convert())); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaStatistics), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaStatistics>(exception)); } }
/// <summary> /// Get user tags by username asynchronously /// <remarks>Returns media list containing tags</remarks> /// </summary> /// <param name="userId">User id (pk)</param> /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param> /// <returns> /// <see cref="InstaMediaList" /> /// </returns> public async Task <IResult <InstaMediaList> > GetUserTagsAsync(long userId, PaginationParameters paginationParameters) { UserAuthValidator.Validate(_userAuthValidate); var userTags = new InstaMediaList(); try { var uri = UriCreator.GetUserTagsUri(userId, _user.RankToken, paginationParameters.NextId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.Fail("", (InstaMediaList)null)); } var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json, new InstaMediaListDataConverter()); userTags.AddRange( mediaResponse.Medias.Select(ConvertersFabric.Instance.GetSingleMediaConverter) .Select(converter => converter.Convert())); userTags.NextId = paginationParameters.NextId = mediaResponse.NextMaxId; paginationParameters.PagesLoaded++; while (mediaResponse.MoreAvailable && !string.IsNullOrEmpty(paginationParameters.NextId) && paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextMedia = await GetUserTagsAsync(userId, paginationParameters); if (!nextMedia.Succeeded) { return(nextMedia); } userTags.AddRange(nextMedia.Value); userTags.NextId = paginationParameters.NextId = nextMedia.Value.NextId; } return(Result.Success(userTags)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, userTags)); } }
public async Task <IResult <InstaExploreFeed> > GetExploreFeedAsync(PaginationParameters paginationParameters) { var exploreFeed = new InstaExploreFeed(); try { var exploreUri = UriCreator.GetExploreUri(paginationParameters.NextId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, exploreUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaExploreFeed>(response, json)); } var feedResponse = JsonConvert.DeserializeObject <InstaExploreFeedResponse>(json, new InstaExploreFeedDataConverter()); exploreFeed = ConvertersFabric.Instance.GetExploreFeedConverter(feedResponse).Convert(); var nextId = feedResponse.Items.Medias.LastOrDefault(media => !string.IsNullOrEmpty(media.NextMaxId)) ?.NextMaxId; exploreFeed.Medias.PageSize = feedResponse.ResultsCount; paginationParameters.NextId = nextId; exploreFeed.NextId = nextId; while (feedResponse.MoreAvailable && !string.IsNullOrEmpty(paginationParameters.NextId) && paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextFeed = await GetExploreFeedAsync(paginationParameters); if (!nextFeed.Succeeded) { return(Result.Fail(nextFeed.Info, exploreFeed)); } nextId = feedResponse.Items.Medias.LastOrDefault(media => !string.IsNullOrEmpty(media.NextMaxId)) ?.NextMaxId; exploreFeed.NextId = paginationParameters.NextId = nextId; paginationParameters.PagesLoaded++; exploreFeed.Medias.AddRange(nextFeed.Value.Medias); } exploreFeed.Medias.Pages = paginationParameters.PagesLoaded; return(Result.Success(exploreFeed)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, exploreFeed)); } }
private async Task <IResult <InstaMediaList> > GetUserMediaAsync(long userId, PaginationParameters paginationParameters) { var mediaList = new InstaMediaList(); try { var instaUri = UriCreator.GetUserMediaListUri(userId, paginationParameters.NextId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); //Debug.WriteLine(json); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaMediaList>(response, json)); } var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json, new InstaMediaListDataConverter()); mediaList = ConvertersFabric.Instance.GetMediaListConverter(mediaResponse).Convert(); mediaList.NextMaxId = paginationParameters.NextId = mediaResponse.NextMaxId; paginationParameters.PagesLoaded++; while (mediaResponse.MoreAvailable && !string.IsNullOrEmpty(paginationParameters.NextId) && paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextMedia = await GetUserMediaAsync(userId, paginationParameters); if (!nextMedia.Succeeded) { return(Result.Fail(nextMedia.Info, mediaList)); } mediaList.NextMaxId = paginationParameters.NextId = nextMedia.Value.NextMaxId; mediaList.AddRange(nextMedia.Value); } mediaList.Pages = paginationParameters.PagesLoaded; mediaList.PageSize = mediaResponse.ResultsCount; return(Result.Success(mediaList)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, mediaList)); } }
private async Task <IResult <InstaMedia> > ExposeVideoAsync(string uploadId, string caption, InstaLocationShort location) { try { var instaUri = UriCreator.GetMediaConfigureUri(); var data = new JObject { { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "_uid", _user.LoggedInUser.Pk }, { "_csrftoken", _user.CsrfToken }, { "experiment", "ig_android_profile_contextual_feed" }, { "id", _user.LoggedInUser.Pk }, { "upload_id", uploadId }, }; var request = _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data); request.Headers.Host = "i.instagram.com"; var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var jObject = JsonConvert.DeserializeObject <ImageThumbnailResponse>(json); if (response.IsSuccessStatusCode) { var mediaResponse = JsonConvert.DeserializeObject <InstaMediaItemResponse>(json, new InstaMediaDataConverter()); var converter = ConvertersFabric.Instance.GetSingleMediaConverter(mediaResponse); var obj = converter.Convert(); if (obj.Caption == null && !string.IsNullOrEmpty(caption)) { var editedMedia = await _instaApi.MediaProcessor.EditMediaAsync(obj.InstaIdentifier, caption, location); if (editedMedia.Succeeded) { return(Result.Success(editedMedia.Value)); } } return(Result.Success(obj)); } return(Result.Fail <InstaMedia>(jObject.Status)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaMedia>(exception)); } }
/// <summary> /// Get media comments /// </summary> /// <param name="mediaId">Media id</param> /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param> public async Task <IResult <InstaCommentList> > GetMediaCommentsAsync(string mediaId, PaginationParameters paginationParameters) { UserAuthValidator.Validate(_userAuthValidate); try { var commentsUri = UriCreator.GetMediaCommentsUri(mediaId, paginationParameters.NextId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, commentsUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaCommentList>(response, json)); } var commentListResponse = JsonConvert.DeserializeObject <InstaCommentListResponse>(json); var pagesLoaded = 1; InstaCommentList Convert(InstaCommentListResponse commentsResponse) { return(ConvertersFabric.Instance.GetCommentListConverter(commentsResponse).Convert()); } while (commentListResponse.MoreComentsAvailable && !string.IsNullOrEmpty(commentListResponse.NextMaxId) && pagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextComments = await GetCommentListWithMaxIdAsync(mediaId, commentListResponse.NextMaxId); if (!nextComments.Succeeded) { return(Result.Fail(nextComments.Info, Convert(commentListResponse))); } commentListResponse.NextMaxId = nextComments.Value.NextMaxId; commentListResponse.MoreComentsAvailable = nextComments.Value.MoreComentsAvailable; commentListResponse.Comments.AddRange(nextComments.Value.Comments); pagesLoaded++; } var converter = ConvertersFabric.Instance.GetCommentListConverter(commentListResponse); return(Result.Success(converter.Convert())); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaCommentList>(exception)); } }
public async Task <IResult <InstaUserShortList> > GetUserFollowersAsync(string username, PaginationParameters paginationParameters) { var followers = new InstaUserShortList(); try { var user = await GetUserAsync(username); var userFollowersUri = UriCreator.GetUserFollowersUri(user.Value.Pk, _user.RankToken, paginationParameters.NextId); var followersResponse = await GetUserListByUriAsync(userFollowersUri); if (!followersResponse.Succeeded) { Result.Fail(followersResponse.Info, (InstaUserList)null); } followers.AddRange( followersResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter) .Select(converter => converter.Convert())); followers.NextId = followersResponse.Value.NextMaxId; var pagesLoaded = 1; while (!string.IsNullOrEmpty(followersResponse.Value.NextMaxId) && pagesLoaded < paginationParameters.MaximumPagesToLoad) { var nextFollowersUri = UriCreator.GetUserFollowersUri(user.Value.Pk, _user.RankToken, followersResponse.Value.NextMaxId); followersResponse = await GetUserListByUriAsync(nextFollowersUri); if (!followersResponse.Succeeded) { return(Result.Success($"Not all pages were downloaded: {followersResponse.Info.Message}", followers)); } followers.AddRange( followersResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter) .Select(converter => converter.Convert())); pagesLoaded++; followers.NextId = followersResponse.Value.NextMaxId; } return(Result.Success(followers)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, followers)); } }
public async Task <IResult <InstaDirectInboxThreadList> > SendDirectMessage(string recipients, string threadIds, string text) { var threads = new InstaDirectInboxThreadList(); try { var directSendMessageUri = UriCreator.GetDirectSendMessageUri(); var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, directSendMessageUri, _deviceInfo); var fields = new Dictionary <string, string> { { "text", text } }; if (!string.IsNullOrEmpty(recipients)) { fields.Add("recipient_users", "[[" + recipients + "]]"); } else { return(Result.Fail <InstaDirectInboxThreadList>("Please provide at least one recipient.")); } if (!string.IsNullOrEmpty(threadIds)) { fields.Add("thread_ids", "[" + threadIds + "]"); } request.Content = new FormUrlEncodedContent(fields); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaDirectInboxThreadList>(response, json)); } var result = JsonConvert.DeserializeObject <InstaSendDirectMessageResponse>(json); if (!result.IsOk()) { return(Result.Fail <InstaDirectInboxThreadList>(result.Status)); } threads.AddRange(result.Threads.Select(thread => ConvertersFabric.Instance.GetDirectThreadConverter(thread).Convert())); return(Result.Success(threads)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaDirectInboxThreadList>(exception)); } }
/// <summary> /// Send singup sms code /// </summary> /// <param name="phoneNumber">Phone number</param> public async Task <IResult <bool> > SendSignUpSmsCodeAsync(string phoneNumber) { var data = new Dictionary <string, string> { { "phone_id", _deviceInfo.PhoneGuid.ToString() }, { "phone_number", phoneNumber }, { "_csrftoken", _user.CsrfToken }, { "guid", _deviceInfo.DeviceGuid.ToString() }, { "device_id", _deviceInfo.DeviceId }, { "android_build_type", "release" }, { "waterfall_id", RegistrationWaterfallId }, }; return(await GetResultAsync(UriCreator.GetSignUpSMSCodeUri(), data, true)); }
/// <summary> /// Check phone number /// </summary> /// <param name="phoneNumber">Phone number</param> public async Task <IResult <bool> > CheckPhoneNumberAsync(string phoneNumber) { var data = new Dictionary <string, string> { { "phone_id", _deviceInfo.PhoneGuid.ToString() }, { "login_nonce_map", "{}" }, { "phone_number", phoneNumber }, { "_csrftoken", _user.CsrfToken }, { "guid", _deviceInfo.DeviceGuid.ToString() }, { "device_id", _deviceInfo.DeviceId }, { "prefill_shown", "False" }, }; return(await GetResultAsync(UriCreator.GetCheckPhoneNumberUri(), data, true)); }
/// <summary> /// Send registration verify email /// </summary> /// <param name="email">Email</param> public async Task <IResult <bool> > SendRegistrationVerifyEmailAsync(string email) { var data = new Dictionary <string, string> { { "phone_id", _deviceInfo.PhoneGuid.ToString() }, { "_csrftoken", _user.CsrfToken }, { "guid", _deviceInfo.DeviceGuid.ToString() }, { "device_id", _deviceInfo.DeviceId }, { "email", email }, { "waterfall_id", RegistrationWaterfallId }, { "auto_confirm_only", "false" }, }; return(await GetResultAsync(UriCreator.GetSendRegistrationVerifyEmailUri(), data, true, true).ConfigureAwait(false)); }
public Uri BuildRequestUri(ModelServiceClient modelService) { var builder = UriCreator.FromUri(modelService.ModelServiceBaseUri); builder = builder.WithPath(PageId.HasValue ? $"PageModel/{CmUriScheme}/{PublicationId}-{PageId.Value}" : $"PageModel/{CmUriScheme}/{PublicationId}/{GetCanonicalUrlPath(Path)}"); builder.WithQueryParam("includes", PageInclusion).WithQueryParam("modelType", DataModelType); if (ContentType != ContentType.IGNORE) { builder.WithQueryParam("raw", ContentType == ContentType.RAW); } return(builder.Build()); }
/// <summary> /// Search user by location /// </summary> /// <param name="latitude">Latitude</param> /// <param name="longitude">Longitude</param> /// <param name="desireUsername">Desire username</param> /// <param name="count">Maximum user count</param> public async Task <IResult <InstaUserSearchLocation> > SearchUserByLocationAsync(double latitude, double longitude, string desireUsername, int count = 50) { UserAuthValidator.Validate(_userAuthValidate); try { var uri = UriCreator.GetUserSearchByLocationUri(); if (count <= 0) { count = 30; } var fields = new Dictionary <string, string> { { "timezone_offset", InstaApiConstants.TIMEZONE_OFFSET.ToString() }, { "lat", latitude.ToString(CultureInfo.InvariantCulture) }, { "lng", longitude.ToString(CultureInfo.InvariantCulture) }, { "count", count.ToString() }, { "query", desireUsername }, { "context", "blended" }, { "rank_token", _user.RankToken } }; if (!Uri.TryCreate(uri, fields.AsQueryString(), out var newuri)) { return(Result.Fail <InstaUserSearchLocation>("Unable to create uri for user search by location")); } var request = _httpHelper.GetDefaultRequest(HttpMethod.Get, newuri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaUserSearchLocation>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaUserSearchLocation>(json); return(obj.Status.ToLower() == "ok"? Result.Success(obj) : Result.UnExpectedResponse <InstaUserSearchLocation>(response, json)); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaUserSearchLocation), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaUserSearchLocation>(exception)); } }
/// <summary> /// Nux new account seen /// </summary> public async Task <IResult <bool> > NuxNewAccountSeenAsync() { var data = new JObject { { "is_fb4a_installed", "false" }, { "phone_id", _deviceInfo.PhoneGuid.ToString() }, { "_csrftoken", _user.CsrfToken }, { "_uid", _user.LoggedInUser.Pk.ToString() }, { "guid", _deviceInfo.DeviceGuid.ToString() }, { "device_id", _deviceInfo.DeviceId }, { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "waterfall_id", Guid.NewGuid().ToString() }, }; return(await GetResultAsync(UriCreator.GetNuxNewAccountSeenUri(true), data, false).ConfigureAwait(false)); }
private async Task <IResult <InstaRecentActivityResponse> > GetFollowingActivityWithMaxIdAsync(string maxId) { var uri = UriCreator.GetFollowingRecentActivityUri(maxId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo); var response = await _httpClient.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { var followingActivity = JsonConvert.DeserializeObject <InstaRecentActivityResponse>(json, new InstaRecentActivityConverter()); return(Result.Success(followingActivity)); } return(Result.Fail(GetBadStatusFromJsonString(json).Message, (InstaRecentActivityResponse)null)); }
public static System.Uri CreateInstanceOfUri(Random rndGen) { Uri result; UriKind kind; try { string uriString = UriCreator.CreateUri(rndGen, out kind); result = new Uri(uriString, kind); } catch (ArgumentException) { result = new Uri("my.schema://*****:*****@my.domain/path1/path2?query1=123&query2=%22hello%22"); } return(result); }
private async Task <IResult <InstaPlaceListResponse> > SearchPlaces(double latitude, double longitude, string query, PaginationParameters paginationParameters) { try { if (paginationParameters == null) { paginationParameters = PaginationParameters.MaxPagesToLoad(1); } var instaUri = UriCreator.GetSearchPlacesUri(InstaApiConstants.TIMEZONE_OFFSET, latitude, longitude, query, paginationParameters.NextMaxId, paginationParameters.ExcludeList); var request = _httpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var obj = JsonConvert.DeserializeObject <InstaPlaceListResponse>(json); if (response.StatusCode != HttpStatusCode.OK) { return(Result.Fail <InstaPlaceListResponse>(obj.Message)); } if (obj.Items?.Count > 0) { foreach (var item in obj.Items) { obj.ExcludeList.Add(item.Location.Pk); } } return(Result.Success(obj)); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaPlaceListResponse), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaPlaceListResponse>(exception)); } }
private async Task <IResult <InstaTVChannel> > GetChannel(InstaTVChannelType?channelType, long?userId, PaginationParameters paginationParameters) { try { var instaUri = UriCreator.GetIGTVChannelUri(); var data = new JObject { { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "_uid", _user.LoggedInUser.Pk.ToString() }, { "_csrftoken", _user.CsrfToken } }; if (channelType != null) { data.Add("id", channelType.Value.GetRealChannelType()); } else { data.Add("id", $"user_{userId}"); } if (paginationParameters != null && !string.IsNullOrEmpty(paginationParameters.NextMaxId)) { data.Add("max_id", paginationParameters.NextMaxId); } var request = _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaTVChannel>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaTVChannelResponse>(json); return(Result.Success(ConvertersFabric.Instance.GetTVChannelConverter(obj).Convert())); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaTVChannel), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaTVChannel>(exception)); } }
/// <summary> /// Search city location for business account /// </summary> /// <param name="cityOrTown">City/town name</param> public async Task <IResult <InstaBusinessCityLocationList> > SearchCityLocationAsync(string cityOrTown) { UserAuthValidator.Validate(_userAuthValidate); try { if (string.IsNullOrEmpty(cityOrTown)) { return(Result.Fail <InstaBusinessCityLocationList>("CityOrTown cannot be null or empty")); } var instaUri = UriCreator.GetBusinessGraphQLUri(); var queryParams = new JObject { { "0", cityOrTown } }; var data = new Dictionary <string, string> { { "query_id", "1860980127555904" }, { "locale", InstaApiConstants.ACCEPT_LANGUAGE.Replace("-", "_") }, { "vc_policy", "ads_viewer_context_policy" }, { "signed_body", $"{_httpHelper._apiVersion.SignatureKey}." }, { InstaApiConstants.HEADER_IG_SIGNATURE_KEY_VERSION, InstaApiConstants.IG_SIGNATURE_KEY_VERSION }, { "strip_nulls", "true" }, { "strip_defaults", "true" }, { "query_params", queryParams.ToString(Formatting.None) }, }; var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaBusinessCityLocationList>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaBusinessCityLocationList>(json, new InstaBusinessCityLocationDataConverter()); return(Result.Success(obj)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaBusinessCityLocationList>(exception)); } }
/// <summary> /// Get suggested categories /// </summary> public async Task <IResult <InstaBusinessSugesstedCategoryList> > GetSuggestedCategoriesAsync() { UserAuthValidator.Validate(_userAuthValidate); try { var instaUri = UriCreator.GetBusinessGraphQLUri(); var zero = new JObject { { "page_name", _user.UserName.ToLower() }, { "num_result", "5" } }; var queryParams = new JObject { { "0", zero } }; var data = new Dictionary <string, string> { { "query_id", "706774002864790" }, { "locale", InstaApiConstants.ACCEPT_LANGUAGE.Replace("-", "_") }, { "vc_policy", "ads_viewer_context_policy" }, { "signed_body", $"{_httpHelper._apiVersion.SignatureKey}." }, { InstaApiConstants.HEADER_IG_SIGNATURE_KEY_VERSION, InstaApiConstants.IG_SIGNATURE_KEY_VERSION }, { "strip_nulls", "true" }, { "strip_defaults", "true" }, { "query_params", queryParams.ToString(Formatting.None) }, }; var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaBusinessSugesstedCategoryList>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaBusinessSugesstedCategoryList>(json, new InstaBusinessSuggestedCategoryDataConverter()); return(Result.Success(obj)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaBusinessSugesstedCategoryList>(exception)); } }
/// <summary> /// Adds items to collection asynchronous. /// </summary> /// <param name="collectionId">Collection identifier.</param> /// <param name="mediaIds">Media id list.</param> public async Task <IResult <InstaCollectionItem> > AddItemsToCollectionAsync(long collectionId, params string[] mediaIds) { UserAuthValidator.Validate(_userAuthValidate); try { if (mediaIds?.Length < 1) { return(Result.Fail <InstaCollectionItem>("Provide at least one media id to add to collection")); } var editCollectionUri = UriCreator.GetEditCollectionUri(collectionId); var data = new JObject { { "module_name", InstaApiConstants.FEED_SAVED_ADD_TO_COLLECTION_MODULE }, { "added_media_ids", JsonConvert.SerializeObject(mediaIds) }, { "radio_type", "wifi-none" }, { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "_uid", _user.LoggedInUser.Pk }, { "_csrftoken", _user.CsrfToken } }; var request = _httpHelper.GetSignedRequest(HttpMethod.Get, editCollectionUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaCollectionItem>(response, json)); } var newCollectionResponse = JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json); var converter = ConvertersFabric.Instance.GetCollectionConverter(newCollectionResponse); return(Result.Success(converter.Convert())); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaCollectionItem), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaCollectionItem>(exception)); } }
/// <summary> /// Get full media insights /// </summary> /// <param name="mediaId">Media id (<see cref="InstaMedia.InstaIdentifier"/>)</param> public async Task <IResult <InstaFullMediaInsights> > GetFullMediaInsightsAsync(string mediaId) { UserAuthValidator.Validate(_userAuthValidate); try { var instaUri = UriCreator.GetGraphStatisticsUri(InstaApiConstants.ACCEPT_LANGUAGE, InstaInsightSurfaceType.Post); var queryParamsData = new JObject { { "access_token", "" }, { "id", mediaId } }; var variables = new JObject { { "query_params", queryParamsData } }; var data = new Dictionary <string, string> { { "access_token", "undefined" }, { "fb_api_caller_class", "RelayModern" }, { "variables", variables.ToString(Formatting.None) }, { "doc_id", "1527362987318283" } }; var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaFullMediaInsights>(response, json)); } var obj = JsonConvert.DeserializeObject <InstaFullMediaInsightsRootResponse>(json); return(Result.Success(ConvertersFabric.Instance.GetFullMediaInsightsConverter(obj.Data.Media).Convert())); } catch (HttpRequestException httpException) { _logger?.LogException(httpException); return(Result.Fail(httpException, default(InstaFullMediaInsights), ResponseType.NetworkProblem)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaFullMediaInsights>(exception)); } }
private async Task <IResult <InstaCommentListResponse> > GetCommentListWithMaxIdAsync(string mediaId, string nextId) { var commentsUri = UriCreator.GetMediaCommentsUri(mediaId, nextId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, commentsUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.Fail("Unable to get next portion of comments", (InstaCommentListResponse)null)); } var comments = JsonConvert.DeserializeObject <InstaCommentListResponse>(json); return(Result.Success(comments)); }
private async Task <IResult <InstaRecentActivityResponse> > GetFollowingActivityWithMaxIdAsync(string maxId) { var uri = UriCreator.GetFollowingRecentActivityUri(maxId); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaRecentActivityResponse>(response, json)); } var followingActivity = JsonConvert.DeserializeObject <InstaRecentActivityResponse>(json, new InstaRecentActivityConverter()); return(Result.Success(followingActivity)); }
/// <summary> /// Searches for specific hashtag by search query. /// </summary> /// <param name="query">Search query</param> /// <param name="excludeList">Array of numerical hashtag IDs (ie "17841562498105353") to exclude from the response, allowing you to skip tags from a previous call to get more results</param> /// <param name="rankToken">The rank token from the previous page's response</param> /// <returns> /// List of hashtags /// </returns> public async Task <IResult <InstaHashtagSearch> > SearchHashtagAsync(string query, IEnumerable <long> excludeList, string rankToken) { UserAuthValidator.Validate(_userAuthValidate); var RequestHeaderFieldsTooLarge = (HttpStatusCode)431; var count = 50; var tags = new InstaHashtagSearch(); try { var userUri = UriCreator.GetSearchTagUri(query, count, excludeList, rankToken); var request = _httpHelper.GetDefaultRequest(HttpMethod.Get, userUri, _deviceInfo); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode == RequestHeaderFieldsTooLarge) { return(Result.Success(tags)); } if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <InstaHashtagSearch>(response, json)); } var tagsResponse = JsonConvert.DeserializeObject <InstaHashtagSearchResponse>(json, new InstaHashtagSearchDataConverter()); tags = ConvertersFabric.Instance.GetHashTagsSearchConverter(tagsResponse).Convert(); if (tags.Any() && excludeList != null && excludeList.Contains(tags.First().Id)) { tags.RemoveAt(0); } if (!tags.Any()) { tags = new InstaHashtagSearch(); } return(Result.Success(tags)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail(exception, tags)); } }
/// <summary> /// The logger object. This reference is used to write log entries. /// </summary> //private Logger log; #endregion #region constructors /// <summary> /// Initializes a new instance of the <see cref="TddAppComController"/> class. /// </summary> /// <param name="remoteHost">The host name of APP interface.</param> /// <param name="remotePort">The port of APP interface.</param> /// <param name="pushMessageServerHost">The host name of the push message server.</param> /// <param name="pushMessageServerPort">The port of the push message server.</param> public TddAppComController(string remoteHost, ushort remotePort, string pushMessageServerHost, ushort pushMessageServerPort) { // get logger reference // this.log = LogCreator.GetInstance(); // method entry log message // this.log.Trace("TddAppComController(...) - running..."); // set parameter inherited parameter values this.LastError = new KeyValuePair <int, string>(0, NoErrorString); this.DeviceNumber = DefaultDeviceNumber; this.ChannelNumber = TddConstants.NoChannelNumber; // create URI creator this.uriCreator = new UriCreator(remoteHost, remotePort); // create HTTP client this.httpClient = new AppComHttpClient(); // this.log.Info("TddAppComController(...) - HTTP client started."); // create HTTP server this.pushMessageServer = new AppComHttpServer(pushMessageServerHost, pushMessageServerPort); // this.log.Info("TddAppComController(...) - Push message server is started. Listening on '{0}':{1}", pushMessageServerHost, pushMessageServerPort); // create APPCOM protocol layer. this.appComProtocolLayer = new AppComProtocolLayer(this.httpClient, this.pushMessageServer); // this.log.Info("TddAppComController(...) - APPCOM protocol layer started."); // create processors for asynchronous messages this.pushMessageProcessor = new PushMessageProcessor(this.appComProtocolLayer); // this.log.Info("TddAppComController(...) - Push message processor started."); // register push message server try { this.RegisterPushMessageServer(); // this.log.Info("TddAppComController(...) - Push message server registered."); } catch (Exception exception) { // this.log.Warn("TddAppComController(...) - Cannot register push message server. Error: {0}", exception.Message); } // method exit log message // this.log.Trace("TddAppComController(...) - done"); }
public async Task <IResult <InstaRecipients> > GetRankedRecipientsAsync() { var userUri = UriCreator.GetRankedRecipientsUri(); var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, userUri, _deviceInfo); var response = await _httpClient.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { var responseRecipients = JsonConvert.DeserializeObject <InstaRecipientsResponse>(json, new InstaRecipientsDataConverter("ranked_recipients")); var converter = ConvertersFabric.GetRecipientsConverter(responseRecipients); return(Result.Success(converter.Convert())); } return(Result.Fail(GetBadStatusFromJsonString(json).Message, (InstaRecipients)null)); }