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

Implement UpdateActivityAsync functionality for WebexAdapter #527

Open
wants to merge 2 commits 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
61 changes: 59 additions & 2 deletions libraries/Bot.Builder.Community.Adapters.Webex/WebexAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,67 @@ public override async Task<ResourceResponse[]> SendActivitiesAsync(ITurnContext
/// <param name="activity">An activity to be sent back to the messaging API.</param>
/// <param name="cancellationToken">A cancellation token for the task.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
public override async Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity,
CancellationToken cancellationToken)
{
return Task.FromException<ResourceResponse>(new NotSupportedException("Webex adapter does not support updateActivity."));
if (activity.Id is null)
{
throw new InvalidOperationException($"Activity Id is required for UpdateActivityAsync.");
}

if (activity.Type != ActivityTypes.Message)
{
throw new InvalidOperationException($"Unsupported Activity Type: '{activity.Type}'. Only Activities of type 'Message' are supported.");
}

// transform activity into the webex message format
string recipientId;

// map text format
if (activity.TextFormat == TextFormatTypes.Xml)
{
_logger.LogTrace(
$"Unsupported TextFormat: '{activity.TextFormat}'. Only TextFormat of types 'Plain' or 'Markdown' are supported.");
activity.TextFormat = TextFormatTypes.Plain;
}

var messageType = activity.TextFormat == TextFormatTypes.Plain
? MessageTextType.Text
: MessageTextType.Markdown;

if (activity.Conversation?.Id != null)
{
recipientId = activity.Conversation.Id;
}
else
{
throw new InvalidOperationException("No RoomId to send the message");
}

string responseId;

if (activity.Attachments != null && activity.Attachments.Count > 0)
{
if (activity.Attachments[0].ContentType == "application/vnd.microsoft.card.adaptive")
{
responseId = await _webexClient.CreateUpdateMessageAsync(activity.Id, recipientId, activity.Text,
activity.Attachments, messageType, cancellationToken).ConfigureAwait(false);
}
else
{
throw new NotSupportedException("Webex adapter Update does not support update with attachments other than adaptive cards.");
}
}
else
{
responseId = await _webexClient
.CreateUpdateMessageAsync(activity.Id, recipientId, activity.Text, null, messageType: messageType, cancellationToken)
.ConfigureAwait(false);
}

return new ResourceResponse(responseId);
}


/// <summary>
/// Standard BotBuilder adapter method to delete a previous message.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,68 @@ public virtual async Task<string> CreateMessageWithAttachmentsAsync(string recip

return result.Id;
}

public virtual async Task<string> CreateUpdateMessageAsync(string messageId, string roomId, string textOrMarkdown, IList<Attachment> attachments, MessageTextType messageType = MessageTextType.Markdown, CancellationToken cancellationToken = default)
{
Message result;

var attachmentsContent = new List<object>();

if (attachments != null)
{
foreach (var attach in attachments)
{
attachmentsContent.Add(attach.Content);
}
}

var text = textOrMarkdown ?? string.Empty;
string markdown = null;

if (!string.IsNullOrEmpty(textOrMarkdown) && messageType == MessageTextType.Markdown)
{
markdown = textOrMarkdown;
text = Shared.MarkdownToPlaintextRenderer.Render(textOrMarkdown);
}

var request = new WebexMessageRequest
{
RoomId = roomId,
Text = text,
Markdown = markdown,
Attachments = attachmentsContent.Count > 0 ? attachmentsContent : null,
};

var http = (HttpWebRequest)WebRequest.Create(new Uri(MessageUrl + "/" + messageId));
http.PreAuthenticate = true;
http.Headers.Add("Authorization", "Bearer " + Options.WebexAccessToken);
http.Accept = "application/json";
http.ContentType = "application/json" +
"; charset=utf-8";
http.Method = "PUT";

var parsedContent = JsonConvert.SerializeObject(request);
var encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(parsedContent);

var newStream = await http.GetRequestStreamAsync().ConfigureAwait(false);

await newStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);

newStream.Close();

var response = await http.GetResponseAsync().ConfigureAwait(false);

var stream = response.GetResponseStream();

using (var sr = new StreamReader(stream))
{
var content = await sr.ReadToEndAsync().ConfigureAwait(false);
result = JsonConvert.DeserializeObject<Message>(content);
}

return result.Id;
}

/// <summary>
/// Shows details for an attachment action, by ID.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,21 +229,6 @@ await Assert.ThrowsAsync<AuthenticationException>(async () =>
});
}

[Fact]
public async void UpdateActivityAsyncShouldThrowNotSupportedException()
{
var webexAdapter = new WebexAdapter(new Mock<WebexClientWrapper>(_testOptions).Object, _adapterOptions);

var activity = new Activity();

var turnContext = new TurnContext(webexAdapter, activity);

await Assert.ThrowsAsync<NotSupportedException>(async () =>
{
await webexAdapter.UpdateActivityAsync(turnContext, activity, default);
});
}

[Fact]
public async void SendActivitiesAsyncNotNullToPersonEmailShouldSucceed()
{
Expand Down