
# 创建直播拉流转推任务 - CreatePullTask
#### 功能介绍
根据租户指定的拉流源以及拉流任务信息创建直播拉流转推任务
#### 调用方法
请参见[如何调用API](https://support.huaweicloud.com/api-live/live_03_0001.html)。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限。
- 如果使用角色与策略授权，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-live/live_03_0013.html)。
- 如果使用身份策略授权，需具备如下身份策略权限。
  
  | 授权项                        | 访问级别  | 资源类型（\*为必须） | 条件键 | 别名 | 依赖的授权项 |
  |:---|:---|:---|:---|:---|:---|
  | live:stream:createPullTask | Write | -           | -   | -  | -      |
     
  
 
#### URI
POST /v1/{project_id}/pull/stream/task
表1路径参数 
| 参数         | 是否必选 | 参数类型   | 描述                                                                                |
|:---|:---|:---|:---|
| project_id | 是    | String | 项目ID，获取方法请参考[获取项目ID](https://support.huaweicloud.com/api-live/live_03_0023.html)。 |
   
#### 请求参数
表2请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                                                                      |
|:---|:---|:---|:---|
| X-Auth-Token | 否    | String | 用户Token，使用Token鉴权方式时必填。通过调用IAM服务获取用户Token接口获取（响应消息头中X-Subject-Token的值）。 |
   
表3请求Body参数 
| 参数                    | 是否必选 | 参数类型             | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
|:---|:---|:---|:---|
| region                | 否    | String           | **参数解释**： 任务执行区域 **约束限制**： 如果指定推流域名，则region需要与推流域名直播源站一致，缺省为租户归属region **取值范围**： 字符长度为\[1,64\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| source_type           | 是    | String           | **参数解释**： 拉流源类型 **约束限制**： 不涉及 **取值范围**： - PullLivePushLive：直播   - PullVodPushLive：视频地址路径    **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| source_urls           | 是    | Array of strings | **参数解释**： 拉流源URL **约束限制**： - 当source_type为PullLivePushLive时，只能填写一个URL。   - 当source_type为PullVodPushLive时，可以指定多个视频地址路径URL。   - 数组长度为\[1,30\]。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| domain                | 否    | String           | **参数解释**： 直播推流域名 **约束限制**： 不涉及 **取值范围**： 字符长度为\[0-255\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| app_name              | 否    | String           | **参数解释**： 应用名称 **约束限制**： 不涉及 **取值范围**： 字符长度为\[0-128\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| stream_name           | 否    | String           | **参数解释**： 流名称 **约束限制**： 不涉及 **取值范围**： 字符长度为\[0-512\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| push_args             | 否    | String           | **参数解释**： 推流参数 **约束限制**： 不涉及 **取值范围**： 字符长度为\[0,2048\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| destination_url       | 否    | String           | **参数解释**： 完整的目标URL **约束限制**： 如果指定此参数，domain、app_name和stream_name需要传入空字符串或不传 **取值范围**： 字符长度为\[0,2048\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| start_time            | 否    | String           | **参数解释**： 任务启动时间 **约束限制**： - 时间格式："2006-01-02T15:04:05Z"   - 必须小于结束时间，缺省为当前时间    **取值范围**： 不涉及 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| end_time              | 否    | String           | **参数解释**： 任务结束时间 **约束限制**： - 时间格式："2006-01-02T15:04:05Z"   - 必须大于开始时间，至多为开始时间+7天    **取值范围**： 不涉及 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| vod_loop_time         | 否    | String           | **参数解释**： 视频播放循环次数 **约束限制**： 仅当source_type为PullVodPushLive生效 **取值范围**： - -1：无限循环，以结束时间为准。   - N：按文件列表播放N轮，以播放完成和结束时间先到的为准。   - 不传、为空（""）时按缺省值生效。    **默认取值**： -1                                                                                                                                                                                                                                                                                                                                                            |
| vod_refresh_type      | 否    | String           | **参数解释**： 视频地址路径更新source_urls后的生效形式 **约束限制**： 仅当source_type为PullVodPushLive生效 **取值范围**： - immediate_new_source：立即播放新的文件源   - continue_from_file_start：从上次断流URL文件重新播放（更新任务时有效）   - continue_from_break_point：从上次断流URL文件断流位置重新播放（更新任务时有效）    **默认取值**： immediate_new_source                                                                                                                                                                                                                                                   |
| vod_start_video_index | 否    | Integer          | **参数解释**： 播放文件索引，从0开始表示第一个文件 **约束限制**： 仅当source_type为PullVodPushLive生效，最大值 len(source_urls)-1 **默认取值**： 0 **取值范围：** 0\~2147483647                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| vod_start_video_time  | 否    | Integer          | **参数解释**： 指定从上述指定文件的第几秒开始播放 **约束限制**： 仅当source_type为PullVodPushLive生效 **默认取值**： 0 **取值范围：** 0\~2147483647                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| backup_source_type    | 否    | String           | **参数解释**： 备源的类型 **约束限制**： - 仅当source_type为PullVodPushLive生效。   - 主直播源拉流中断时，自动使用备源进行拉流。    **取值范围**： PullLivePushLive：直播 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| backup_source_urls    | 否    | Array of strings | **参数解释**： 备源URL **约束限制**： 数组长度为\[0,30\]，且仅当source_type为PullVodPushLive生效                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| callback_events       | 否    | Array of strings | **参数解释**： 要回调的事件列表（不填则回调全部） - TaskStart：任务启动回调   - TaskExit：任务停止回调   - VodSourceFileStart：仅PullVodPushLive可用，文件启动切换   - VodSourceFileFinish：仅PullVodPushLive可用，文件播放完毕   - ResetTaskConfig：仅PullVodPushLive可用，任务更新   - TaskAlarm：用于告警事件通知    **约束限制**： 不涉及 |
| callback_url          | 否    | String           | **参数解释**： 回调接收地址 **约束限制**： 不涉及 **取值范围**： 字符长度为\[0,2048\]位 **默认取值**： 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
   
#### 响应参数
**状态码：200**
表4响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                 |
|:---|:---|:---|
| task_id    | String | **参数解释**： 任务ID **取值范围**： 不涉及 |
| request_id | String | **参数解释**： 请求ID **取值范围**： 不涉及 |
   
**状态码：400**
表5响应Body参数 
| 参数         | 参数类型   | 描述   |
|:---|:---|:---|
| error_code | String | 错误码  |
| error_msg  | String | 错误描述 |
| request_id | String | 请求id |
   
#### 请求示例
```
POST https://{endpoint}/v1/{project_id}/pull/stream/task
{
  "region" : "cn-north-4",
  "source_type" : "PullLivePushLive",
  "source_urls" : [ "rtmp://play.example.huawei.com/live/stream1" ],
  "domain" : "publish.example.huawei.com",
  "app_name" : "live",
  "stream_name" : "test",
  "start_time" : "2018-05-19T18:00:00Z",
  "end_time" : "2018-05-19T21:00:00Z",
  "push_args" : "arg1=value1",
  "callback_events" : [ "TaskStart", "TaskExit", "TaskAlarm" ],
  "callback_url" : "callback.example.com",
  "backup_source_type" : "PullLivePushLive",
  "backup_source_urls" : [ "rtmp://play.example.huawei.com/live/stream1_bak" ]
}
```
#### 响应示例
**状态码：200**
创建拉流转推任务成功
```
{
  "task_id" : "7864b3dc-e92f-42db-a754-08e627b6d8dd",
  "request_id" : "85968475-e92f-42db-a754-08e627b6d8dd"
}
```
**状态码：400**
创建拉流转推任务失败
```
{
  "error_code" : "LIVE.100011001",
  "error_msg" : "Request Illegal",
  "request_id" : "85968475-e92f-42db-a754-08e627b6d8dd"
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  ```
  package com.huaweicloud.sdk.test;
  import com.huaweicloud.sdk.core.auth.ICredential;
  import com.huaweicloud.sdk.core.auth.BasicCredentials;
  import com.huaweicloud.sdk.core.exception.ConnectionException;
  import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
  import com.huaweicloud.sdk.core.exception.ServiceResponseException;
  import com.huaweicloud.sdk.live.v1.region.LiveRegion;
  import com.huaweicloud.sdk.live.v1.*;
  import com.huaweicloud.sdk.live.v1.model.*;
  import java.time.OffsetDateTime;
  import java.time.format.DateTimeFormatter;
  import java.util.List;
  import java.util.ArrayList;
  public class CreatePullTaskSolution {
      public static void main(String[] args) {
          // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
          // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
          String ak = System.getenv("CLOUD_SDK_AK");
          String sk = System.getenv("CLOUD_SDK_SK");
          String projectId = "{project_id}";
          ICredential auth = new BasicCredentials()
                  .withProjectId(projectId)
                  .withAk(ak)
                  .withSk(sk);
          LiveClient client = LiveClient.newBuilder()
                  .withCredential(auth)
                  .withRegion(LiveRegion.valueOf("<YOUR REGION>"))
                  .build();
          CreatePullTaskRequest request = new CreatePullTaskRequest();
          LivePullStreamTask body = new LivePullStreamTask();
          List<LivePullStreamTask.CallbackEventsEnum> listbodyCallbackEvents = new ArrayList<>();
          listbodyCallbackEvents.add(LivePullStreamTask.CallbackEventsEnum.fromValue("TaskStart"));
          listbodyCallbackEvents.add(LivePullStreamTask.CallbackEventsEnum.fromValue("TaskExit"));
          listbodyCallbackEvents.add(LivePullStreamTask.CallbackEventsEnum.fromValue("TaskAlarm"));
          List<String> listbodyBackupSourceUrls = new ArrayList<>();
          listbodyBackupSourceUrls.add("rtmp://play.example.huawei.com/live/stream1_bak");
          List<String> listbodySourceUrls = new ArrayList<>();
          listbodySourceUrls.add("rtmp://play.example.huawei.com/live/stream1");
          body.withCallbackUrl("callback.example.com");
          body.withCallbackEvents(listbodyCallbackEvents);
          body.withBackupSourceUrls(listbodyBackupSourceUrls);
          body.withBackupSourceType("PullLivePushLive");
          body.withEndTime(OffsetDateTime.parse("2018-05-19T21:00:00Z", DateTimeFormatter.ISO_OFFSET_DATE_TIME));
          body.withStartTime(OffsetDateTime.parse("2018-05-19T18:00:00Z", DateTimeFormatter.ISO_OFFSET_DATE_TIME));
          body.withPushArgs("arg1=value1");
          body.withStreamName("test");
          body.withAppName("live");
          body.withDomain("publish.example.huawei.com");
          body.withSourceUrls(listbodySourceUrls);
          body.withSourceType(LivePullStreamTask.LivePullStreamTask.fromValue("PullLivePushLive"));
          body.withRegion("cn-north-4");
          request.withBody(body);
          try {
              CreatePullTaskResponse response = client.createPullTask(request);
              System.out.println(response.toString());
          } catch (ConnectionException e) {
              e.printStackTrace();
          } catch (RequestTimeoutException e) {
              e.printStackTrace();
          } catch (ServiceResponseException e) {
              e.printStackTrace();
              System.out.println(e.getHttpStatusCode());
              System.out.println(e.getRequestId());
              System.out.println(e.getErrorCode());
              System.out.println(e.getErrorMsg());
          }
      }
  }
  ```
- [Python]
  ```
  # coding: utf-8
  import os
  from huaweicloudsdkcore.auth.credentials import BasicCredentials
  from huaweicloudsdklive.v1.region.live_region import LiveRegion
  from huaweicloudsdkcore.exceptions import exceptions
  from huaweicloudsdklive.v1 import *
  if __name__ == "__main__":
      # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak = os.environ["CLOUD_SDK_AK"]
      sk = os.environ["CLOUD_SDK_SK"]
      projectId = "{project_id}"
      credentials = BasicCredentials(ak, sk, projectId)
      client = LiveClient.new_builder() \
          .with_credentials(credentials) \
          .with_region(LiveRegion.value_of("<YOUR REGION>")) \
          .build()
      try:
          request = CreatePullTaskRequest()
          listCallbackEventsbody = [
              "TaskStart",
              "TaskExit",
              "TaskAlarm"
          ]
          listBackupSourceUrlsbody = [
              "rtmp://play.example.huawei.com/live/stream1_bak"
          ]
          listSourceUrlsbody = [
              "rtmp://play.example.huawei.com/live/stream1"
          ]
          request.body = LivePullStreamTask(
              callback_url="callback.example.com",
              callback_events=listCallbackEventsbody,
              backup_source_urls=listBackupSourceUrlsbody,
              backup_source_type="PullLivePushLive",
              end_time="2018-05-19T21:00:00Z",
              start_time="2018-05-19T18:00:00Z",
              push_args="arg1=value1",
              stream_name="test",
              app_name="live",
              domain="publish.example.huawei.com",
              source_urls=listSourceUrlsbody,
              source_type="PullLivePushLive",
              region="cn-north-4"
          )
          response = client.create_pull_task(request)
          print(response)
      except exceptions.ClientRequestException as e:
          print(e.status_code)
          print(e.request_id)
          print(e.error_code)
          print(e.error_msg)
  ```
- [Go]
  ```
  package main
  import (
  "fmt"
  "time"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/sdktime"
      live "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/live/v1"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/live/v1/model"
      region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/live/v1/region"
  )
  func main() {
      // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak := os.Getenv("CLOUD_SDK_AK")
      sk := os.Getenv("CLOUD_SDK_SK")
      projectId := "{project_id}"
      auth, err := basic.NewCredentialsBuilder().
          WithAk(ak).
          WithSk(sk).
          WithProjectId(projectId).
          SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      hcClient, err := live.LiveClientBuilder().
           WithRegion(region.ValueOf("<YOUR REGION>")).
           WithCredential(auth).
           SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      client := live.NewLiveClient(hcClient)
      request := &model.CreatePullTaskRequest{}
  var listCallbackEventsbody = []model.LivePullStreamTaskCallbackEvents{
          model.GetLivePullStreamTaskCallbackEventsEnum().TASK_START,
      model.GetLivePullStreamTaskCallbackEventsEnum().TASK_EXIT,
      model.GetLivePullStreamTaskCallbackEventsEnum().TASK_ALARM,
      }
  var listBackupSourceUrlsbody = []string{
          "rtmp://play.example.huawei.com/live/stream1_bak",
      }
  var listSourceUrlsbody = []string{
          "rtmp://play.example.huawei.com/live/stream1",
      }
  callbackUrlLivePullStreamTask:= "callback.example.com"
  backupSourceTypeLivePullStreamTask:= "PullLivePushLive"
  dateTimeEndTime, _ := time.ParseInLocation("2006-01-02T15:04:05Z", "2018-05-19T21:00:00Z", time.UTC)
  endTimeLivePullStreamTask:= sdktime.SdkTime(dateTimeEndTime)
  dateTimeStartTime, _ := time.ParseInLocation("2006-01-02T15:04:05Z", "2018-05-19T18:00:00Z", time.UTC)
  startTimeLivePullStreamTask:= sdktime.SdkTime(dateTimeStartTime)
  pushArgsLivePullStreamTask:= "arg1=value1"
  streamNameLivePullStreamTask:= "test"
  appNameLivePullStreamTask:= "live"
  domainLivePullStreamTask:= "publish.example.huawei.com"
  regionLivePullStreamTask:= "cn-north-4"
  request.Body = &model.LivePullStreamTask{
  CallbackUrl: &callbackUrlLivePullStreamTask,
  CallbackEvents: &listCallbackEventsbody,
  BackupSourceUrls: &listBackupSourceUrlsbody,
  BackupSourceType: &backupSourceTypeLivePullStreamTask,
  EndTime: &endTimeLivePullStreamTask,
  StartTime: &startTimeLivePullStreamTask,
  PushArgs: &pushArgsLivePullStreamTask,
  StreamName: &streamNameLivePullStreamTask,
  AppName: &appNameLivePullStreamTask,
  Domain: &domainLivePullStreamTask,
  SourceUrls: listSourceUrlsbody,
  SourceType: model.GetLivePullStreamTaskSourceTypeEnum().PULL_LIVE_PUSH_LIVE,
  Region: &regionLivePullStreamTask,
  }
  response, err := client.CreatePullTask(request)
  if err == nil {
          fmt.Printf("%+v\n", response)
      } else {
          fmt.Println(err)
      }
  }
  ```
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/Live/sdk?api=CreatePullTask)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述         |
|:---|:---|
| 200 | 创建拉流转推任务成功 |
| 400 | 创建拉流转推任务失败 |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-live/ErrorCode.html)。
