Skip to content
This repository has been archived by the owner on Jul 2, 2023. It is now read-only.

Commit

Permalink
Added PresenceSub
Browse files Browse the repository at this point in the history
  • Loading branch information
Sky Morey authored and Sky Morey committed Jan 12, 2018
1 parent b2da5be commit 851e8ea
Show file tree
Hide file tree
Showing 32 changed files with 262 additions and 201 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

# SlackAPI

This is a third party implementation of Slack's API written in C#. This supports their WebAPI aswell as their Real Time Messaging API.
This is a third party implementation of Slack's API written in C#. This supports their WebAPI as well as their Real Time Messaging API.

# Examples

Expand All @@ -24,7 +24,7 @@ Want committer access? Feel like I'm too lazy to keep up with Slack's ever chang

Create some pull requests, give me a reason to give you access.

# Howto build the solution
# How to build the solution
###### (aka where is the config.json file?)
The project **SlackAPI.Tests** requires a valid `config.json` file for tests. You have two options to build the solution:
- Unload SlackAPI.Tests project and you're able to build SlackAPI solution.
Expand Down
8 changes: 4 additions & 4 deletions SlackAPI.Console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ static void Main(string[] args)
{
try
{
var clientId = "PUT CLIENT ID FROM SLACK APPLICATION REGISTATION HERE";
var clientSecret = "PUT CLIENT SECRET FROM SLACK APPLICATION REGISTATION HERE";
var redirectUri = "PUT REDIRECT FROM SLACK APPLICATION REGISTATION HERE";
var clientId = "58195700114.297428006771"; // PUT CLIENT ID FROM SLACK APPLICATION REGISTATION HERE";
var clientSecret = "70e8cbec2fa97cf376d526954a86b289"; // PUT CLIENT SECRET FROM SLACK APPLICATION REGISTATION HERE";
var redirectUri = "http://localhost"; // PUT REDIRECT FROM SLACK APPLICATION REGISTATION HERE";

Console.WriteLine("------------------------------------------------------------------");
Console.WriteLine("This app will open your web browser pointing at an authentication");
Expand All @@ -26,7 +26,7 @@ static void Main(string[] args)

// start...
var state = Guid.NewGuid().ToString();
var uri = SlackClient.GetAuthorizeUri(clientId, SlackScope.Identify | SlackScope.Read | SlackScope.Post, redirectUri, state, "socialsaleslounge");
var uri = SlackClient.GetAuthorizeUri(clientId, SlackScope.Identify | SlackScope.Read | SlackScope.Post | SlackScope.Client, redirectUri, state, "socialsaleslounge");
Console.WriteLine("Directing to: " + uri);
Process.Start(uri.ToString());

Expand Down
8 changes: 6 additions & 2 deletions SlackAPI.Tests/Configuration/IntegrationFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,22 @@ public IntegrationFixture()
{
this.Config = this.GetConfig();
this.UserClient = this.GetClient(this.Config.UserAuthToken);
this.UserClientWithPresence = this.GetClient(this.Config.UserAuthToken, new[] { new Tuple<string, string>("batch_presence_aware", "true") });
this.BotClient = this.GetClient(this.Config.BotAuthToken);
}

public SlackConfig Config { get; }

public SlackSocketClient UserClient { get; }

public SlackSocketClient UserClientWithPresence { get; }

public SlackSocketClient BotClient { get; }

public void Dispose()
{
this.UserClient.CloseSocket();
this.UserClientWithPresence.CloseSocket();
this.BotClient.CloseSocket();
}

Expand All @@ -39,14 +43,14 @@ private SlackConfig GetConfig()
return JsonConvert.DeserializeAnonymousType(json, jsonObject).slack;
}

private SlackSocketClient GetClient(string authToken)
private SlackSocketClient GetClient(string authToken, Tuple<string, string>[] loginParameters = null)
{
SlackSocketClient client;

using (var syncClient = new InSync($"{nameof(SlackClient.Connect)} - Connected callback"))
using (var syncClientSocket = new InSync($"{nameof(SlackClient.Connect)} - SocketConnected callback"))
{
client = new SlackSocketClient(authToken);
client = new SlackSocketClient(authToken, loginParameters);
client.Connect(x =>
{
Console.WriteLine("Connected");
Expand Down
2 changes: 1 addition & 1 deletion SlackAPI.Tests/Configuration/SlackConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class SlackConfig
{
public string UserAuthToken { get; set; }
public string BotAuthToken { get; set; }
public string TestChannel { get; set; }
public string TestChannelId { get; set; }
public string DirectMessageUser { get; set; }
public string AuthCode { get; set; }
public string ClientId { get; set; }
Expand Down
10 changes: 5 additions & 5 deletions SlackAPI.Tests/Configuration/config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
"slack": {
"userAuthToken": "token-tokentoken-tokentoken-tokentoken-token",
"botAuthToken": "bottoken-bottoken-bottoken-bottoken",
"testChannel": "SuperSecretChannel",
"directMessageUser": "someUserId",
"authCode": "some-super-secret-code-from-Slack-specially-created-for-you-=)",
"clientId": "your-special-id",
"clientSecret": "such-special-secret-key"
"testChannelId": "someChannelId",
"directMessageUser": "someUserId",
"authCode": "some-super-secret-code-from-Slack-specially-created-for-you-=)",
"clientId": "your-special-id",
"clientSecret": "such-special-secret-key"
}
}
9 changes: 8 additions & 1 deletion SlackAPI.Tests/Connect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ public void TestConnectAsUser()
Assert.True(client.IsConnected, "Invalid, doesn't think it's connected.");
}

[Fact]
public void TestConnectAsUserWithPresence()
{
var client = this.fixture.UserClientWithPresence;
Assert.True(client.IsConnected, "Invalid, doesn't think it's connected.");
}

[Fact(Skip = "Unable to get a working test with data we have in config.json")]
public void TestGetAccessToken()
{
Expand Down Expand Up @@ -71,7 +78,7 @@ public void TestConnectPostAndDelete()
{
// given
SlackSocketClient client = this.fixture.UserClient;
string channel = this.fixture.Config.TestChannel;
string channel = this.fixture.Config.TestChannelId;

// when
DateTime messageTimestamp = PostMessage(client, channel);
Expand Down
6 changes: 3 additions & 3 deletions SlackAPI.Tests/PostMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public void SimpleMessageDelivery()
actual = response;
sync.Proceed();
},
this.fixture.Config.TestChannel,
this.fixture.Config.TestChannelId,
"Hi there!");
}

Expand All @@ -56,7 +56,7 @@ public void Attachments()
actual = response;
sync.Proceed();
},
this.fixture.Config.TestChannel,
this.fixture.Config.TestChannelId,
string.Empty,
attachments: SlackMother.SomeAttachments);
}
Expand All @@ -81,7 +81,7 @@ public void AttachmentsWithActions()
actual = response;
sync.Proceed();
},
this.fixture.Config.TestChannel,
this.fixture.Config.TestChannelId,
string.Empty,
attachments: SlackMother.SomeAttachmentsWithActions);
}
Expand Down
41 changes: 41 additions & 0 deletions SlackAPI.Tests/PresenceSub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using SlackAPI.Tests.Configuration;
using SlackAPI.Tests.Helpers;
using System.Linq;
using Xunit;

