데이터 통합사용 가능한 커넥터Microsoft OneDrive

본 번역은 검증되지 않았습니다. AIP를 통해 영문원문으로부터 번역되었습니다.

Microsoft OneDrive

Microsoft OneDrive 커넥터는 Microsoft OneDrive용 Palantir 제공 드라이버입니다.

새 Microsoft OneDrive 소스를 생성하려면 Palantir 제공 드라이버의 표준 설정 절차를 따른 다음, 아래 섹션에서 Microsoft OneDrive별 구성 및 네트워킹을 확인하세요. 전체 속성에 대한 출처는 공식 Microsoft OneDrive 드라이버 관련 문서 ↗를 참조하세요.

베타

Microsoft OneDrive 커넥터는 베타 개발 단계에 있으며, 등록 환경에서 사용하지 못할 수 있습니다. 개발이 진행되는 동안 기능이 변경될 수 있습니다.

지원 기능

기능상태
탐색🟡 베타
배치 동기화🟡 베타
점진적🟡 베타
OAuth 2.0 인증🟡 베타

소개

Microsoft OneDrive 커넥터는 Microsoft Graph를 통해 파일, 폴더, 드라이브, 권한 및 공유 메타데이터를 읽습니다. 예약된 읽기 작업에는 배치 동기화를 사용하여 선택한 표를 데이터셋에 기록하세요.

파일을 다운로드하려면 배치 동기화에서 DownloadFile 저장 프로시저를 호출하세요. 또는 코드에서 OneDrive 소스를 사용하여 파일을 다운로드하거나 업로드하거나 교체할 수 있습니다.

인증

위임 인증을 통해 사용자로서 Microsoft OneDrive에 액세스하려면 AuthScheme=AzureAD를 설정하세요.

위임 사용자 인증(AzureAD)

AuthScheme=AzureAD를 사용하면 소스는 연결을 승인한 사용자로서 Microsoft OneDrive에 액세스합니다.

  1. Microsoft Entra 관리 센터 ↗에서 애플리케이션을 등록하세요. 클라이언트 ID를 기록하고, 클라이언트 암호를 생성하고, 테넌트 ID 또는 도메인을 기록하세요.
  2. 애플리케이션에 필요한 액세스에 해당하는 위임된 Microsoft Graph 파일 권한(예: Files.Read.All)을 부여하세요. 사용자가 파일을 써야 하는 경우 Files.ReadWrite.All을 추가하세요. 테넌트의 동의 정책에 따라 관리자가 동의해야 할 수 있습니다.
  3. 소스를 생성하고 AuthScheme=AzureAD, AzureTenant, OAuthClientId, OAuthClientSecret, InitiateOAuth=REFRESH를 설정하세요.
  4. 소스에서 생성된 CallbackURL을 애플리케이션의 웹 리디렉션 URI로 복사하세요. 소스를 저장하고 승인을 선택한 다음, 소스에서 액세스해야 하는 OneDrive의 사용자로 로그인하세요.

데이터 읽기

소스 탐색기에서 사용할 수 있는 표에는 파일 내용이 아닌 OneDrive 파일, 폴더, 드라이브, 권한 및 공유에 대한 메타데이터가 포함되어 있습니다. 표를 선택하고 배치 동기화를 설정하여 이 메타데이터를 데이터셋으로 읽어 들이세요.

파일 다운로드

파일을 다운로드하려면 배치 동기화에서 DownloadFile 저장 프로시저 ↗를 사용하거나 코드에서 OneDrive 소스를 사용하세요.

배치 동기화의 경우 동기화 정의에 다음 쿼리를 추가하세요.

Copied!
1 EXECUTE DownloadFile ResourceId = '1234'

결과물 데이터셋은 파일 내용을 Base64로 인코딩된 스트링으로 저장합니다. 다운스트림 변환에서 스트링을 바이너리로 디코딩하세요.

저장 프로시저를 사용하여 파일을 추출하는 Microsoft OneDrive 동기화.

스크린샷에는 Encoding='NONE'이 설정되어 있습니다. Base64로 인코딩된 파일 내용을 받으려면 위 쿼리와 같이 Encoding을 설정하지 않은 상태로 두세요.

구성

아래 속성은 필수이거나 권장됩니다.

