Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

paginationParameters does not work on GetUserFollowingAsync. #222

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -262,4 +262,8 @@ paket-files/

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
*.pyc

# binary files and texts notes
**/*.bin
**/*.txt
4 changes: 3 additions & 1 deletion InstaSharper.Examples/InstaSharper.Examples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="InstaSharper, Version=1.2.6.0, Culture=neutral, processorArchitecture=MSIL">
<Reference Include="InstaSharper, Version=1.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\InstaSharper\bin\release\net452\InstaSharper.dll</HintPath>
</Reference>
Expand All @@ -52,10 +52,12 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Samples\Basics.cs" />
<Compile Include="Samples\CollectionSample.cs" />
<Compile Include="Samples\CommentMedia.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Samples\IDemoSample.cs" />
<Compile Include="Samples\LocationSample.cs" />
<Compile Include="Samples\Messaging.cs" />
<Compile Include="Samples\SaveLoadState.cs" />
<Compile Include="Samples\Stories.cs" />
Expand Down
100 changes: 64 additions & 36 deletions InstaSharper.Examples/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using InstaSharper.API;
using InstaSharper.API.Builder;
using InstaSharper.Classes;
using InstaSharper.Classes.Android.DeviceInfo;
using InstaSharper.Examples.Samples;
using InstaSharper.Logger;

Expand Down Expand Up @@ -34,61 +34,89 @@ public static async Task<bool> MainAsync()
var userSession = new UserSessionData
{
UserName = "username",
Password = "password"
Password = "password"
};

// create new InstaApi instance using Builder
var device = AndroidDeviceGenerator.GetByName(AndroidDevices.SAMSUNG_NOTE3);
var requestMessage = ApiRequestMessage.FromDevice(device);
_instaApi = InstaApiBuilder.CreateBuilder()
.SetUser(userSession)
.SetApiRequestMessage(requestMessage)
.UseLogger(new DebugLogger(LogLevel.Info)) // use logger for requests and debug messages
.UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages
.SetRequestDelay(TimeSpan.FromSeconds(2))
.Build();
// login
Console.WriteLine($"Logging in as {userSession.UserName}");
var logInResult = await _instaApi.LoginAsync();
if (!logInResult.Succeeded)

const string stateFile = "state.bin";
try
{
Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
if (File.Exists(stateFile))
{
Console.WriteLine("Loading state from file");
Stream fs = File.OpenRead(stateFile);
fs.Seek(0, SeekOrigin.Begin);
_instaApi.LoadStateDataFromStream(fs);
}
}
else
catch (Exception e)
{
Console.WriteLine("Press 1 to start basic demo samples");
Console.WriteLine("Press 2 to start upload photo demo sample");
Console.WriteLine("Press 3 to start comment media demo sample");
Console.WriteLine("Press 4 to start stories demo sample");
Console.WriteLine("Press 5 to start demo with saving state of API instance");
Console.WriteLine("Press 6 to start messaging demo sample");
Console.WriteLine(e);
}

var samplesMap = new Dictionary<ConsoleKey, IDemoSample>
if (!_instaApi.IsUserAuthenticated)
{
// login
Console.WriteLine($"Logging in as {userSession.UserName}");
var logInResult = await _instaApi.LoginAsync();
if (!logInResult.Succeeded)
{
[ConsoleKey.D1] = new Basics(_instaApi),
[ConsoleKey.D2] = new UploadPhoto(_instaApi),
[ConsoleKey.D3] = new CommentMedia(_instaApi),
[ConsoleKey.D4] = new Stories(_instaApi),
[ConsoleKey.D5] = new SaveLoadState(_instaApi),
[ConsoleKey.D6] = new Messaging(_instaApi)
};
var key = Console.ReadKey();
Console.WriteLine(Environment.NewLine);
if (samplesMap.ContainsKey(key.Key))
await samplesMap[key.Key].DoShow();
Console.WriteLine("Done. Press esc key to exit...");

key = Console.ReadKey();
return key.Key == ConsoleKey.Escape;
Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
return false;
}
}
var state = _instaApi.GetStateDataAsStream();
using (var fileStream = File.Create(stateFile))
{
state.Seek(0, SeekOrigin.Begin);
state.CopyTo(fileStream);
}

Console.WriteLine("Press 1 to start basic demo samples");
Console.WriteLine("Press 2 to start upload photo demo sample");
Console.WriteLine("Press 3 to start comment media demo sample");
Console.WriteLine("Press 4 to start stories demo sample");
Console.WriteLine("Press 5 to start demo with saving state of API instance");
Console.WriteLine("Press 6 to start messaging demo sample");
Console.WriteLine("Press 7 to start location demo sample");
Console.WriteLine("Press 8 to start collections demo sample");