namespace SlackAPI.Tests
{
[Collection("Integration tests")]
public class PresenceSub
{
private readonly IntegrationFixture fixture;

public PresenceSub(IntegrationFixture fixture)
{
this.fixture = fixture;
}

[Fact]
public void PresenceSubscribe()
{
var client = this.fixture.UserClientWithPresence;
var directMessageUser = client.Users.FirstOrDefault(x => x.name == this.fixture.Config.DirectMessageUser);
Assert.NotNull(directMessageUser);

//UserListResponse actual = null;
using (var sync = new InSync(nameof(SlackClient.UserLookup)))
{
client.OnPresenceChangeReceived += (user) =>
{

};
client.OnUserChangeReceived += (user) =>
{

};
client.SendPresenceSub(new[] { directMessageUser.id });
sync.Proceed();
}
}
}
}
1 change: 1 addition & 0 deletions SlackAPI.Tests/SlackAPI.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
<Compile Include="PostMessage.cs" />
<Compile Include="JoinDirectMessageChannel.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PresenceSub.cs" />
<Compile Include="Users.cs" />
</ItemGroup>
<ItemGroup>
Expand Down
5 changes: 3 additions & 2 deletions SlackAPI.Tests/Update.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using SlackAPI.Tests.Configuration;
using SlackAPI.Tests.Helpers;
using System;
using Xunit;

namespace SlackAPI.Tests
Expand Down Expand Up @@ -32,7 +33,7 @@ public void SimpleUpdate()
sync.Proceed();
},
messageId,
this.fixture.Config.TestChannel,
this.fixture.Config.TestChannelId,
"[changed]",
attachments: SlackMother.SomeAttachments,
as_user: true);
Expand All @@ -56,7 +57,7 @@ private string PostedMessage(SlackSocketClient client)
Assert.True(response.ok, "Error while posting message to channel. ");
sync.Proceed();
},
this.fixture.Config.TestChannel,
this.fixture.Config.TestChannelId,
"Hi there!",
as_user: true);
}
Expand Down
1 change: 1 addition & 0 deletions SlackAPI.Tests/Users.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public Users(IntegrationFixture fixture)
{
this.fixture = fixture;
}