속성필수 여부설명기본값
AuthScheme ↗권장Microsoft OneDrive에 연결할 때 사용할 인증 유형을 지정합니다. 이 속성을 비워 두면 기본 인증이 사용됩니다.AzureServicePrincipal
AzureTenant ↗권장데이터 액세스에 사용되는 Microsoft OneDrive 테넌트를 이름(예: contoso.onmicrosoft.com) 또는 ID로 식별합니다. (조건부).—
InitiateOAuth ↗권장인증 및 권한 부여를 받은 사용자가 작업하는 동안 사용자 액세스를 유지하는 OAuth 액세스 토큰을 가져오거나 갱신하는 프로세스를 지정합니다.GETANDREFRESH
OAuthClientId ↗권장사용자 지정 OAuth 애플리케이션을 생성할 때 할당된 클라이언트 ID를 지정합니다. (컨슈머 키라고도 합니다.) 이 ID는 사용자 지정 애플리케이션을 OAuth 권한 부여 서버에 등록합니다.—
OAuthClientSecret ↗권장사용자 지정 OAuth 애플리케이션을 생성할 때 할당된 클라이언트 암호를 지정합니다. (컨슈머 암호라고도 합니다). 이 암호는 사용자 지정 애플리케이션을 OAuth 권한 부여 서버에 등록합니다.—

네트워킹

아래 표에는 소스가 실행되기 위해 액세스할 수 있어야 하는 도메인이 나열되어 있습니다.

각 도메인에 해당하는 이그레스 정책을 추가하세요. 소스가 온프레미스에 호스팅되어 Foundry에서 직접 연결할 수 없는 경우, 대신 에이전트 프록시 이그레스 정책을 사용하세요. 에이전트 호스트 자체에서도 나열된 도메인에 연결할 수 있어야 합니다. 자세한 내용은 에이전트를 프록시로 사용을 참조하세요.

도메인필수 조건
graph.microsoft.comAzureEnvironment=GLOBAL인 경우(기본값)
login.microsoftonline.comAuthScheme=AzureAD(기본값), AzureServicePrincipal, AzureServicePrincipalCert 중 하나이고 AzureEnvironment=GLOBAL인 경우
microsoftgraph.chinacloudapi.cnAzureEnvironment=CHINA인 경우
login.chinacloudapi.cnAuthScheme=AzureAD(기본값), AzureServicePrincipal, AzureServicePrincipalCert 중 하나이고 AzureEnvironment=CHINA인 경우
graph.microsoft.usAzureEnvironment=USGOVT인 경우
login.microsoftonline.usAuthScheme=AzureAD(기본값), AzureServicePrincipal, AzureServicePrincipalCert 중 하나이고 AzureEnvironment=USGOVT 또는 USGOVTDOD인 경우
dod-graph.microsoft.usAzureEnvironment=USGOVTDOD인 경우

OAuth 2.0 인증

이 커넥터는 OAuth 2.0 인증을 지원합니다. Palantir 제공 드라이버의 OAuth 2.0 지침에 따라 연결을 구성하고 승인하세요.

데이터 쓰기

OneDrive에서 파일을 업로드하거나 교체하려면 소스를 외부 변환 또는 외부 Function으로 가져오세요. 그런 다음 코드에서 Microsoft OneDrive 소스 사용에 표시된 대로 Microsoft Graph를 호출하세요.

쓰기 전에 외부 변환의 내보내기 구성 또는 Functions의 외부 API 액세스 설정을 완료하세요. Functions에는 마킹 검증 없이 이 소스로 내보내기 활성화도 필요합니다. 애플리케이션에 쓰기에 필요한 Microsoft Graph 권한을 부여하세요.

코드에서 Microsoft OneDrive 소스 사용

아래 예제에는 OAuthClientSecret에 OAuth 클라이언트 시크릿을 저장하는 OneDrive 소스가 필요합니다. 이 예제에서는 해당 시크릿과 소스의 거버넌스가 적용된 이그레스를 재사용하여 OAuth 2.0 클라이언트 자격 증명 흐름을 통해 수명이 짧은 애플리케이션 토큰을 요청합니다. 이 코드 경로는 커넥터 배치 동기화에 사용되는 AuthScheme과 별개입니다.

워크플로에 필요한 Microsoft Graph 애플리케이션 권한을 애플리케이션에 부여하세요.

  • 파일 다운로드: Files.Read.All.
  • 파일 업로드 또는 교체: Files.ReadWrite.All.

