Skip to content

Commit 114e20f

Browse files
Import Push changes to Unity project + add samples
1 parent 2e128be commit 114e20f

File tree

7 files changed

+334
-4
lines changed

7 files changed

+334
-4
lines changed

unity-chat/PubnubChatUnity/Assets/PubnubChat/Runtime/PubnubChatApi/Entities/Channel.cs

Lines changed: 83 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Threading.Tasks;
55
using System.Timers;
66
using PubnubApi;
7+
using Environment = PubnubApi.Environment;
78

89
namespace PubnubChatApi
910
{
@@ -856,6 +857,15 @@ public virtual async Task<ChatOperationResult> SendText(string message, SendText
856857
{"text", message},
857858
{"type", "text"}
858859
};
860+
if (chat.Config.PushNotifications is { SendPushes : true})
861+
{
862+
var pushPayload = await GetPushPayload(message, sendTextParams.CustomPushData ?? new Dictionary<string, string>());
863+
foreach (var kvp in pushPayload)
864+
{
865+
var pushJson = jsonLibrary.SerializeToJsonString(kvp.Value);
866+
messageDict[kvp.Key] = pushJson;
867+
}
868+
}
859869
if (sendTextParams.Files.Any())
860870
{
861871
var fileTasks = sendTextParams.Files.Select(SendFileForPublish);
@@ -1157,6 +1167,8 @@ public async Task<ChatOperationResult<bool>> IsUserPresent(string userId)
11571167
/// Gets all the users that are present in the channel.
11581168
/// </para>
11591169
/// </summary>
1170+
/// <param name="limit">Limit number of users details to be returned. Default and max value is 1000.</param>
1171+
/// <param name="offset">Use this parameter to provide starting position of results for pagination purpose. Default value is 0.</param>
11601172
/// <returns>A ChatOperationResult containing the list of users present in the channel.</returns>
11611173
/// <example>
11621174
/// <code>
@@ -1169,11 +1181,15 @@ public async Task<ChatOperationResult<bool>> IsUserPresent(string userId)
11691181
/// </code>
11701182
/// </example>
11711183
/// <seealso cref="IsUserPresent"/>
1172-
public async Task<ChatOperationResult<List<string>>> WhoIsPresent()
1184+
public async Task<ChatOperationResult<List<string>>> WhoIsPresent(int limit = 1000, int offset = 0)
11731185
{
1186+
if (limit > 1000)
1187+
{
1188+
limit = 1000;
1189+
}
11741190
var result = new ChatOperationResult<List<string>>("Channel.WhoIsPresent()", chat) { Result = new List<string>() };
11751191
var response = await chat.PubnubInstance.HereNow().Channels(new[] { Id }).IncludeState(true)
1176-
.IncludeUUIDs(true).ExecuteAsync().ConfigureAwait(false);
1192+
.IncludeUUIDs(true).Limit(limit).Offset(offset).ExecuteAsync().ConfigureAwait(false);
11771193
if (result.RegisterOperation(response))
11781194
{
11791195
return result;
@@ -1357,5 +1373,70 @@ public async Task<ChatOperationResult> DeleteFile(string id, string name)
13571373
return (await chat.PubnubInstance.DeleteFile().Channel(Id).FileId(id).FileName(name).ExecuteAsync())
13581374
.ToChatOperationResult("Channel.DeleteFile()", chat);
13591375
}
1376+
1377+
private async Task<Dictionary<string, object>> GetPushPayload(string text, Dictionary<string, string> customPushData)
1378+
{
1379+
var pushConfig = chat.Config.PushNotifications;
1380+
if (pushConfig == null || pushConfig.SendPushes == false)
1381+
{
1382+
return new Dictionary<string, object>();
1383+
}
1384+
var title = chat.PubnubInstance.GetCurrentUserId().ToString();
1385+
var currentUser = await chat.GetCurrentUser();
1386+
if (!currentUser.Error && !string.IsNullOrEmpty(currentUser.Result.UserName))
1387+
{
1388+
title = currentUser.Result.UserName;
1389+
}
1390+
var customData = new Dictionary<string, object>();
1391+
foreach (var entry in customPushData)
1392+
{
1393+
customData.Add(entry.Key, entry.Value);
1394+
}
1395+
if (!string.IsNullOrEmpty(Name))
1396+
{
1397+
customData["subtitle"] = Name;
1398+
}
1399+
1400+
var finalCustom = new Dictionary<PNPushType, Dictionary<string, object>>()
1401+
{
1402+
{ PNPushType.FCM, customData }
1403+
};
1404+
var pushBuilder = new MobilePushHelper().PushTypeSupport(new[] { PNPushType.APNS2, PNPushType.FCM })
1405+
.Title(title).Sound("default").Body(text);
1406+
1407+
var apnsTopic = pushConfig.APNSTopic;
1408+
if (!string.IsNullOrEmpty(apnsTopic))
1409+
{
1410+
var apnsEnv = pushConfig.APNSEnvironment;
1411+
pushBuilder.Apns2Data(new List<Apns2Data>()
1412+
{
1413+
new Apns2Data()
1414+
{
1415+
targets = new List<PushTarget>()
1416+
{ new PushTarget() { topic = apnsTopic, environment = (Environment)apnsEnv } },
1417+
}
1418+
});
1419+
finalCustom.Add(PNPushType.APNS2, customData);
1420+
}
1421+
pushBuilder.Custom(finalCustom);
1422+
1423+
return pushBuilder.GetPayload();
1424+
}
1425+
1426+
/// <summary>
1427+
/// Registers this channel to receive push notifications.
1428+
/// </summary>
1429+
public async Task<ChatOperationResult> RegisterForPush()
1430+
{
1431+
return await chat.RegisterPushChannels(new List<string>() { Id }).ConfigureAwait(false);
1432+
}
1433+
1434+
/// <summary>
1435+
/// Un-Registers this channel from receiving push notifications.
1436+
/// </summary>
1437+
public async Task<ChatOperationResult> UnRegisterFromPush()
1438+
{
1439+
return await chat.UnRegisterPushChannels(new List<string>() { Id }).ConfigureAwait(false);
1440+
}
13601441
}
13611442
}

unity-chat/PubnubChatUnity/Assets/PubnubChat/Runtime/PubnubChatApi/Entities/Chat.cs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1716,6 +1716,88 @@ public async Task<ChatOperationResult> EmitEvent(PubnubChatEventType type, strin
17161716

17171717
#endregion
17181718

1719+
#region Push
1720+
1721+
/// <summary>
1722+
/// Retrieves the Push Notifications config from the main Chat config.
1723+
/// Alternatively you can also use Config.PushNotifications
1724+
/// </summary>
1725+
public PubnubChatConfig.PushNotificationsConfig GetCommonPushOptions => Config.PushNotifications;
1726+
1727+
/// <summary>
1728+
/// Registers a list of channels to receive push notifications.
1729+
/// </summary>
1730+
public async Task<ChatOperationResult> RegisterPushChannels(List<string> channelIds)
1731+
{
1732+
var pushSettings = GetCommonPushOptions;
1733+
return (await PubnubInstance.AddPushNotificationsOnChannels()
1734+
.Channels(channelIds.ToArray())
1735+
.PushType(pushSettings.DeviceGateway)
1736+
.DeviceId(pushSettings.DeviceToken)
1737+
.Topic(pushSettings.APNSTopic)
1738+
.Environment(pushSettings.APNSEnvironment)
1739+
.ExecuteAsync()
1740+
.ConfigureAwait(false))
1741+
.ToChatOperationResult("Chat.RegisterPushChannels()", this);
1742+
}
1743+
1744+
/// <summary>
1745+
/// Un-registers a list of channels from receiving push notifications.
1746+
/// </summary>
1747+
public async Task<ChatOperationResult> UnRegisterPushChannels(List<string> channelIds)
1748+
{
1749+
var pushSettings = GetCommonPushOptions;
1750+
return (await PubnubInstance.RemovePushNotificationsFromChannels()
1751+
.Channels(channelIds.ToArray())
1752+
.PushType(pushSettings.DeviceGateway)
1753+
.DeviceId(pushSettings.DeviceToken)
1754+
.Topic(pushSettings.APNSTopic)
1755+
.Environment(pushSettings.APNSEnvironment)
1756+
.ExecuteAsync()
1757+
.ConfigureAwait(false))
1758+
.ToChatOperationResult("Chat.RegisterPushChannels()", this);
1759+
}
1760+
1761+
/// <summary>
1762+
/// Un-registers all channels from receiving push notifications.
1763+
/// </summary>
1764+
public async Task<ChatOperationResult> UnRegisterAllPushChannels()
1765+
{
1766+
var pushSettings = GetCommonPushOptions;
1767+
return (await PubnubInstance.RemoveAllPushNotificationsFromDeviceWithPushToken()
1768+
.PushType(pushSettings.DeviceGateway)
1769+
.DeviceId(pushSettings.DeviceToken)
1770+
.Topic(pushSettings.APNSTopic)
1771+
.Environment(pushSettings.APNSEnvironment)
1772+
.ExecuteAsync()
1773+
.ConfigureAwait(false))
1774+
.ToChatOperationResult("Chat.RegisterPushChannels()", this);
1775+
}
1776+
1777+
/// <summary>
1778+
/// Returns the IDs of all currently registered push channels.
1779+
/// </summary>
1780+
public async Task<ChatOperationResult<List<string>>> GetPushChannels()
1781+
{
1782+
var result = new ChatOperationResult<List<string>>("Chat.GetPushChannels()", this);
1783+
var pushSettings = GetCommonPushOptions;
1784+
var audit = await PubnubInstance.AuditPushChannelProvisions()
1785+
.PushType(pushSettings.DeviceGateway)
1786+
.DeviceId(pushSettings.DeviceToken)
1787+
.Topic(pushSettings.APNSTopic)
1788+
.Environment(pushSettings.APNSEnvironment)
1789+
.ExecuteAsync()
1790+
.ConfigureAwait(false);
1791+
if (result.RegisterOperation(audit))
1792+
{
1793+
return result;
1794+
}
1795+
result.Result = audit.Result.Channels;
1796+
return result;
1797+
}
1798+
1799+
#endregion
1800+
17191801
/// <summary>
17201802
/// Destroys the chat instance and cleans up resources.
17211803
/// <para>

unity-chat/PubnubChatUnity/Assets/PubnubChat/Runtime/PubnubChatApi/Entities/Data/PubnubChatConfig.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,16 @@ namespace PubnubChatApi
44
{
55
public class PubnubChatConfig
66
{
7+
[System.Serializable]
8+
public class PushNotificationsConfig
9+
{
10+
public bool SendPushes;
11+
public string DeviceToken;
12+
public PNPushType DeviceGateway = PNPushType.FCM;
13+
public string APNSTopic;
14+
public PushEnvironment APNSEnvironment = PushEnvironment.Development;
15+
}
16+
717
[System.Serializable]
818
public class RateLimitPerChannel
919
{
@@ -20,10 +30,11 @@ public class RateLimitPerChannel
2030
public bool StoreUserActivityTimestamp { get; }
2131
public int StoreUserActivityInterval { get; }
2232
public bool SyncMutedUsers { get; }
33+
public PushNotificationsConfig PushNotifications { get; }
2334

2435
public PubnubChatConfig(int typingTimeout = 5000, int typingTimeoutDifference = 1000, int rateLimitFactor = 2,
2536
RateLimitPerChannel rateLimitPerChannel = null, bool storeUserActivityTimestamp = false,
26-
int storeUserActivityInterval = 60000, bool syncMutedUsers = false)
37+
int storeUserActivityInterval = 60000, bool syncMutedUsers = false, PushNotificationsConfig pushNotifications = null)
2738
{
2839
RateLimitsPerChannel = rateLimitPerChannel ?? new RateLimitPerChannel();
2940
RateLimitFactor = rateLimitFactor;
@@ -32,6 +43,7 @@ public PubnubChatConfig(int typingTimeout = 5000, int typingTimeoutDifference =
3243
TypingTimeout = typingTimeout;
3344
TypingTimeoutDifference = typingTimeoutDifference;
3445
SyncMutedUsers = syncMutedUsers;
46+
PushNotifications = pushNotifications ?? new PushNotificationsConfig();
3547
}
3648
}
3749
}

unity-chat/PubnubChatUnity/Assets/PubnubChat/Runtime/PubnubChatApi/Entities/Data/SendTextParams.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ public class SendTextParams
1010
public Dictionary<int, MentionedUser> MentionedUsers = new();
1111
public Message QuotedMessage = null;
1212
public List<ChatInputFile> Files = new();
13+
public Dictionary<string, string> CustomPushData = new();
1314
}
1415
}

unity-chat/PubnubChatUnity/Assets/PubnubChat/Samples~/PubnubChatConfigAsset/PubnubChatConfigAsset.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public class PubnubChatConfigAsset : ScriptableObject
1313
[field: SerializeField] public bool StoreUserActivityTimestamp { get; private set; }
1414
[field: SerializeField] public int StoreUserActivityInterval { get; private set; } = 60000;
1515
[field: SerializeField] public bool SyncMutedUsers { get; private set; } = false;
16+
[field: SerializeField] public PubnubChatConfig.PushNotificationsConfig PushNotifications { get; private set; } = new ();
1617

1718
public static implicit operator PubnubChatConfig(PubnubChatConfigAsset asset)
1819
{
@@ -22,7 +23,8 @@ public static implicit operator PubnubChatConfig(PubnubChatConfigAsset asset)
2223
rateLimitPerChannel: asset.RateLimitPerChannel,
2324
storeUserActivityInterval: asset.StoreUserActivityInterval,
2425
storeUserActivityTimestamp: asset.StoreUserActivityTimestamp,
25-
syncMutedUsers: asset.SyncMutedUsers);
26+
syncMutedUsers: asset.SyncMutedUsers,
27+
pushNotifications: asset.PushNotifications);
2628
}
2729
}
2830
}

0 commit comments

Comments
 (0)