var samplesMap = new Dictionary<ConsoleKey, IDemoSample>
{
[ConsoleKey.D1] = new Basics(_instaApi),
[ConsoleKey.D2] = new UploadPhoto(_instaApi),
[ConsoleKey.D3] = new CommentMedia(_instaApi),
[ConsoleKey.D4] = new Stories(_instaApi),
[ConsoleKey.D5] = new SaveLoadState(_instaApi),
[ConsoleKey.D6] = new Messaging(_instaApi),
[ConsoleKey.D7] = new LocationSample(_instaApi),
[ConsoleKey.D8] = new CollectionSample(_instaApi)

};
var key = Console.ReadKey();
Console.WriteLine(Environment.NewLine);
if (samplesMap.ContainsKey(key.Key))
await samplesMap[key.Key].DoShow();
Console.WriteLine("Done. Press esc key to exit...");

key = Console.ReadKey();
return key.Key == ConsoleKey.Escape;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();
if (logoutResult.Succeeded) Console.WriteLine("Logout succeed");
// perform that if user needs to logged out
// var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();
// if (logoutResult.Succeeded) Console.WriteLine("Logout succeed");
}
return false;
}
Expand Down
18 changes: 11 additions & 7 deletions InstaSharper.Examples/Samples/Basics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Linq;
using System.Threading.Tasks;
using InstaSharper.API;
using InstaSharper.Classes;
using InstaSharper.Examples.Utils;

namespace InstaSharper.Examples.Samples
Expand All @@ -27,16 +28,19 @@ public async Task DoShow()
Console.WriteLine(
$"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

// get self followers
var followers = await _instaApi.GetUserFollowersAsync(currentUser.Value.UserName, 5);
Console.WriteLine($"Count of followers [{currentUser.Value.UserName}]:{followers.Value.Count}");
// get followers of user 'elonmusk'
var followers = await _instaApi.GetUserFollowersAsync("elonmusk",
PaginationParameters.MaxPagesToLoad(5)
.StartFromId("AQAC8w90POWyM7zMjHWmO9vsZNL_TuLp6FR506_C_y3fUAjlCclrIDI2RdSGvur5UjLrq4Cq7NJN8QUhHG-vpbT6pCLB5X9crDxBOHUEuNJ4fA"));
Console.WriteLine($"Count of followers [elonmusk]:{followers.Value.Count}");
Console.WriteLine($"Next id will be: '{followers.Value.NextId}'");

// get self folling
var following = await _instaApi.GetUserFollowingAsync(currentUser.Value.UserName, 5);
var following = await _instaApi.GetUserFollowingAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5));
Console.WriteLine($"Count of following [{currentUser.Value.UserName}]:{following.Value.Count}");

// get self user's media, latest 5 pages
var currentUserMedia = await _instaApi.GetUserMediaAsync(currentUser.Value.UserName, 5);
var currentUserMedia = await _instaApi.GetUserMediaAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5));
if (currentUserMedia.Succeeded)
{
Console.WriteLine($"Media count [{currentUser.Value.UserName}]: {currentUserMedia.Value.Count}");
Expand All @@ -45,7 +49,7 @@ public async Task DoShow()
}

