Skip to content

Commit cde30df

Browse files
Update Unity project and add FileSamples
1 parent 698bb49 commit cde30df

File tree

11 files changed

+446
-31
lines changed

11 files changed

+446
-31
lines changed

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

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,32 @@ public async Task<ChatOperationResult> SendText(string message)
800800
return await SendText(message, new SendTextParams()).ConfigureAwait(false);
801801
}
802802

803+
private async Task<ChatOperationResult<ChatFile>> SendFileForPublish(ChatInputFile inputFile)
804+
{
805+
var result = new ChatOperationResult<ChatFile>("Channel.SendFileForPublish()", chat);
806+
var send = await chat.PubnubInstance.SendFile().Channel(Id).File(inputFile.Source).FileName(inputFile.Name)
807+
.ShouldStore(false)
808+
.ExecuteAsync().ConfigureAwait(false);
809+
if (result.RegisterOperation(send))
810+
{
811+
return result;
812+
}
813+
var getUrl = await chat.PubnubInstance.GetFileUrl().Channel(Id).FileId(send.Result.FileId)
814+
.FileName(send.Result.FileName).ExecuteAsync().ConfigureAwait(false);
815+
if (result.RegisterOperation(getUrl))
816+
{
817+
return result;
818+
}
819+
result.Result = new ChatFile()
820+
{
821+
Id = send.Result.FileId,
822+
Name = send.Result.FileName,
823+
Type = inputFile.Type,
824+
Url = getUrl.Result.Url
825+
};
826+
return result;
827+
}
828+
803829
/// <summary>
804830
/// Sends the text message with additional parameters.
805831
/// <para>
@@ -812,6 +838,7 @@ public async Task<ChatOperationResult> SendText(string message)
812838
public virtual async Task<ChatOperationResult> SendText(string message, SendTextParams sendTextParams)
813839
{
814840
var result = new ChatOperationResult("Channel.SendText()", chat);
841+
var jsonLibrary = chat.PubnubInstance.JsonPluggableLibrary;
815842

816843
var baseInterval = Type switch
817844
{
@@ -829,6 +856,26 @@ public virtual async Task<ChatOperationResult> SendText(string message, SendText
829856
{"text", message},
830857
{"type", "text"}
831858
};
859+
if (sendTextParams.Files.Any())
860+
{
861+
var fileTasks = sendTextParams.Files.Select(SendFileForPublish);
862+
var fileResults = await Task.WhenAll(fileTasks).ConfigureAwait(false);
863+
foreach (var fileResult in fileResults)
864+
{
865+
result.RegisterOperation(fileResult);
866+
}
867+
var failedUploads = fileResults.Where(x => x.Error).ToList();
868+
if (failedUploads.Any())
869+
{
870+
var combinedException = string.Join("\n",failedUploads.Select(x => x.Exception.Message));
871+
result.Exception = new PNException($"Message publishing aborted: {failedUploads.Count} out of {fileResults.Length} " +
872+
$"file uploads failed. Exceptions from file uploads: {combinedException}");
873+
result.Error = true;
874+
return result;
875+
}
876+
var chatFilesAsDictionaries = fileResults.Select(x => x.Result.ToDictionary()).ToList();
877+
messageDict["files"] = jsonLibrary.SerializeToJsonString(chatFilesAsDictionaries);
878+
}
832879
var meta = sendTextParams.Meta ?? new Dictionary<string, object>();
833880
if (sendTextParams.QuotedMessage != null)
834881
{
@@ -851,7 +898,7 @@ public virtual async Task<ChatOperationResult> SendText(string message, SendText
851898
.Channel(Id)
852899
.ShouldStore(sendTextParams.StoreInHistory)
853900
.UsePOST(sendTextParams.SendByPost)
854-
.Message(chat.PubnubInstance.JsonPluggableLibrary.SerializeToJsonString(messageDict))
901+
.Message(jsonLibrary.SerializeToJsonString(messageDict))
855902
.Meta(meta)
856903
.ExecuteAsync().ConfigureAwait(false);
857904
if (result.RegisterOperation(publishResult))
@@ -874,6 +921,8 @@ public virtual async Task<ChatOperationResult> SendText(string message, SendText
874921
}, exception =>
875922
{
876923
chat.Logger.Error($"Error occured when trying to SendText(): {exception.Message}");
924+
result.Error = true;
925+
result.Exception = new PNException($"Encountered exception in SendText(): {exception.Message}");
877926
completionSource.SetResult(true);
878927
});
879928

@@ -1242,5 +1291,71 @@ public async Task<ChatOperationResult<List<Membership>>> InviteMultiple(List<Use
12421291
{
12431292
return await chat.InviteMultipleToChannel(Id, users).ConfigureAwait(false);
12441293
}
1294+
1295+
/// <summary>
1296+
/// Retrieves a wrapper object with a of files that were sent on this channel.
1297+
/// </summary>
1298+
/// <param name="limit">Optional - number of files to return.</param>
1299+
/// <param name="next">Optional - String token to get the next batch of files.</param>
1300+
public async Task<ChatOperationResult<ChatFilesResult>> GetFiles(int limit = 0, string next = "")
1301+
{
1302+
var result = new ChatOperationResult<ChatFilesResult>("Channel.GetFiles()", chat);
1303+
1304+
var listFilesOperation = chat.PubnubInstance.ListFiles().Channel(Id);
1305+
if (limit > 0)
1306+
{
1307+
listFilesOperation = listFilesOperation.Limit(limit);
1308+
}
1309+
if (!string.IsNullOrEmpty(next))
1310+
{
1311+
listFilesOperation = listFilesOperation.Next(next);
1312+
}
1313+
var listFiles = await listFilesOperation.ExecuteAsync().ConfigureAwait(false);
1314+
if (result.RegisterOperation(listFiles))
1315+
{
1316+
return result;
1317+
}
1318+
1319+
var files = new List<ChatFile>();
1320+
if (listFiles.Result.FilesList != null && listFiles.Result.FilesList.Any())
1321+
{
1322+
var getUrlsTasks = listFiles.Result.FilesList.Select(x =>
1323+
chat.PubnubInstance.GetFileUrl().Channel(Id).FileId(x.Id).FileName(x.Name).ExecuteAsync());
1324+
var getUrls = await Task.WhenAll(getUrlsTasks).ConfigureAwait(false);
1325+
foreach (var pnResult in getUrls)
1326+
{
1327+
if (result.RegisterOperation(pnResult))
1328+
{
1329+
return result;
1330+
}
1331+
}
1332+
for (int i = 0; i < listFiles.Result.FilesList.Count; i++)
1333+
{
1334+
files.Add(new ChatFile()
1335+
{
1336+
Id = listFiles.Result.FilesList[i].Id,
1337+
Name = listFiles.Result.FilesList[i].Name,
1338+
Url = getUrls[i].Result.Url,
1339+
});
1340+
}
1341+
}
1342+
1343+
result.Result = new ChatFilesResult()
1344+
{
1345+
Files = files,
1346+
Next = listFiles.Result.Next,
1347+
Total = listFiles.Result.Count
1348+
};
1349+
return result;
1350+
}
1351+
1352+
/// <summary>
1353+
/// Deletes a file with a specified Id and Name from this channel.
1354+
/// </summary>
1355+
public async Task<ChatOperationResult> DeleteFile(string id, string name)
1356+
{
1357+
return (await chat.PubnubInstance.DeleteFile().Channel(Id).FileId(id).FileName(name).ExecuteAsync())
1358+
.ToChatOperationResult("Channel.DeleteFile()", chat);
1359+
}
12451360
}
12461361
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System.Collections.Generic;
2+
using PubnubApi;
3+
4+
namespace PubnubChatApi
5+
{
6+
public class ChatFilesResult
7+
{
8+
public List<ChatFile> Files;
9+
public string Next;
10+
public int Total;
11+
}
12+
13+
public class ChatFile
14+
{
15+
public string Name;
16+
public string Id;
17+
public string Url;
18+
public string Type;
19+
20+
internal Dictionary<string, string> ToDictionary()
21+
{
22+
return new Dictionary<string, string>()
23+
{
24+
{ "name", Name },
25+
{ "id", Id },
26+
{ "url", Url },
27+
{ "type", Type }
28+
};
29+
}
30+
}
31+
32+
public struct ChatInputFile
33+
{
34+
public string Name;
35+
public string Type;
36+
public string Source;
37+
}
38+
}

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

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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
@@ -9,5 +9,6 @@ public class SendTextParams
99
public Dictionary<string, object> Meta = new();
1010
public Dictionary<int, MentionedUser> MentionedUsers = new();
1111
public Message QuotedMessage = null;
12+
public List<ChatInputFile> Files = new();
1213
}
1314
}

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,10 @@ public List<TextLink> TextLinks {
211211
/// <seealso cref="pubnub_chat_message_type"/>
212212
public PubnubChatMessageType Type { get; internal set; }
213213

214+
/// <summary>
215+
/// Files sent within this message.
216+
/// </summary>
217+
public List<ChatFile> Files { get; }
214218

215219
/// <summary>
216220
/// Event that is triggered when the message is updated.
@@ -234,7 +238,7 @@ public List<TextLink> TextLinks {
234238

235239
protected override string UpdateChannelId => ChannelId;
236240

237-
internal Message(Chat chat, string timeToken,string originalMessageText, string channelId, string userId, PubnubChatMessageType type, Dictionary<string, object> meta, List<MessageAction> messageActions) : base(chat, timeToken)
241+
internal Message(Chat chat, string timeToken,string originalMessageText, string channelId, string userId, PubnubChatMessageType type, Dictionary<string, object> meta, List<MessageAction> messageActions, List<ChatFile> files) : base(chat, timeToken)
238242
{
239243
TimeToken = timeToken;
240244
OriginalMessageText = originalMessageText;
@@ -243,6 +247,7 @@ internal Message(Chat chat, string timeToken,string originalMessageText, string
243247
Type = type;
244248
Meta = meta;
245249
MessageActions = messageActions;
250+
Files = files;
246251
}
247252

248253
protected override SubscribeCallback CreateUpdateListener()

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,16 @@ private class DraftCallbackDataHelper
105105
/// </summary>
106106
public List<MessageElement> MessageElements => GetMessageElements();
107107

108+
/// <summary>
109+
/// Defines whether this MessageDraft should search for suggestions after it's content is updated.
110+
/// </summary>
108111
public bool ShouldSearchForSuggestions { get; set; }
109112

113+
/// <summary>
114+
/// Can be used to attach files to send with this MessageDraft.
115+
/// </summary>
116+
public List<ChatInputFile> Files { get; set; } = new();
117+
110118
private Channel channel;
111119
private Chat chat;
112120

@@ -579,6 +587,7 @@ public async Task<ChatOperationResult> Send(SendTextParams sendTextParams)
579587
}
580588
}
581589
sendTextParams.MentionedUsers = mentions;
590+
sendTextParams.Files = Files;
582591
return await channel.SendText(Render(), sendTextParams).ConfigureAwait(false);
583592
}
584593

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public async Task<ChatOperationResult<List<ThreadMessage>>> GetThreadHistory(str
9292
{
9393
result.Result.Add(new ThreadMessage(chat, message.TimeToken, message.OriginalMessageText,
9494
message.ChannelId, ParentChannelId, message.UserId, PubnubChatMessageType.Text, message.Meta,
95-
message.MessageActions));
95+
message.MessageActions, message.Files));
9696
}
9797

9898
return result;

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ public class ThreadMessage : Message
1313

1414
internal ThreadMessage(Chat chat, string timeToken, string originalMessageText, string channelId,
1515
string parentChannelId, string userId, PubnubChatMessageType type, Dictionary<string, object> meta,
16-
List<MessageAction> messageActions) : base(chat, timeToken, originalMessageText, channelId, userId, type,
17-
meta, messageActions)
16+
List<MessageAction> messageActions, List<ChatFile> files) : base(chat, timeToken, originalMessageText, channelId, userId, type,
17+
meta, messageActions, files)
1818
{
1919
ParentChannelId = parentChannelId;
2020
}

0 commit comments

Comments
 (0)