-
Notifications
You must be signed in to change notification settings - Fork 28
[#712] Add TeamsAttachmentDownloader to Core #776
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
Open
ceciliaavila
wants to merge
9
commits into
main
Choose a base branch
from
southworks/update/teams-attachment-downloader
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
fd3c059
Move teamsAttachmentDownloader to agents-hosting
ceciliaavila 40a4503
Improve downloadFile function
ceciliaavila 1b4a240
Merge branch 'main' into southworks/update/teams-attachment-downloader
ceciliaavila 6a033fb
Remove http://localhost from condition
ceciliaavila 205cd0a
Merge branch 'main' into southworks/update/teams-attachment-downloader
ceciliaavila 9800c43
Merge branch 'main' into southworks/update/teams-attachment-downloader
ceciliaavila 76653d5
Remove contentType override
ceciliaavila cef14a4
Merge branch 'main' into southworks/update/teams-attachment-downloader
ceciliaavila cd81629
Merge branch 'main' into southworks/update/teams-attachment-downloader
benbrown File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
packages/agents-hosting/src/app/teamsAttachmentDownloader.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| /** | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. | ||
| */ | ||
|
|
||
| import { Attachment, Channels } from '@microsoft/agents-activity' | ||
| import { debug } from '@microsoft/agents-activity/logger' | ||
| import { ConnectorClient } from '../connector-client' | ||
| import { InputFile, InputFileDownloader } from './inputFileDownloader' | ||
| import { TurnContext } from '../turnContext' | ||
| import { TurnState } from './turnState' | ||
| import axios, { AxiosInstance } from 'axios' | ||
| import { z } from 'zod' | ||
|
|
||
| const logger = debug('agents:teamsAttachmentDownloader') | ||
|
|
||
| /** | ||
| * Downloads attachments from Teams using the bots access token. | ||
| */ | ||
| export class TeamsAttachmentDownloader<TState extends TurnState = TurnState> implements InputFileDownloader<TState> { | ||
| private _httpClient: AxiosInstance | ||
| private _stateKey: string | ||
|
|
||
| public constructor (stateKey: string = 'inputFiles') { | ||
| this._httpClient = axios.create() | ||
| this._stateKey = stateKey | ||
| } | ||
|
|
||
| /** | ||
| * Download any files relative to the current user's input. | ||
| * | ||
| * @param {TurnContext} context Context for the current turn of conversation. | ||
| * @returns {Promise<InputFile[]>} Promise that resolves to an array of downloaded input files. | ||
| */ | ||
| public async downloadFiles (context: TurnContext): Promise<InputFile[]> { | ||
| if (context.activity.channelId !== Channels.Msteams && context.activity.channelId !== Channels.M365Copilot) { | ||
| return Promise.resolve([]) | ||
| } | ||
| // Filter out HTML attachments | ||
| const attachments = context.activity.attachments?.filter((a) => a.contentType && !a.contentType.startsWith('text/html')) | ||
| if (!attachments || attachments.length === 0) { | ||
| return Promise.resolve([]) | ||
| } | ||
|
|
||
| const connectorClient : ConnectorClient = context.turnState.get<ConnectorClient>(context.adapter.ConnectorClientKey) | ||
| this._httpClient.defaults.headers = connectorClient.axiosInstance.defaults.headers | ||
|
|
||
| const files: InputFile[] = [] | ||
| for (const attachment of attachments) { | ||
| const file = await this.downloadFile(attachment) | ||
| if (file) { | ||
| files.push(file) | ||
| } | ||
| } | ||
|
|
||
| return files | ||
| } | ||
|
|
||
| /** | ||
| * @private | ||
| * @param {Attachment} attachment - Attachment to download. | ||
| * @returns {Promise<InputFile>} - Promise that resolves to the downloaded input file. | ||
| */ | ||
| private async downloadFile (attachment: Attachment): Promise<InputFile | undefined> { | ||
| let inputFile: InputFile | undefined | ||
|
|
||
| if (attachment.contentUrl && (attachment.contentUrl.startsWith('https://') || attachment.contentUrl.startsWith('http://localhost'))) { | ||
ceciliaavila marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| try { | ||
| const contentSchema = z.object({ downloadUrl: z.string().url() }) | ||
| const parsed = contentSchema.safeParse(attachment.content) | ||
| const downloadUrl = parsed.success ? parsed.data.downloadUrl : attachment.contentUrl | ||
| const response = await this._httpClient.get(downloadUrl, { responseType: 'arraybuffer' }) | ||
|
|
||
| const content = Buffer.from(response.data, 'binary') | ||
| let contentType = response.headers['content-type'] || 'application/octet-stream' | ||
| if (contentType.startsWith('image/')) { | ||
benbrown marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| contentType = 'image/png' | ||
| } | ||
| inputFile = { content, contentType, contentUrl: attachment.contentUrl } | ||
| } catch (error) { | ||
| logger.error(`Failed to download Teams attachment: ${error}`) | ||
| return undefined | ||
| } | ||
| } else { | ||
| if (!attachment.content) { | ||
| logger.error('Attachment missing content') | ||
| return undefined | ||
| } | ||
| if (!(attachment.content instanceof ArrayBuffer) && !Buffer.isBuffer(attachment.content)) { | ||
| logger.error('Attachment content is not ArrayBuffer or Buffer') | ||
| return undefined | ||
| } | ||
| inputFile = { | ||
| content: Buffer.from(attachment.content as ArrayBuffer), | ||
| contentType: attachment.contentType, | ||
| contentUrl: attachment.contentUrl | ||
| } | ||
| } | ||
| return inputFile | ||
| } | ||
|
|
||
| /** | ||
| * Downloads files from the attachments in the current turn context and stores them in state. | ||
| * | ||
| * @param context The turn context containing the activity with attachments. | ||
| * @param state The turn state to store the files in. | ||
| * @returns A promise that resolves when the downloaded files are stored. | ||
| */ | ||
| public async downloadAndStoreFiles (context: TurnContext, state: TState): Promise<void> { | ||
| const files = await this.downloadFiles(context) | ||
| state.setValue(this._stateKey, files) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.