File value-added services

Updated at:

To use methods for document preview, audio and video transcoding and playback, and archive download, you must enable the corresponding features.

getOfficePreviewUrl method

Important

Supported in standard mode

Warning

Not supported in hosted mode

To preview documents, you must activate the corresponding service.

const result = await client.getOfficePreviewUrl(params, options)

Parameters

Field

Type

Required

Description

params

IOfficePreviewReq

Yes

The file to preview.

options

AxiosRequestConfig

No

Other configuration items.

IOfficePreviewReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

share_id

string

No

The share ID.

file_path

string

No

The file path.

file_id

string

No

The file ID.

parent_file_id

string

No

The parent file ID.

parent_file_path

string

No

The parent file path.

allow_copy

boolean

Yes

Specifies whether copying is allowed.

referer

string

No

The address. Set to location.origin or undefined.

Return value

Field

Type

Required

Description

result

object

Yes

The result.

result

Field

Type

Required

Description

access_token

string

Yes

The token information.

preview_url

string

Yes

The preview URL.

Appendix: Example of the document preview method

PDS document preview integrates with the document preview feature of Alibaba Cloud IMM. For more information, see Quick Start.

The steps are as follows:

(1) Modify the HTML

First, import sdk.js in the HTML file. 
<script src="https://g.alicdn.com/IMM/office-js/1.1.15/aliyun-web-office-sdk.min.js"></script>

<!-- The element where the iframe is mounted -->
<div id="preview-div"></div>

(2) Main logic

Call the getOfficePreviewUrl operation to obtain the access_token and preview_url.

// Obtain the collaboration URL and AccessToken.
var tokenInfo = await client.getOfficePreviewUrl({
  drive_id: '1',
  file_id: 'xxxxxx'
})
 
let instance = aliyun.config({
  mount: document.querySelector('#preview-div'),  // The preview iframe is rendered in this element.
  url: tokenInfo.preview_url, // Set the document collaboration URL.
  refreshToken,               // Configure the method to refresh the token.
})
// Set the AccessToken.
instance.setToken({
  token: tokenInfo.access_token,
  timeout: 10*60*1000     
})


// Method to refresh the token.
// Call the getOfficePreviewUrl operation again to obtain a new access_token and preview_url.
async function refreshToken(){
   var tokenInfo = await client.getOfficePreviewUrl({
      drive_id: '1',
      file_id: 'xxxxxx'
   })
   return {
      token: tokenInfo.access_token,
      timeout: 10*60*1000   
   }
}

(3) iframe style

You can make adjustments based on your requirements.

#preview-div iframe{
  width: 100%;
  height: 100%;
}

getOfficeEditUrl method

Important

Supported in standard mode

Warning

Not supported in hosted mode

To edit documents, you must activate the corresponding service.

const result = await client.getOfficeEditUrl(params, options)

Parameters

Field

Type

Required

Description

params

IOfficeEditReq

Yes

The file to preview.

options

AxiosRequestConfig

No

Other configuration items.

IOfficeEditReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

share_id

string

No

The share ID.

file_path

string

No

The file path.

file_id

string

No

The file ID.

parent_file_id

string

No

The parent file ID.

parent_file_path

string

No

The parent file path.

option

object

No

Contains the following fields:

{

readonly: boolean,

copy: boolean

}

referer

string

No

The address. Set to location.origin or undefined.

Return value

Field

Type

Required

Description

result

IOfficeEditRes

Yes

Returned result

IOfficeEditRes

Field

Type

Required

Description

office_access_token

string

Yes

The token.

office_refresh_token

string

Yes

The token.

edit_url

string

Yes

The URL information.

refreshOfficeEditToken method

Important

Supported in standard mode

Warning

Not supported in hosted mode

To use the refresh feature for document edits, you must enable the corresponding service.

const result = await client.refreshOfficeEditToken(params, options)

Parameters

Field

Type

Required

Description

params

IOfficeRefreshReq

Yes

The file to preview.

options

AxiosRequestConfig

No

Other configuration items.

IOfficeRefreshReq

Field

Type

Required

Description

office_access_token

string

Yes

token

office_refresh_token

string

Yes

The token.

Return value

Field

Type

Required

Description

result

IOfficeRefreshReq

Yes

The result.

getAudioUrlFromDefinition method

Important

Supported in standard mode

Warning

Not supported in hosted mode

To obtain the URL for audio transcoding, you must activate the corresponding service.

const result = await client.getAudioUrlFromDefinition(params, options)

Parameters

Field

Type

Required

Description

params

IVideoPreviewUrlReq

No

For more information about the parameters, see IVideoPreviewUrlReq.

options

AxiosRequestConfig

No

Other configuration items.

IVideoPreviewUrlReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

file_id

string

Yes

The file ID.

audio_template_id

string

Yes

The audio template ID. Valid values:

LQ: Standard quality

HQ: High quality

expire_sec

string

No

The shard size.

referer

string

No

The address. Set to location.origin or undefined.