[Fact]
public void UserList()
{
Expand Down
2 changes: 1 addition & 1 deletion SlackAPI/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static object Deserialize(this string data, Type type)

private static JsonSerializerSettings CreateSettings()
{
JsonSerializerSettings settings = new JsonSerializerSettings();
var settings = new JsonSerializerSettings();
settings.Converters = Converters;

return settings;
Expand Down
4 changes: 2 additions & 2 deletions SlackAPI/JavascriptBotsToArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ public override bool CanConvert(Type objectType)

public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
List<Bot> bots = new List<Bot>();
var bots = new List<Bot>();
int d = reader.Depth;

while (reader.Read() && reader.Depth > d)
{
Bot current = new Bot();
var current = new Bot();
int depth = reader.Depth;

current.name = reader.Value.ToString();
Expand Down
4 changes: 2 additions & 2 deletions SlackAPI/JavascriptDateTimeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public override bool CanConvert(Type objectType)

public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
decimal value = decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
DateTime res = new DateTime(621355968000000000 + (long)(value * 10000000m)).ToLocalTime();
var value = decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
var res = new DateTime(621355968000000000 + (long)(value * 10000000m)).ToLocalTime();
System.Diagnostics.Debug.Assert(
Decimal.Equals(
Decimal.Parse(res.ToProperTimeStamp()),
Expand Down
14 changes: 7 additions & 7 deletions SlackAPI/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ public void GotRequest(IAsyncResult result)
if (result.AsyncState != this)
throw new InvalidOperationException("This shouldn't be happening! D:");

using (Stream requestStream = request.EndGetRequestStream(result))
using (var requestStream = request.EndGetRequestStream(result))
if (Post.Length > 0)
using (StreamWriter writer = new StreamWriter(requestStream))
using (var writer = new StreamWriter(requestStream))
{
bool first = true;
foreach (Tuple<string, string> postEntry in Post)
Expand Down Expand Up @@ -81,8 +81,8 @@ internal void GotResponse(IAsyncResult result)

K responseObj;

using (Stream responseReading = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseReading))
using (var responseReading = response.GetResponseStream())
using (var reader = new StreamReader(responseReading))
{
string responseData = reader.ReadToEnd();
responseObj = responseData.Deserialize<K>();
Expand All @@ -109,13 +109,13 @@ public RequestPath(string requestPath, bool isPrimaryAPI = true)

public static RequestPath GetRequestPath<K>()
{
Type t = typeof(K);
var t = typeof(K);
if (paths.ContainsKey(t))
return paths[t];

TypeInfo info = t.GetTypeInfo();
var info = t.GetTypeInfo();

RequestPath path = info.GetCustomAttribute<RequestPath>();
var path = info.GetCustomAttribute<RequestPath>();
if (path == null) throw new InvalidOperationException(string.Format("No valid request path for {0}", t.Name));

paths.Add(t, path);
Expand Down
12 changes: 6 additions & 6 deletions SlackAPI/RequestStateForTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ private async Task<K> ExecuteResult()

K responseObj;

using (Stream responseReading = response.GetResponseStream())
using (var responseReading = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseReading))
using (var reader = new StreamReader(responseReading))
{
string responseData = reader.ReadToEnd();
responseObj = responseData.Deserialize<K>();
Expand All @@ -64,14 +64,14 @@ private async Task<K> ExecutePost()
{
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
using (var requestStream = await request.GetRequestStreamAsync())
{
if (Post.Length > 0)
{
using (StreamWriter writer = new StreamWriter(requestStream))
using (var writer = new StreamWriter(requestStream))
{
bool first = true;
foreach (Tuple<string, string> postEntry in Post)
var first = true;
foreach (var postEntry in Post)
{
if (!first)
writer.Write('&');
Expand Down
3 changes: 2 additions & 1 deletion SlackAPI/SlackAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@
<Compile Include="OwnedStampedMessage.cs" />
<Compile Include="RPCMessages\PostMessageResponse.cs" />
<Compile Include="Preferences.cs" />
<Compile Include="RPCMessages\PresenseResponse.cs" />
<Compile Include="RPCMessages\PresenceResponse.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Request.cs" />
<Compile Include="Response.cs" />
Expand Down Expand Up @@ -173,6 +173,7 @@
<Compile Include="WebSocketMessages\NewMessage.cs" />
<Compile Include="WebSocketMessages\Ping.cs" />
<Compile Include="WebSocketMessages\Pong.cs" />
<Compile Include="WebSocketMessages\PresenceSub.cs" />
<Compile Include="WebSocketMessages\PresenceChange.cs" />
<Compile Include="WebSocketMessages\ReactionAdded.cs" />
<Compile Include="WebSocketMessages\SubteamSelfAdded.cs" />
Expand Down
Loading

0 comments on commit 851e8ea

Please sign in to comment.