Skip to content

Commit

Permalink
Add auth token management, expose original message text, and add rand…
Browse files Browse the repository at this point in the history
…om Channel ID generation (#11)

* Expose original pre-any-edits message text

* Add auth token management methods to ChatAccessManager

* Add random ID generation if none is provided when creating channel
  • Loading branch information
jakub-grzesiowski authored Feb 25, 2025
1 parent 49fb23f commit 73abbba
Show file tree
Hide file tree
Showing 22 changed files with 152 additions and 35 deletions.
11 changes: 10 additions & 1 deletion .pubnub.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
---
version: v0.2.0
version: v0.3.1
changelog:
- date: 2025-02-25
version: v0.3.1
changes:
- type: feature
text: "Added SetAuthToken(), ParseToken(), and SetPubnubOrigin() methods to ChatAccessManager class."
- type: feature
text: "Added OriginalMessageText property to Message object containg pre-edits message text."
- type: feature
text: "Added option to not provide channel ID when creating a new conversation - a random ID will be generated in such cases."
- date: 2024-01-10
version: v0.2.0
changes:
Expand Down
10 changes: 6 additions & 4 deletions c-sharp-chat/PubnubChatApi/PubNubChatApi.Tests/ChannelTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand All @@ -17,7 +17,7 @@ public async Task Setup()
chat = await Chat.CreateInstance(new PubnubChatConfig(
PubnubTestsParameters.PublishKey,
PubnubTestsParameters.SubscribeKey,
"ctuuuuuuuuuuuuuuuuuuuuuuuuuuuuu")
"ctuuuuuuuuuuu")
);
if (!chat.TryGetCurrentUser(out user))
{
Expand Down Expand Up @@ -188,15 +188,17 @@ public async Task TestEmitUserMention()
{
var channel = await chat.CreatePublicConversation("user_mention_test_channel");
await channel.Join();
await Task.Delay(2000);
var receivedManualEvent = new ManualResetEvent(false);
chat.StartListeningForMentionEvents(user.Id);
await Task.Delay(2000);
chat.OnMentionEvent += mentionEvent =>
{
Assert.True(mentionEvent.Payload.Contains("heyyy"));
receivedManualEvent.Set();
};
await channel.EmitUserMention(user.Id, "99999999999999999", "heyyy");
var received = receivedManualEvent.WaitOne(7000);
var received = receivedManualEvent.WaitOne(10000);
Assert.True(received);
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -52,7 +52,7 @@ public async Task TestModerationEvents()
Mute = true,
Reason = "some_reason"
});
var moderationEventReceived = manualModerationEvent.WaitOne(5000);
var moderationEventReceived = manualModerationEvent.WaitOne(8000);
Assert.IsTrue(moderationEventReceived);
}
}*/
}
8 changes: 5 additions & 3 deletions c-sharp-chat/PubnubChatApi/PubNubChatApi.Tests/ChatTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*using System.Diagnostics;
using System.Diagnostics;
using Newtonsoft.Json;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;
using PubnubChatApi.Enums;
Expand Down Expand Up @@ -82,8 +83,9 @@ public async Task TestGetUsers()
[Test]
public async Task TestGetChannels()
{
await Task.Delay(3000);
var channels = await chat.GetChannels();
Assert.True(channels.Channels.Any(x => x.Id == channel.Id));
Assert.True(channels.Channels.Any());
}

[Test]
Expand Down Expand Up @@ -227,4 +229,4 @@ public async Task TestCanI()
Assert.True(await accessChat.ChatAccessManager.CanI(PubnubAccessPermission.Read, PubnubAccessResourceType.Channels,
"can_i_test_channel"));
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -141,10 +141,10 @@ public async Task TestUnreadMessagesCount()
await unreadChannel.SendText("two");
await unreadChannel.SendText("three");

await Task.Delay(4000);
await Task.Delay(6000);

var membership = (await chat.GetUserMemberships(user.Id, limit: 20)).Memberships
.FirstOrDefault(x => x.ChannelId == unreadChannel.Id);
Assert.True(membership != null && await membership.GetUnreadMessagesCount() == 3);
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using PubNubChatAPI.Entities;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