Return value

Field

Type

Required

Description

result

IVideoPreviewUrlRes

Yes

For more information about the return value, see Video transcoding.

IVideoPreviewUrlRes

Field

Type

Required

Description

preview_url

string

Yes

The playback URL.

getVideoUrlFromDefinition method

Important

Supported in standard mode

Warning

Not supported in hosted mode

To obtain the URL based on the video definition, you must activate the corresponding service.

const result = await client.getVideoUrlFromDefinition(params, options)

Parameters

Field

Type

Required

Description

params

IVideoPreviewPlayInfoReq

No

The information about the video to play. It inherits from IFileKey.

options

AxiosRequestConfig

No

Other configuration items.

IVideoPreviewPlayInfoReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

file_id

string

Yes

The file ID.

category

string

No

The category. Set to live_transcoding.

template_id

string

No

The template ID. If you do not specify this parameter, the transcoding information for all templates is pulled.

get_without_url

boolean

No

Specifies whether to pull the video stream. Default value: false. If you set this parameter to true, no URL is obtained. This reduces unnecessary transcoding costs.

url_expire_sec

number

No

The timeout period of the URL. Unit: seconds (s). Maximum value: 4 hours.

referer

string

No

The address. Set to location.origin or undefined.

Return value

Field

Type

Required

Description

result

IVideoPreviewPlayInfoRes

Yes

Return value

IVideoPreviewUrlRes

Field

Type

Required

Description

video_preview_play_info

object

Yes

Information related to playback.

... Other fields

Example:

(1) Get all supported definitions after transcoding

const previewInfo = await client.getVideoUrlFromDefinition({
  drive_id: "xxx",
  file_id: "xxx",
  get_without_url: true
});

const definitions = previewInfo?.video_preview_play_info?.live_transcoding_task_list?.map(n=>{
   return {
     template_id: n.template_id,
     template_name: n.template_name
   }
})

The definition format is as follows:

[
  {
    template_id: "264_480p",
    template_name: "pdsSD"
  },
  {
    template_id: "264_720p",
    template_name: "pdsHD"
  }
]

The parameters of the transcoded video do not exceed the values specified in the transcoding template.

Transcoding template

264_480p

264_720p

264_1080p

265_4K

Video encoder

h264

h264

h264

h265

Video resolution

720x480

1280x720

1920x1080

3840x2160

Video bitrate (kbps)

600

1500

3000

6000

Video frame rate (fps)

25

25

25

25

Audio encoder

aac

aac

aac

aac

Audio sampling rate (Hz)

44100

44100

44100

44100

Number of audio channels

2

2

2

2

Audio bitrate (kbps)

72

128

160

224

(2) Get the URL for a specific definition after transcoding

const previewInfo = await client.getVideoUrlFromDefinition({
  drive_id: "xxx",
  file_id: "xxx",
  template_id: "264_480p",
});

Normal response:

{
  "domain_id": "xxx",
  "drive_id": "xxxx",
  "file_id": "xxxx",
  "video_preview_play_info": {
    "category": "live_transcoding",
    "meta": {
      "duration": 2.484688,
      "width": 1280,
      "height": 720,
      "live_transcoding_meta": {
        "ts_segment": 10,
        "ts_total_count": 1
      }
    },
    "live_transcoding_task_list": [
      {
        "template_id": "264_480p",
        "template_name": "pdsSD",
        "status": "finished",
        "stage": "stage_all",
        "url": "https://xxxxxf1ec8c36"   // Playback URL
      }
    ]
  }
}

(3) Abnormal cases

If transcoding is in progress, the following JSON object is returned with a status code of 202. In this case, you must poll the getVideoUrlFromDefinition method until the status in live_transcoding_task_list is 'finished'.

{
  code: "VideoPreviewWaitAndRetry",
  message: "video is transcoding, please wait and retry. offline transcode when play, wait transcoding",
};

If the value-added service for transcoding is not enabled, a status code of 400 is returned:

{
  code: "VideoPreviewDisabled.OnlineVideoTranscode",
  message: "video preview online_video_transcode is disabled",
};

No corresponding transcoding information is found. This usually occurs when an incorrect template_id is passed.

{
    "domain_id": "x x x",
    "drive_id": "xxxx",
    "file_id": "61c5729c722d8f86d9c848508b8c5f6dc6604248",
    "video_preview_play_info": {
        "category": "live_transcoding",
        "meta": {
            "duration": 14.433333,
            "width": 960,
            "height": 544,
            "live_transcoding_meta": {
                "ts_segment": 10,
                "ts_total_count": 2
            }
        }
    }
}

(4) How to play the transcoded video

Transcoded videos are usually in the .m3u8 format. You can use an open source video player, such as videojs, for playback.

The following is an example of a Vue-based encapsulation.

<template>
  <video class="video-js" ref="videoPlayer"></video>
</template>
<script> 
import videojs from 'video.js';
import { getToken } from 'token.js';
import client from 'client.js'
  
