// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Teams.Api;
using Microsoft.Teams.Api.Activities;
using Microsoft.Teams.Api.Clients;
using Microsoft.Teams.Cards;
using Microsoft.Teams.Common.Logging;
namespace Microsoft.Teams.Apps;
///
/// context that comes from client (tab/embed) requests
/// for remote function calls
///
public interface IFunctionContext : IClientContext
{
///
/// the api client
///
public ApiClient Api { get; }
///
/// the app logger instance
///
public ILogger Log { get; }
///
/// the function payload
///
public T Data { get; }
///
/// send an activity to the conversation
///
/// activity activity to send
/// optional cancellation token
public Task Send(TActivity activity, CancellationToken cancellationToken = default) where TActivity : IActivity;
///
/// send a message activity to the conversation
///
/// the text to send
/// optional cancellation token
public Task Send(string text, CancellationToken cancellationToken = default);
///
/// send a message activity with a card attachment
///
/// the card to send as an attachment
/// optional cancellation token
public Task Send(AdaptiveCard card, CancellationToken cancellationToken = default);
}
///
/// context that comes from client (tab/embed) requests
/// for remote function calls
///
public class FunctionContext(App app) : ClientContext, IFunctionContext
{
public required ApiClient Api { get; set; }
public required ILogger Log { get; set; }
public required T Data { get; set; }
public async Task Send(TActivity activity, CancellationToken cancellationToken = default) where TActivity : IActivity
{
var conversationId = ConversationId ?? activity.Conversation?.Id;
// Conversation ID can be missing if the app is running in a personal scope. In this case, create
// a conversation between the bot and the user. This will either create a new conversation or return
// a pre-existing one.
if (conversationId is null)
{
var res = await Api.Conversations.CreateAsync(new()
{
TenantId = TenantId,
Members = [
new()
{
Id = UserId,
Name = UserName,
}
]
}).ConfigureAwait(false);
conversationId = res.Id;
}
return await app.Send(conversationId, activity, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public Task Send(string text, CancellationToken cancellationToken = default)
{
return Send(new MessageActivity(text), cancellationToken);
}
public Task Send(AdaptiveCard card, CancellationToken cancellationToken = default)
{
return Send(new MessageActivity().AddAttachment(card), cancellationToken);
}
}