//get user time line feed, latest 5 pages
var userFeed = await _instaApi.GetUserTimelineFeedAsync(5);
var userFeed = await _instaApi.GetUserTimelineFeedAsync(PaginationParameters.MaxPagesToLoad(5));
if (userFeed.Succeeded)
{
Console.WriteLine(
Expand All @@ -62,7 +66,7 @@ public async Task DoShow()
}

// get tag feed, latest 5 pages
var tagFeed = await _instaApi.GetTagFeedAsync("quadcopter", 5);
var tagFeed = await _instaApi.GetTagFeedAsync("quadcopter", PaginationParameters.MaxPagesToLoad(5));
if (tagFeed.Succeeded)
{
Console.WriteLine(
Expand Down
27 changes: 27 additions & 0 deletions InstaSharper.Examples/Samples/CollectionSample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Threading.Tasks;
using InstaSharper.API;

namespace InstaSharper.Examples.Samples
{
internal class CollectionSample : IDemoSample
{
private readonly IInstaApi _instaApi;

public CollectionSample(IInstaApi instaApi)
{
_instaApi = instaApi;
}

public async Task DoShow()
{
// get all collections of current user
var collections = await _instaApi.GetCollectionsAsync();
Console.WriteLine($"Loaded {collections.Value.Items.Count} collections for current user");
foreach (var instaCollection in collections.Value.Items)
{
Console.WriteLine($"Collection: name={instaCollection.CollectionName}, id={instaCollection.CollectionId}");
}
}
}
}
37 changes: 37 additions & 0 deletions InstaSharper.Examples/Samples/LocationSample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using InstaSharper.API;
using InstaSharper.Classes;

namespace InstaSharper.Examples.Samples
{
internal class LocationSample : IDemoSample
{
private readonly IInstaApi _instaApi;

public LocationSample(IInstaApi instaApi)
{
_instaApi = instaApi;
}

public async Task DoShow()
{
// search for related locations near location with latitude = 55.753923, logitude = 37.620940
// additionaly you can specify search query or just empty string
var result = await _instaApi.SearchLocation(55.753923, 37.620940, "square");
Console.WriteLine($"Loaded {result.Value.Count} locations");
var firstLocation = result.Value?.FirstOrDefault();
if(firstLocation == null)
return;
Console.WriteLine($"Loading feed for location: name={firstLocation.Name}; id={firstLocation.ExternalId}.");

var locationFeed =
await _instaApi.GetLocationFeed(long.Parse(firstLocation.ExternalId), PaginationParameters.MaxPagesToLoad(5));

Console.WriteLine(locationFeed.Succeeded
? $"Loaded {locationFeed.Value.Medias?.Count} medias for location, total location medias: {locationFeed.Value.MediaCount}"
: $"Unable to load location '{firstLocation.Name}' feed");
}
}
}
9 changes: 7 additions & 2 deletions InstaSharper.Examples/Samples/Messaging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public async Task DoShow()
Console.WriteLine("Unable to get ranked recipients");
return;
}
Console.WriteLine($"Got {recipientsResult.Value.Items.Count} ranked threads");
foreach (var thread in recipientsResult.Value.Items)
Console.WriteLine($"Got {recipientsResult.Value.Threads.Count} ranked threads");
foreach (var thread in recipientsResult.Value.Threads)
Console.WriteLine($"Threadname: {thread.ThreadTitle}, users: {thread.Users.Count}");

var inboxThreads = await _instaApi.GetDirectInboxAsync();
Expand All @@ -36,9 +36,14 @@ public async Task DoShow()
foreach (var thread in inboxThreads.Value.Inbox.Threads)
Console.WriteLine($"Threadname: {thread.Title}, users: {thread.Users.Count}");
var firstThread = inboxThreads.Value.Inbox.Threads.FirstOrDefault();
// send message to specific thread
var sendMessageResult = await _instaApi.SendDirectMessage($"{firstThread.Users.FirstOrDefault()?.Pk}",
firstThread.ThreadId, "test");
Console.WriteLine(sendMessageResult.Succeeded ? "Message sent" : "Unable to send message");

// just send message to user (thread not specified)
sendMessageResult = await _instaApi.SendDirectMessage($"{firstThread.Users.FirstOrDefault()?.Pk}", string.Empty , "one more test");
Console.WriteLine(sendMessageResult.Succeeded ? "Message sent" : "Unable to send message");
}
}
}
2 changes: 2 additions & 0 deletions InstaSharper.Examples/Samples/SaveLoadState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading.Tasks;
using InstaSharper.API;
using InstaSharper.API.Builder;
using InstaSharper.Classes;

namespace InstaSharper.Examples.Samples
{
Expand All @@ -25,6 +26,7 @@ public async Task DoShow()
Console.WriteLine($"Got current user: {result.Value.UserName} using existing API instance");
var stream = _instaApi.GetStateDataAsStream();
var anotherInstance = InstaApiBuilder.CreateBuilder()
.SetUser(UserSessionData.Empty)
.SetRequestDelay(TimeSpan.FromSeconds(2))
.Build();
anotherInstance.LoadStateDataFromStream(stream);
Expand Down
40 changes: 28 additions & 12 deletions InstaSharper.Tests/Classes/AuthenticatedTestFixture.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,54 @@
using System;
using System.IO;
using System.Threading.Tasks;
using InstaSharper.API;
using InstaSharper.Classes;
using InstaSharper.Tests.Utils;

namespace InstaSharper.Tests.Classes
{
public class AuthenticatedTestFixture : IDisposable
public class AuthenticatedTestFixture
{
private readonly string _password = Environment.GetEnvironmentVariable("instaapiuserpassword");
private readonly string _username = "alex_codegarage";

public AuthenticatedTestFixture()
{
ApiInstance = TestHelpers.GetDefaultInstaApiInstance(new UserSessionData
ApiInstance =
TestHelpers.GetDefaultInstaApiInstance(UserSessionData.ForUsername(_username).WithPassword(_password));
const string stateFile = "state.bin";
try
{
UserName = _username,
Password = _password
});
if (File.Exists(stateFile))
{
Stream fs = File.OpenRead(stateFile);
fs.Seek(0, SeekOrigin.Begin);
ApiInstance.LoadStateDataFromStream(fs);
if (ApiInstance.IsUserAuthenticated)
return;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}

var loginTask = Task.Run(ApiInstance.LoginAsync);

if (!loginTask.Wait(TimeSpan.FromSeconds(30)))
throw new Exception($"Unable to login, user: {_username}, password: {_password}.");

if (!loginTask.Result.Succeeded) return;
var state = ApiInstance.GetStateDataAsStream();
using (var fileStream = File.Create(stateFile))
{
state.Seek(0, SeekOrigin.Begin);
state.CopyTo(fileStream);
}
}

public IInstaApi ApiInstance { get; }

public void Dispose()
{
var logoutTask = Task.Run(ApiInstance.LogoutAsync);
if (!logoutTask.Wait(TimeSpan.FromSeconds(10)))
throw new Exception($"Not able to logout, user: {_username}, password: {_password}.");
}

public string GetUsername()
{
return _username;
Expand Down
Loading