Drive UI의 '다음으로 열기' 컨텍스트 메뉴와 통합

사용자가 파일을 선택하고 Drive UI의 '연결 프로그램' 메뉴 항목을 클릭하면 Drive에서 사용자를 Drive UI 통합 구성에 정의된 앱의 열기 URL로 리디렉션합니다.

Drive UI 통합을 구성할 때 '가져오기' 체크박스를 선택한 경우 사용자는 앱별 파일과 Google Workspace 파일 조합을 선택하여 열 수 있습니다. Drive UI 통합을 구성할 때 앱별 파일은 '기본 MIME 유형' 및 '기본 파일 확장자' 필드에 정의되는 반면 Google Workspace 파일은 '보조 MIME 유형' 및 '보조 파일 확장자' 필드에 정의됩니다.

Drive에서는 사용자가 열고자 하는 각 파일에 대해 정의된 기본 MIME 유형과 보조 MIME 유형을 기준으로 MIME 유형을 확인합니다.

  • '기본 MIME 유형' 필드에 정의된 MIME 유형의 경우 파일 ID가 앱에 전달됩니다. 앱별 파일을 처리하는 방법에 관한 자세한 내용은 앱별 문서의 Open URL 처리를 참고하세요.

  • '보조 MIME 유형' 필드에 정의된 MIME 유형의 경우 Drive UI에 Google Workspace 파일을 어떤 파일 형식으로 변환할지 묻는 대화상자가 표시됩니다. 예를 들어 Drive UI에서 Google Docs 파일을 선택했는데 '보조 MIME 유형' 필드가 앱이 text/plain 또는 application/pdf를 지원한다고 제안하면 Drive UI에서 사용자에게 일반 텍스트 또는 PDF로 변환할지 묻습니다.

    Google Workspace 파일을 처리하는 방법에 관한 자세한 내용은 Google Workspace 문서의 열린 URL 처리를 참고하세요. Google Workspace 문서 및 MIME 유형 변환 형식의 목록은 Google Workspace 문서의 MIME 유형 내보내기를 참고하세요.

앱별 문서의 열기 URL 처리

Drive UI 통합 구성에서 설명했듯이 앱은 파일을 열기 위한 정보가 포함된 템플릿 변수를 수신합니다. 앱은 state 매개변수 내에서 기본 템플릿 변수 집합을 수신합니다. 앱별 열기 URL의 기본 state 정보는 다음과 같습니다.

{
  "ids": ["ID"],
  "resourceKeys":{"RESOURCE_KEYS":"RESOURCE_KEYS"},
  "action":"open",
  "userId":"USER_ID"
}

이 출력에는 다음 값이 포함됩니다.

  • ID: 상위 폴더의 ID입니다.
  • RESOURCE_KEYS: 각 리소스 키에 매핑된 파일 ID의 JSON 사전입니다.
  • open: 실행 중인 작업입니다. 공개 URL을 사용할 경우 값은 open입니다.
  • USER_ID: 사용자를 고유하게 식별하는 프로필 ID입니다.

앱은 다음 단계에 따라 이 요청에 대해 조치를 취해야 합니다.

  1. action 필드의 값이 open이고 ids 필드가 있는지 확인합니다.
  2. userId 값을 사용하여 사용자의 새 세션을 만듭니다. 로그인한 사용자에 관한 자세한 내용은 사용자 및 새 이벤트를 참고하세요.
  3. files.get 메서드를 사용하여 권한을 확인하고, 파일 메타데이터를 가져오고, ID 값을 사용하여 파일 콘텐츠를 다운로드합니다.
  4. 요청에 resourceKeys가 설정된 경우 X-Goog-Drive-Resource-Keys 요청 헤더를 설정합니다. 리소스 키에 관한 자세한 내용은 리소스 키를 사용하여 링크 공유 파일에 액세스를 참고하세요.

state 매개변수는 URL로 인코딩되므로 앱에서 이스케이프 문자를 처리하고 JSON으로 파싱해야 합니다.

Google Workspace 문서의 열린 URL 처리

Drive UI 통합 구성에서 설명했듯이 앱은 state 매개변수 내에서 기본 템플릿 변수 집합을 수신합니다. Google Workspace Open URL의 기본 state 정보는 다음과 같습니다.

{
  "exportIds": ["ID"],
  "resourceKeys":{"RESOURCE_KEYS":"RESOURCE_KEYS"},
  "action":"open",
  "userId":"USER_ID"
}

이 출력에는 다음 값이 포함됩니다.

  • EXPORT_ID: 내보내는 파일 ID의 쉼표로 구분된 목록 (기본 제공 Google 문서를 열 때만 사용됨)
  • RESOURCE_KEYS: 각 리소스 키에 매핑된 파일 ID의 JSON 사전입니다.
  • open: 실행 중인 작업입니다. 공개 URL을 사용할 경우 값은 open입니다.
  • USER_ID: 사용자를 식별하는 프로필 ID입니다.