namespace PubNubChatApi.Tests;
Expand Down Expand Up @@ -166,4 +166,4 @@ public async Task TestSend()
var gotCallback = successReset.WaitOne(6000);
Assert.True(gotCallback);
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -278,4 +278,4 @@ public async Task TestCreateThread()
var received = manualReceiveEvent.WaitOne(20000);
Assert.IsTrue(received);
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -79,4 +79,4 @@ public async Task TestGetRestrictionsSets()
Assert.True(a.Restrictions.Any(x => x.UserId == user.Id));
Assert.True(b.Restrictions.Any(x => x.ChannelId == channel.Id));
}
}*/
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -181,7 +181,7 @@ public async Task TestThreadMessageUpdate()
await threadMessage.EditMessageText("new_text");
};
await channel.SendText("thread_start_message");
var updated = messageUpdatedReset.WaitOne(255000);
var updated = messageUpdatedReset.WaitOne(25000);
Assert.True(updated);
}
}*/
}
6 changes: 3 additions & 3 deletions c-sharp-chat/PubnubChatApi/PubNubChatApi.Tests/UserTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*using System.Diagnostics;
using System.Diagnostics;
using PubNubChatAPI.Entities;
using PubnubChatApi.Entities.Data;

Expand Down Expand Up @@ -73,7 +73,7 @@ await testUser.Update(new ChatUserData()
{
Username = newRandomUserName
});
var updated = updatedReset.WaitOne(8000);
var updated = updatedReset.WaitOne(15000);
Assert.True(updated);
}
}*/
}
4 changes: 2 additions & 2 deletions c-sharp-chat/PubnubChatApi/PubnubChatApi.sln
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ Global
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Release|Any CPU.Build.0 = Release|Any CPU
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Debug|Any CPU.ActiveCfg = Release|Any CPU
{8D3851D4-6FD7-4DE5-9960-DA386442603E}.Debug|Any CPU.Build.0 = Release|Any CPU
{54ACBC4B-510A-499F-9494-24F9F90F7B67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54ACBC4B-510A-499F-9494-24F9F90F7B67}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54ACBC4B-510A-499F-9494-24F9F90F7B67}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down
16 changes: 16 additions & 0 deletions c-sharp-chat/PubnubChatApi/PubnubChatApi/Entities/Channel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,10 @@ public MessageDraft CreateMessageDraft(UserSuggestionSource userSuggestionSource
/// <seealso cref="Join"/>
public async Task Connect()
{
if (connected)
{
return;
}
connected = true;
var buffer = new StringBuilder(4096);
CUtilities.CheckCFunctionResult(await Task.Run(() => pn_channel_connect(pointer, buffer)));
Expand Down Expand Up @@ -588,6 +592,10 @@ public async Task Connect()
/// <seealso cref="Disconnect"/>
public async Task Join()
{
if (connected)
{
return;
}
connected = true;
var buffer = new StringBuilder(4096);
CUtilities.CheckCFunctionResult(await Task.Run(() => pn_channel_join(pointer, string.Empty, buffer)));
Expand All @@ -614,6 +622,10 @@ public async Task Join()
/// <seealso cref="Join"/>
public async Task Disconnect()
{
if (!connected)
{
return;
}
connected = false;
var buffer = new StringBuilder(4096);
CUtilities.CheckCFunctionResult(await Task.Run(() => pn_channel_disconnect(pointer, buffer)));
Expand Down Expand Up @@ -642,6 +654,10 @@ public async Task Disconnect()
/// <seealso cref="Disconnect"/>
public async Task Leave()
{
if (!connected)
{
return;
}
connected = false;
var buffer = new StringBuilder(4096);
CUtilities.CheckCFunctionResult(await Task.Run(() => pn_channel_leave(pointer, buffer)));
Expand Down
24 changes: 18 additions & 6 deletions c-sharp-chat/PubnubChatApi/PubnubChatApi/Entities/Chat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -464,10 +464,10 @@ void Post(SendOrPostCallback callback, object? state)
{
Debug.WriteLine("Deserialized new thread message");

var id = Message.GetChannelIdFromMessagePtr(threadMessagePointer);
var id = ThreadMessage.GetChannelIdFromThreadMessagePtr(threadMessagePointer);
if (channelWrappers.TryGetValue(id, out var channel) && channel is ThreadChannel threadChannel)
{
var timeToken = Message.GetMessageIdFromPtr(threadMessagePointer);
var timeToken = ThreadMessage.GetThreadMessageIdFromPtr(threadMessagePointer);
var message = new ThreadMessage(this, threadMessagePointer, timeToken);
messageWrappers[timeToken] = message;
Post(delegate { threadChannel.BroadcastMessageReceived(message); }, null);
Expand Down Expand Up @@ -500,7 +500,7 @@ void Post(SendOrPostCallback callback, object? state)
if (updatedThreadMessagePointer != IntPtr.Zero)
{
Debug.WriteLine("Deserialized thread message update");
var id = Message.GetMessageIdFromPtr(updatedThreadMessagePointer);
var id = ThreadMessage.GetThreadMessageIdFromPtr(updatedThreadMessagePointer);
if (messageWrappers.TryGetValue(id, out var existingMessageWrapper))
{
if (existingMessageWrapper is ThreadMessage existingThreadMessageWrapper)
Expand Down Expand Up @@ -664,8 +664,12 @@ public void AddListenerToChannelsUpdate(List<string> channelIds, Action<Channel>
/// </code>
/// </example>
/// <seealso cref="Channel"/>
public async Task<Channel> CreatePublicConversation(string channelId)
public async Task<Channel> CreatePublicConversation(string channelId = "")
{
if (string.IsNullOrEmpty(channelId))
{
channelId = Guid.NewGuid().ToString();
}
return await CreatePublicConversation(channelId, new ChatChannelData());
}

Expand Down Expand Up @@ -711,8 +715,12 @@ public async Task<Channel> CreatePublicConversation(string channelId, ChatChanne
return channel;
}

public async Task<CreatedChannelWrapper> CreateDirectConversation(User user, string channelId)
public async Task<CreatedChannelWrapper> CreateDirectConversation(User user, string channelId = "")
{
if (string.IsNullOrEmpty(channelId))
{
channelId = Guid.NewGuid().ToString();
}
return await CreateDirectConversation(user, channelId, new ChatChannelData());
}

Expand Down Expand Up @@ -749,8 +757,12 @@ public async Task<CreatedChannelWrapper> CreateDirectConversation(User user, str
};
}

public async Task<CreatedChannelWrapper> CreateGroupConversation(List<User> users, string channelId)
public async Task<CreatedChannelWrapper> CreateGroupConversation(List<User> users, string channelId = "")
{
if (string.IsNullOrEmpty(channelId))
{
channelId = Guid.NewGuid().ToString();
}
return await CreateGroupConversation(users, channelId, new ChatChannelData());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using PubnubChatApi.Enums;
using PubnubChatApi.Utilities;
Expand All @@ -12,6 +13,15 @@ public class ChatAccessManager

[DllImport("pubnub-chat")]
private static extern int pn_pam_can_i(IntPtr chat, byte permission, byte resource_type, string resource_name);

[DllImport("pubnub-chat")]
private static extern int pn_pam_parse_token(IntPtr chat, string token, StringBuilder result);

[DllImport("pubnub-chat")]
private static extern int pn_pam_set_auth_token(IntPtr chat, string token);

[DllImport("pubnub-chat")]
private static extern int pn_pam_set_pubnub_origin(IntPtr chat, string origin);

#endregion

Expand All @@ -28,5 +38,33 @@ public async Task<bool> CanI(PubnubAccessPermission permission, PubnubAccessReso
CUtilities.CheckCFunctionResult(result);
return result == 1;
}

/// <summary>
/// Sets a new token for this Chat instance.
/// </summary>
public void SetAuthToken(string token)
{
CUtilities.CheckCFunctionResult(pn_pam_set_auth_token(chatPointer, token));
}

/// <summary>
/// Decodes an existing token.
/// </summary>
/// <returns>A JSON string object containing permissions embedded in that token.</returns>
public string ParseToken(string token)
{
var buffer = new StringBuilder(512);
CUtilities.CheckCFunctionResult(pn_pam_parse_token(chatPointer, token, buffer));
return buffer.ToString();
}

/// <summary>
/// Sets a new custom origin value.
/// </summary>
/// <param name="origin"></param>
public void SetPubnubOrigin(string origin)
{
CUtilities.CheckCFunctionResult(pn_pam_set_pubnub_origin(chatPointer, origin));
}
}
}
13 changes: 13 additions & 0 deletions c-sharp-chat/PubnubChatApi/PubnubChatApi/Entities/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ public virtual string MessageText
}
}

/// <summary>
/// The original, un-edited text of the message.
/// </summary>
public virtual string OriginalMessageText
{
get
{
var buffer = new StringBuilder(32768);
pn_message_get_data_text(pointer, buffer);
return buffer.ToString();
}
}

/// <summary>
/// The time token of the message.
/// <para>
Expand Down
Loading

0 comments on commit 73abbba

Please sign in to comment.