관리자가 선택한 권한에 대한 동의를 부여해야 합니다.

이 코드 예제에는 글로벌 Microsoft ID 및 Graph 엔드포인트가 하드 코딩되어 있으므로 AzureEnvironment=GLOBAL로 구성된 소스에서만 사용하세요. 소버린 클라우드 환경에 필요한 엔드포인트는 매개변수화되어 있지 않습니다.

소스를 코드 리포지토리로 가져오세요. 각 자리 표시자를 프로젝트에서 사용하는 소스, 테넌트, 애플리케이션, 드라이브, 항목, 대상, 결과물 파일, 결과물 데이터셋 및 예상 다운로드 호스트 값으로 바꾸세요. 드라이브 및 항목 ID는 커넥터의 파일 뷰 또는 Microsoft Graph에서 확인할 수 있습니다.

Graph 및 로그인 호스트와 함께 Microsoft Graph 다운로드 리디렉션 ↗에서 반환되는 테넌트별 호스트를 허용하도록 소스의 이그레스 정책을 구성하세요. 각 읽기 예제에서 <expected_download_host>를 해당 허용된 호스트 이름으로 설정하세요. TypeScript v1 예제에서는 OneDriveSource를 소스의 API 이름에서 생성된 식별자로 바꾸세요.

Python 예제는 requests ↗ 패키지를 사용합니다. 선택한 Python 예제에 맞게 이 패키지를 리포지토리의 종속성에 추가하세요.

데이터 읽기

파이프라인은 다운로드한 바이트를 비정형 데이터셋에 추가합니다. Python Function은 바이트를 직접 반환합니다. TypeScript Functions는 동일한 바이트를 Base64로 반환합니다.