앱은 다음 단계에 따라 이 요청에 대해 조치를 취해야 합니다.

  1. state 필드의 open 값과 exportIds 필드의 존재를 모두 감지하여 이 요청이 파일을 열기 위한 요청인지 확인합니다.

  2. files.get 메서드를 사용하여 권한을 확인하고, 파일 메타데이터를 가져오고, EXPORT_ID 값을 사용하여 MIME 유형을 확인합니다.

  3. files.export 메서드를 사용하여 파일 콘텐츠를 변환합니다. 다음 코드 샘플은 Google Workspace 문서를 요청된 MIME 유형으로 내보내는 방법을 보여줍니다.

  4. 요청에 resourceKey가 설정된 경우 X-Goog-Drive-Resource-Keys 요청 헤더를 설정합니다. 리소스 키에 관한 자세한 내용은 리소스 키를 사용하여 링크 공유 파일에 액세스를 참고하세요.

    Java

    drive/snippets/drive_v3/src/main/java/ExportPdf.java
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.drive.Drive;
    import com.google.api.services.drive.DriveScopes;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Arrays;
    
    /* Class to demonstrate use-case of drive's export pdf. */
    public class ExportPdf {
    
      /**
       * Download a Document file in PDF format.
       *
       * @param realFileId file ID of any workspace document format file.
       * @return byte array stream if successful, {@code null} otherwise.
       * @throws IOException if service account credentials file not found.
       */
      public static ByteArrayOutputStream exportPdf(String realFileId) throws IOException {
        // Load pre-authorized user credentials from the environment.
        // TODO(developer) - See https://developers.google.com/identity for
        // guides on implementing OAuth2 for your application.
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
            .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
            credentials);
    
        // Build a new authorized API client service.
        Drive service = new Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();
    
        OutputStream outputStream = new ByteArrayOutputStream();
        try {
          service.files().export(realFileId, "application/pdf")
              .executeMediaAndDownloadTo(outputStream);
    
          return (ByteArrayOutputStream) outputStream;
        } catch (GoogleJsonResponseException e) {
          // TODO(developer) - handle error appropriately
          System.err.println("Unable to export file: " + e.getDetails());
          throw e;
        }
      }
    }

    Python

    drive/snippets/drive-v3/file_snippet/export_pdf.py
    import io
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaIoBaseDownload
    
    
    def export_pdf(real_file_id):
      """Download a Document file in PDF format.
      Args:
          real_file_id : file ID of any workspace document format file
      Returns : IO object with location
    
      Load pre-authorized user credentials from the environment.
      TODO(developer) - See https://developers.google.com/identity
      for guides on implementing OAuth2 for the application.
      """
      creds, _ = google.auth.default()
    
      try:
        # create drive api client
        service = build("drive", "v3", credentials=creds)
    
        file_id = real_file_id
    
        # pylint: disable=maybe-no-member
        request = service.files().export_media(
            fileId=file_id, mimeType="application/pdf"
        )
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
          status, done = downloader.next_chunk()
          print(f"Download {int(status.progress() * 100)}.")
    
      except HttpError as error:
        print(f"An error occurred: {error}")
        file = None
    
      return file.getvalue()
    
    
    if __name__ == "__main__":
      export_pdf(real_file_id="1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY")

    Node.js

    drive/snippets/drive_v3/file_snippets/export_pdf.js
    /**
     * Download a Document file in PDF format
     * @param{string} fileId file ID
     * @return{obj} file status
     * */
    async function exportPdf(fileId) {
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
    
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
    
      try {
        const result = await service.files.export({
          fileId: fileId,
          mimeType: 'application/pdf',
        });
        console.log(result.status);
        return result;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }

    2,399필리핀

    drive/snippets/drive_v3/src/DriveExportPdf.php
    use Google\Client;
    use Google\Service\Drive;
    function exportPdf()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
            $fileId = $realFileId;
            $response = $driveService->files->export($fileId, 'application/pdf', array(
                'alt' => 'media'));
            $content = $response->getBody()->getContents();
            return $content;
    
        }  catch(Exception $e) {
             echo "Error Message: ".$e;
        }
    
    }

변환된 파일을 읽기 전용으로 표시하거나 사용자가 파일을 새 파일 형식으로 저장할 수 있는 대화상자를 표시합니다.

state 매개변수는 URL로 인코딩되므로 앱에서 이스케이프 문자를 처리하고 JSON으로 파싱해야 합니다.

사용자 및 새 이벤트

Drive 앱은 모든 '열림' 이벤트를 잠재적인 로그인으로 취급해야 합니다. 일부 사용자에게 계정이 여러 개 있을 수 있으므로 state 매개변수의 사용자 ID가 현재 세션과 일치하지 않을 수 있습니다. state 매개변수의 사용자 ID가 현재 세션과 일치하지 않으면 앱의 현재 세션을 종료하고 요청된 사용자로 로그인합니다.

애플리케이션은 Google Drive UI에서 애플리케이션을 여는 것 외에도 앱 내에서 콘텐츠를 선택하는 파일 선택기를 표시할 수 있습니다. 자세한 내용은 Google 선택도구를 참고하세요.