export default {
  data() {
    return {
      drive_id: '1',
      file_id: '612cxxxxxxxxxxxxxxxxxxxxxxxxxxxec7d',
      url: '',
      status: 'loading', // Video status. You can perform other operations based on the status.
      // video.js configuration items
      playerOptions: {
        controls: false, // Specifies whether to display the control bar.
        autoplay: true, // Specifies whether to enable autoplay.
        muted: false, // Specifies whether to mute the video.
        html5: {
          vhs: {
            // Supports M3U8 video playback.
            withCredentials: false,
          },
        },
      },
    };
  },
  mounted() {
    this.init();
    this.getVideoUrlFromDefinition();
  },
  method: {
    init() {
      // Add Authorization to the headers to handle 401 errors.
      videojs.Vhs.xhr.beforeRequest = function (options) {
        const { access_token } = getToken() 
        options.headers = { Authorization: `Bearer ${access_token}` };
        return options;
      };
      this.player = videojs(this.$refs.videoPlayer, this.playerOptions, function () {
        this.on('seeking', () => {
          // console.log('seeking---Video is seeking---')
          this.status = 'loading';
          // Handle the case where the seek operation times out after 15s.
          if (!this.waitingTimer) {
            let second = 0;
            this.waitingTimer = setInterval(() => {
              second++;
              if (second > 15) {
                this.status = 'transcoding';
              }
            }, 1000);
          }
        });
        this.on('seeked', () => {
          // console.log('seeked---Video seek is complete---')
          this.status = 'normal';
          this.waitingTimer = null;
          clearInterval(this.waitingTimer);
        });
      });
    },
    async getVideoUrlFromDefinition() {
      try {
        // Step 1: Pull the template.
        const { video_preview_play_info } = await client.getVideoUrlFromDefinition({
          drive_id: this.drive_id,
          file_id: this.file_id,
          template_id: '',
          get_without_url: true,
        });
        // Get the successfully transcoded template.
        const live_transcoding_task_list =
          video_preview_play_info.live_transcoding_task_list.filter((item) => {
            return item.status === 'finished';
          });
        if (live_transcoding_task_list.length) {
          // Step 2: Get the URL.
          const videoInfo = await client.getVideoUrlFromDefinition({
            drive_id: this.drive_id,
            file_id: this.file_id, 
            template_id: live_transcoding_task_list[0].template_id,
            url_expire_sec: 3600,
          });
          if (
            videoInfo.video_preview_play_info.live_transcoding_task_list.length &&
            videoInfo.video_preview_play_info.live_transcoding_task_list[0].url
          ) {
            // Step 3: Get the URL.
            this.url = videoInfo.video_preview_play_info.live_transcoding_task_list[0].url;
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
  watch: {
    url(value) {
      if (value) {
        this.player.pause();
        // Modify the URL.
        this.player.src({
          src: value,
          type: 'application/x-mpegURL',
        });
        this.player.load();
        this.player.play();
      }
    },
  },
  beforeDestroy() {
    this.waitingTimer && clearInterval(this.waitingTimer);
  },
};
</script>

archiveFiles method

Archives files on the server-side and returns the async_task_id.

const result = await client.archiveFiles(params, options)

Parameters

Field

Type

Required

Description

params

IArchiveFileReq

Yes

The information about the files to archive.

options

AxiosRequestConfig

No

Other configuration items.

IArchiveFileReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

name

string

Yes

The name of the archive task.

files

array

Yes

The list of files to archive. Each item has the format { file_id: string }.

Return value

Field

Type

Required

Description

result

object

Yes

Returns the async_task_id. Format: { async_task_id: string }.

pollingArchiveFiles method

This method is an encapsulation of the archiveFiles method. It packages files on the server-side and directly returns the result. You can call this method as needed.

const result = await client.pollingArchiveFiles(params, options)

Parameters

Field

Type

Required

Description

params

IArchiveFileReq

Yes

The information about the files to archive.

options

AxiosRequestConfig

No

Other configuration items.

IArchiveFileReq

Field

Type

Required

Description

drive_id

string

Yes

The disk ID.

name

string

Yes

The name of the archive task.

files

array

Yes

The list of files to archive. Each item has the format { file_id: string }.

Returns

Field

Type

Required

Description

result

IAsyncTaskRes

Yes

The result of the archive progress.

const downloadArchiveFiles = async () => {
  const archiveName = "download.zip";
  try {
    const params = {
      drive_id: "xxxxx",
      files: ["xxxxx", "xxxx"],
      name: archiveName,
    };
    // pollingArchiveFiles only returns Failed or Succeed. It automatically polls for the Running status.
    const { state, url, message } = await client.pollingArchiveFiles(params);
    if (state === "Failed") {
      throw Error("Failed to archive files. Cause: ", message);
    } else {
      // Download the compressed file.
      const link = document.createElement("a");
      link.href = url;
      link.download = archiveName;
      link.click();
    }
  } catch (err) {
    console.log(err);
  } 
};