Function 예제를 실행하기 전에 소스에 대한 내보내기 활성화를 포함하여 외부 API 액세스 구성을 완료하세요. 이 Foundry 요구 사항은 OneDrive에서 파일을 다운로드하기만 하는 Function에도 적용됩니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 from urllib.parse import quote, urlparse import requests from transforms.api import LightweightOutput, Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems SOURCE_RID = "<source_rid>" TENANT_ID = "<tenant_id>" CLIENT_ID = "<client_id>" DRIVE_ID = "<drive_id>" ITEM_ID = "<item_id>" EXPECTED_DOWNLOAD_HOST = "<expected_download_host>" OUTPUT_FILE_NAME = "<output_file_name>" @external_systems(onedrive=Source(SOURCE_RID)) @transform.using(output=Output("<output_dataset_rid>")) def download_onedrive_file( onedrive: ResolvedSource, output: LightweightOutput, ) -> None: session = requests.Session() proxy = onedrive.get_https_proxy_uri() if proxy: session.proxies.update({"http": proxy, "https": proxy}) token_response = session.post( f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token", data={ "client_id": CLIENT_ID, "client_secret": onedrive.get_secret("OAuthClientSecret"), "scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials", }, allow_redirects=False, ) token_response.raise_for_status() access_token = token_response.json()["access_token"] item_url = ( f"https://graph.microsoft.com/v1.0/drives/{quote(DRIVE_ID, safe='')}" f"/items/{quote(ITEM_ID, safe='')}/content" ) graph_response = session.get( item_url, headers={"Authorization": f"Bearer {access_token}"}, allow_redirects=False, ) if graph_response.is_redirect: location = graph_response.headers["Location"] download_url = urlparse(location) if ( download_url.scheme != "https" or (download_url.hostname or "").lower() != EXPECTED_DOWNLOAD_HOST.lower() ): raise RuntimeError("Microsoft Graph returned an unexpected download host.") file_response = session.get(location, allow_redirects=False) else: file_response = graph_response file_response.raise_for_status() with output.filesystem().open(OUTPUT_FILE_NAME, "wb") as output_file: output_file.write(file_response.content)
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 from urllib.parse import quote, urlparse import requests from functions.api import function from functions.sources import get_source SOURCE_RID = "<source_rid>" TENANT_ID = "<tenant_id>" CLIENT_ID = "<client_id>" DRIVE_ID = "<drive_id>" EXPECTED_DOWNLOAD_HOST = "<expected_download_host>" @function(sources=[SOURCE_RID]) def download_onedrive_file(item_id: str) -> bytes: source = get_source(rid=SOURCE_RID) session = requests.Session() proxy = source.get_https_proxy_uri() if proxy: session.proxies.update({"http": proxy, "https": proxy}) token_response = session.post( f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token", data={ "client_id": CLIENT_ID, "client_secret": source.get_secret("OAuthClientSecret"), "scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials", }, allow_redirects=False, ) token_response.raise_for_status() access_token = token_response.json()["access_token"] graph_response = session.get( f"https://graph.microsoft.com/v1.0/drives/{quote(DRIVE_ID, safe='')}" f"/items/{quote(item_id, safe='')}/content", headers={"Authorization": f"Bearer {access_token}"}, allow_redirects=False, ) if graph_response.is_redirect: location = graph_response.headers["Location"] download_url = urlparse(location) if ( download_url.scheme != "https" or (download_url.hostname or "").lower() != EXPECTED_DOWNLOAD_HOST.lower() ): raise RuntimeError("Microsoft Graph returned an unexpected download host.") file_response = session.get(location, allow_redirects=False) else: file_response = graph_response file_response.raise_for_status() return file_response.content
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 import { ExternalSystems, Function, UserFacingError } from "@foundry/functions-api"; import { OneDriveSource } from "@foundry/external-systems/sources"; import { Buffer } from "buffer"; const TENANT_ID = "<tenant_id>"; const CLIENT_ID = "<client_id>"; const DRIVE_ID = "<drive_id>"; const EXPECTED_DOWNLOAD_HOST = "<expected_download_host>"; interface TokenResponse { access_token: string; } export class OneDriveReadFunctions { @ExternalSystems({ sources: [OneDriveSource] }) @Function() public async downloadOneDriveFile(itemId: string): Promise<string> { const tokenResponse = await OneDriveSource.fetch( `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: OneDriveSource.getSecret("OAuthClientSecret"), scope: "https://graph.microsoft.com/.default", grant_type: "client_credentials", }).toString(), redirect: "manual", }, ); if (!tokenResponse.ok) { throw new UserFacingError(`Token request returned HTTP ${tokenResponse.status}.`); } const token = await tokenResponse.json() as TokenResponse; const graphResponse = await OneDriveSource.fetch( `https://graph.microsoft.com/v1.0/drives/${encodeURIComponent(DRIVE_ID)}` + `/items/${encodeURIComponent(itemId)}/content`, { method: "GET", headers: { Authorization: `Bearer ${token.access_token}` }, redirect: "manual", }, ); let fileResponse = graphResponse; if ([301, 302, 303, 307, 308].includes(graphResponse.status)) { const location = graphResponse.headers.get("location"); if (!location) { throw new UserFacingError("Microsoft Graph returned no download location."); } const downloadUrl = new URL(location); if (downloadUrl.protocol !== "https:" || downloadUrl.hostname.toLowerCase() !== EXPECTED_DOWNLOAD_HOST.toLowerCase()) { throw new UserFacingError("Microsoft Graph returned an unexpected download host."); } fileResponse = await OneDriveSource.fetch(location, { method: "GET", redirect: "manual", }); } if (!fileResponse.ok) { throw new UserFacingError(`Download returned HTTP ${fileResponse.status}.`); } return Buffer.from(await fileResponse.arrayBuffer()).toString("base64"); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 import { Buffer } from "node:buffer"; import { UserFacingError } from "@osdk/functions"; import { getFetch, getSource } from "@palantir/functions-sources"; const SOURCE_RID = "<source_rid>"; const TENANT_ID = "<tenant_id>"; const CLIENT_ID = "<client_id>"; const DRIVE_ID = "<drive_id>"; const EXPECTED_DOWNLOAD_HOST = "<expected_download_host>"; interface TokenResponse { access_token: string; } export const config = { apiName: "downloadOneDriveFileTsV2", sources: [SOURCE_RID], }; export default async function downloadOneDriveFile(itemId: string): Promise<string> { const source = await getSource(SOURCE_RID); const sourceFetch = await getFetch(source); const clientSecret = source.secrets["OAuthClientSecret"]; if (!clientSecret) { throw new UserFacingError("The OneDrive source has no OAuth client secret."); } const tokenResponse = await sourceFetch( `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: clientSecret, scope: "https://graph.microsoft.com/.default", grant_type: "client_credentials", }).toString(), redirect: "manual", }, ); if (!tokenResponse.ok) { throw new UserFacingError(`Token request returned HTTP ${tokenResponse.status}.`); } const token = await tokenResponse.json() as TokenResponse; const graphResponse = await sourceFetch( `https://graph.microsoft.com/v1.0/drives/${encodeURIComponent(DRIVE_ID)}` + `/items/${encodeURIComponent(itemId)}/content`, { method: "GET", headers: { Authorization: `Bearer ${token.access_token}` }, redirect: "manual", }, ); let fileResponse = graphResponse; if ([301, 302, 303, 307, 308].includes(graphResponse.status)) { const location = graphResponse.headers.get("location"); if (!location) { throw new UserFacingError("Microsoft Graph returned no download location."); } const downloadUrl = new URL(location); if (downloadUrl.protocol !== "https:" || downloadUrl.hostname.toLowerCase() !== EXPECTED_DOWNLOAD_HOST.toLowerCase()) { throw new UserFacingError("Microsoft Graph returned an unexpected download host."); } fileResponse = await sourceFetch(location, { method: "GET", redirect: "manual" }); } if (!fileResponse.ok) { throw new UserFacingError(`Download returned HTTP ${fileResponse.status}.`); } return Buffer.from(await fileResponse.arrayBuffer()).toString("base64"); }

데이터 쓰기

각 예제는 PUT을 사용하여 Microsoft Graph 단순 업로드를 수행하고 업로드한 항목의 ID를 반환합니다.

이 예제는 대상 경로에 기존 파일이 있는 경우 해당 파일의 내용을 덮어씁니다. 대상을 신중하게 선택하고, 새 파일을 만들려면 사용되지 않은 경로를 사용하세요. 결과가 불명확하여 재시도하려는 경우 먼저 업로드가 성공했는지 확인하세요.

애플리케이션 인증으로는 민감도 레이블이 지정된 파일을 교체할 수 없습니다. 이 경우 위임된 사용자 워크플로를 사용하세요.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import json from urllib.parse import quote import requests from transforms.api import LightweightOutput, Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems SOURCE_RID = "<source_rid>" TENANT_ID = "<tenant_id>" CLIENT_ID = "<client_id>" DRIVE_ID = "<drive_id>" DESTINATION_PATH = "<new_destination_path>" UPLOAD_CONTENT = b"OneDrive upload from a Foundry Python transform.\n" @external_systems(onedrive=Source(SOURCE_RID)) @transform.using(output=Output("<output_dataset_rid>")) def upload_onedrive_file( onedrive: ResolvedSource, output: LightweightOutput, ) -> None: session = requests.Session() proxy = onedrive.get_https_proxy_uri() if proxy: session.proxies.update({"http": proxy, "https": proxy}) token_response = session.post( f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token", data={ "client_id": CLIENT_ID, "client_secret": onedrive.get_secret("OAuthClientSecret"), "scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials", }, allow_redirects=False, ) token_response.raise_for_status() access_token = token_response.json()["access_token"] encoded_path = "/".join(quote(segment, safe="") for segment in DESTINATION_PATH.split("/")) response = session.put( f"https://graph.microsoft.com/v1.0/drives/{quote(DRIVE_ID, safe='')}" f"/root:/{encoded_path}:/content", headers={ "Authorization": f"Bearer {access_token}", "Content-Type": "text/plain; charset=utf-8", }, data=UPLOAD_CONTENT, allow_redirects=False, ) response.raise_for_status() result = response.json() with output.filesystem().open("upload-result.json", "wb") as output_file: output_file.write( json.dumps({"itemId": result["id"], "fileName": result["name"]}).encode() )
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 from urllib.parse import quote import requests from functions.api import function from functions.sources import get_source SOURCE_RID = "<source_rid>" TENANT_ID = "<tenant_id>" CLIENT_ID = "<client_id>" DRIVE_ID = "<drive_id>" UPLOAD_CONTENT = b"OneDrive upload from a Foundry Python Function.\n" @function(sources=[SOURCE_RID]) def upload_onedrive_file(destination_path: str) -> str: source = get_source(rid=SOURCE_RID) session = requests.Session() proxy = source.get_https_proxy_uri() if proxy: session.proxies.update({"http": proxy, "https": proxy}) token_response = session.post( f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token", data={ "client_id": CLIENT_ID, "client_secret": source.get_secret("OAuthClientSecret"), "scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials", }, allow_redirects=False, ) token_response.raise_for_status() access_token = token_response.json()["access_token"] encoded_path = "/".join(quote(segment, safe="") for segment in destination_path.split("/")) response = session.put( f"https://graph.microsoft.com/v1.0/drives/{quote(DRIVE_ID, safe='')}" f"/root:/{encoded_path}:/content", headers={ "Authorization": f"Bearer {access_token}", "Content-Type": "text/plain; charset=utf-8", }, data=UPLOAD_CONTENT, allow_redirects=False, ) response.raise_for_status() return response.json()["id"]
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 import { ExternalSystems, Function, UserFacingError } from "@foundry/functions-api"; import { OneDriveSource } from "@foundry/external-systems/sources"; import { Buffer } from "buffer"; const TENANT_ID = "<tenant_id>"; const CLIENT_ID = "<client_id>"; const DRIVE_ID = "<drive_id>"; const UPLOAD_CONTENT = Buffer.from( "OneDrive upload from a Foundry TypeScript v1 Function.\n", "utf8", ); interface TokenResponse { access_token: string; } interface UploadResult { id: string; } export class OneDriveWriteFunctions { @ExternalSystems({ sources: [OneDriveSource] }) @Function() public async uploadOneDriveFile(destinationPath: string): Promise<string> { const tokenResponse = await OneDriveSource.fetch( `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: OneDriveSource.getSecret("OAuthClientSecret"), scope: "https://graph.microsoft.com/.default", grant_type: "client_credentials", }).toString(), redirect: "manual", }, ); if (!tokenResponse.ok) { throw new UserFacingError(`Token request returned HTTP ${tokenResponse.status}.`); } const token = await tokenResponse.json() as TokenResponse; const encodedPath = destinationPath.split("/").map(encodeURIComponent).join("/"); const response = await OneDriveSource.fetch( `https://graph.microsoft.com/v1.0/drives/${encodeURIComponent(DRIVE_ID)}` + `/root:/${encodedPath}:/content`, { method: "PUT", headers: { Authorization: `Bearer ${token.access_token}`, "Content-Type": "text/plain; charset=utf-8", }, body: UPLOAD_CONTENT, redirect: "manual", }, ); if (!response.ok) { throw new UserFacingError(`Upload returned HTTP ${response.status}.`); } return (await response.json() as UploadResult).id; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 import { Buffer } from "node:buffer"; import { UserFacingError } from "@osdk/functions"; import { getFetch, getSource } from "@palantir/functions-sources"; const SOURCE_RID = "<source_rid>"; const TENANT_ID = "<tenant_id>"; const CLIENT_ID = "<client_id>"; const DRIVE_ID = "<drive_id>"; const UPLOAD_CONTENT = Buffer.from( "OneDrive upload from a Foundry TypeScript v2 Function.\n", "utf8", ); interface TokenResponse { access_token: string; } interface UploadResult { id: string; } export const config = { apiName: "uploadOneDriveFileTsV2", sources: [SOURCE_RID], }; export default async function uploadOneDriveFile(destinationPath: string): Promise<string> { const source = await getSource(SOURCE_RID); const sourceFetch = await getFetch(source); const clientSecret = source.secrets["OAuthClientSecret"]; if (!clientSecret) { throw new UserFacingError("The OneDrive source has no OAuth client secret."); } const tokenResponse = await sourceFetch( `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: clientSecret, scope: "https://graph.microsoft.com/.default", grant_type: "client_credentials", }).toString(), redirect: "manual", }, ); if (!tokenResponse.ok) { throw new UserFacingError(`Token request returned HTTP ${tokenResponse.status}.`); } const token = await tokenResponse.json() as TokenResponse; const encodedPath = destinationPath.split("/").map(encodeURIComponent).join("/"); const response = await sourceFetch( `https://graph.microsoft.com/v1.0/drives/${encodeURIComponent(DRIVE_ID)}` + `/root:/${encodedPath}:/content`, { method: "PUT", headers: { Authorization: `Bearer ${token.access_token}`, "Content-Type": "text/plain; charset=utf-8", }, body: UPLOAD_CONTENT, redirect: "manual", }, ); if (!response.ok) { throw new UserFacingError(`Upload returned HTTP ${response.status}.`); } return (await response.json() as UploadResult).id; }