// @ts-check
var fs = require('fs');
var path = require('path');
var util = require('./util');
var COS = require('../index');
var pathLib = require('path');
var config = require('./config');
var json2xml = require('../sdk/util').json2xml;


var cos = new COS({
    // 必选参数
    SecretId: config.SecretId,
    SecretKey: config.SecretKey,
    // 可选参数
    FileParallelLimit: 3,    // 控制文件上传并发数
    ChunkParallelLimit: 8,   // 控制单个文件下分片上传并发数，在同园区上传可以设置较大的并发数
    ChunkSize: 1024 * 1024 * 8,  // 控制分片大小，单位 B，在同园区上传可以设置较大的分片大小
    Proxy: '',
    Protocol: 'https:',
    FollowRedirect: false,
    });

var TaskId;

function camSafeUrlEncode(str) {
    return encodeURIComponent(str)
        .replace(/!/g, '%21')
        .replace(/'/g, '%27')
        .replace(/\(/g, '%28')
        .replace(/\)/g, '%29')
        .replace(/\*/g, '%2A');
}

function getAuth() {
    var key = '1mb.zip';
    var auth = cos.getAuth({
        Method: 'get',
        Key: key,
        Expires: 60,
    });
    // 注意：这里的 Bucket 格式是 test-1250000000
    console.log('http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' + camSafeUrlEncode(key).replace(/%2F/g, '/') + '?sign=' + encodeURIComponent(auth));
}

function getV4Auth() {
    console.log();
    var key = '中文.txt';
    var auth = cos.getV4Auth({
        Bucket: config.Bucket,
        Key: key,
        Expires: 60,
    });
    // 注意：这里的 Bucket 格式是 test-1250000000
    console.log('http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' + camSafeUrlEncode(key).replace(/%2F/g, '/') + '?sign=' + encodeURIComponent(auth));
}

function getObjectUrl() {
    var url = cos.getObjectUrl({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
        Expires: 60,
        Sign: true,
    }, function (err, data) {
        console.log(err || data);
    });
    console.log(url);
}

function getService() {
    cos.getService({
      Region: 'ap-guangzhou',
    },function (err, data) {
        console.log(err || data);
    });
}

function putBucket() {
    cos.putBucket({
        Bucket: 'testnew-' + config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1),
        Region: 'ap-guangzhou',
        // BucketAZConfig: 'MAZ',
        // BucketArchConfig: 'OFS',
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucket() {
    cos.getBucket({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function headBucket() {
    cos.headBucket({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucket() {
    cos.deleteBucket({
        Bucket: 'testnew-' + config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1),
        Region: 'ap-guangzhou'
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketAcl() {
    cos.putBucketAcl({
        Bucket: config.Bucket,
        Region: config.Region,
        // GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantWrite: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantReadAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantWriteAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // ACL: 'public-read-write',
        // ACL: 'public-read',
        ACL: 'private',
        AccessControlPolicy: {
        "Owner": { // AccessControlPolicy 里必须有 owner
            "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 Bucket 所属用户的 QQ 号
        },
        "Grants": [
            {
                "Grantee": {
                    "URI": "http://cam.qcloud.com/groups/global/AllUsers", // 允许匿名用户组访问
                },
                "Permission": "READ"
            },
            {
                "Grantee": {
                    "ID": "qcs::cam::uin/1001:uin/1001", // 10002 是 QQ 号
                },
                "Permission": "WRITE"
            },  {
                "Grantee": {
                    "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
                },
                "Permission": "READ_ACP"
            }, {
                "Grantee": {
                    "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
                },
                "Permission": "WRITE_ACP"
            }]
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketAcl() {
    cos.getBucketAcl({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketCors() {
    cos.putBucketCors({
        Bucket: config.Bucket,
        Region: config.Region,
        ResponseVary: "true",
        CORSRules: [{
            "AllowedOrigin": ["*"],
            "AllowedMethod": ["GET", "POST", "PUT", "DELETE", "HEAD"],
            "AllowedHeader": ["*"],
            "ExposeHeader": ["ETag", "Date", "Content-Length", "x-cos-acl", "x-cos-version-id", "x-cos-request-id", "x-cos-delete-marker", "x-cos-server-side-encryption"],
            "MaxAgeSeconds": 5
        }]
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketCors() {
    cos.getBucketCors({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketCors() {
    cos.deleteBucketCors({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketPolicy() {
    var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
    cos.putBucketPolicy({
        Policy: {
            "version": "2.0",
            "statement": [{
                "effect": "allow",
                "principal": {"qcs": ["qcs::cam::uin/10001:uin/10001"]}, // 这里的 10001 是 QQ 号
                "action": [
                    // 这里可以从临时密钥的权限上控制前端允许的操作
                    // 'name/cos:*', // 这样写可以包含下面所有权限

                    // // 列出所有允许的操作
                    // // ACL 读写
                    // 'name/cos:GetBucketACL',
                    // 'name/cos:PutBucketACL',
                    // 'name/cos:GetObjectACL',
                    // 'name/cos:PutObjectACL',
                    // // 简单 Bucket 操作
                    // 'name/cos:PutBucket',
                    // 'name/cos:HeadBucket',
                    // 'name/cos:GetBucket',
                    // 'name/cos:DeleteBucket',
                    // 'name/cos:GetBucketLocation',
                    // // Versioning
                    // 'name/cos:PutBucketVersioning',
                    // 'name/cos:GetBucketVersioning',
                    // // CORS
                    // 'name/cos:PutBucketCORS',
                    // 'name/cos:GetBucketCORS',
                    // 'name/cos:DeleteBucketCORS',
                    // // Lifecycle
                    // 'name/cos:PutBucketLifecycle',
                    // 'name/cos:GetBucketLifecycle',
                    // 'name/cos:DeleteBucketLifecycle',
                    // // Replication
                    // 'name/cos:PutBucketReplication',
                    // 'name/cos:GetBucketReplication',
                    // 'name/cos:DeleteBucketReplication',
                    // // 删除文件
                    // 'name/cos:DeleteMultipleObject',
                    // 'name/cos:DeleteObject',
                    // 简单文件操作
                    'name/cos:PutObject',
                    'name/cos:AppendObject',
                    'name/cos:GetObject',
                    'name/cos:HeadObject',
                    'name/cos:OptionsObject',
                    'name/cos:PutObjectCopy',
                    'name/cos:PostObjectRestore',
                    // 分片上传操作
                    'name/cos:InitiateMultipartUpload',
                    'name/cos:ListMultipartUploads',
                    'name/cos:ListParts',
                    'name/cos:UploadPart',
                    'name/cos:CompleteMultipartUpload',
                    'name/cos:AbortMultipartUpload',
                ],
                // "resource": ["qcs::cos:ap-guangzhou:uid/1250000000:test-1250000000/*"] // 1250000000 是 appid
                "resource": ["qcs::cos:" + config.Region + ":uid/" + AppId + ":" + config.Bucket + "/*"] // 1250000000 是 appid
            }]
        },
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketPolicy() {
    cos.getBucketPolicy({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketPolicy() {
    cos.deleteBucketPolicy({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketLocation() {
    cos.getBucketLocation({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketTagging() {
    cos.putBucketTagging({
        Bucket: config.Bucket,
        Region: config.Region,
        Tags: [
            {"Key": "k1", "Value": "v1"},
            {"Key": "k2", "Value": "v2"}
        ]
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketTagging() {
    cos.getBucketTagging({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketTagging() {
    cos.deleteBucketTagging({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketLifecycle() {
    cos.putBucketLifecycle({
        Bucket: config.Bucket,
        Region: config.Region,
        Rules: [{
            "ID": "1",
            "Status": "Enabled",
            "Filter": {},
            "Transition": {
                "Days": "30",
                "StorageClass": "STANDARD_IA"
            }
        }, {
            "ID": "2",
            "Status": "Enabled",
            "Filter": {
                "Prefix": "dir/"
            },
            "Transition": {
                "Days": "180",
                "StorageClass": "ARCHIVE"
            }
        }, {
            "ID": "3",
            "Status": "Enabled",
            "Filter": {},
            "Expiration": {
                "Days": "180"
            }
        }, {
            "ID": "4",
            "Status": "Enabled",
            "Filter": {},
            "AbortIncompleteMultipartUpload": {
                "DaysAfterInitiation": "30"
            }
        }],
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketLifecycle() {
    cos.getBucketLifecycle({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketLifecycle() {
    cos.deleteBucketLifecycle({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketVersioning() {
    cos.putBucketVersioning({
        Bucket: config.Bucket,
        Region: config.Region,
        VersioningConfiguration: {
            Status: "Enabled"
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketVersioning() {
    cos.getBucketVersioning({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketReplication() {
    var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
    cos.putBucketReplication({
        Bucket: config.Bucket,
        Region: config.Region,
        ReplicationConfiguration: {
            Role: "qcs::cam::uin/10001:uin/10001",
            Rules: [{
                ID: "1",
                Status: "Enabled",
                Prefix: "sync/",
                Destination: {
                    Bucket: "qcs:id/0:cos:ap-chengdu:appid/" + AppId + ":backup",
                    // StorageClass: "Standard",
                }
            }]
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketReplication() {
    cos.getBucketReplication({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketReplication() {
    cos.deleteBucketReplication({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketWebsite() {
    cos.putBucketWebsite({
        Bucket: config.Bucket,
        Region: config.Region,
        WebsiteConfiguration: {
            IndexDocument: {
                Suffix: "index.html" // 必选
            },
            RedirectAllRequestsTo: {
                Protocol: "https"
            },
            // ErrorDocument: {
            //     Key: "error.html"
            // },
            // RoutingRules: [{
            //     Condition: {
            //         HttpErrorCodeReturnedEquals: "404"
            //     },
            //     Redirect: {
            //         Protocol: "https",
            //         ReplaceKeyWith: "404.html"
            //     }
            // }, {
            //     Condition: {
            //         KeyPrefixEquals: "docs/"
            //     },
            //     Redirect: {
            //         Protocol: "https",
            //         ReplaceKeyPrefixWith: "documents/"
            //     }
            // }, {
            //     Condition: {
            //         KeyPrefixEquals: "img/"
            //     },
            //     Redirect: {
            //         Protocol: "https",
            //         ReplaceKeyWith: "picture.jpg"
            //     }
            // }]
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketWebsite() {
    cos.getBucketWebsite({
        Bucket: config.Bucket,
        Region: config.Region
    },function(err, data){
        console.log(err || data);
    });
}

function deleteBucketWebsite() {
    cos.deleteBucketWebsite({
        Bucket: config.Bucket,
        Region: config.Region
    },function(err, data){
        console.log(err || data);
    });
}

function putBucketReferer() {
    cos.putBucketReferer({
        Bucket: config.Bucket,
        Region: config.Region,
        RefererConfiguration: {
            Status: 'Enabled',
            RefererType: 'White-List',
            DomainList: {
                Domains: [
                    '*.qq.com',
                    '*.qcloud.com',
                ]
            },
            EmptyReferConfiguration: 'Allow',
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketReferer() {
    cos.getBucketReferer({
        Bucket: config.Bucket,
        Region: config.Region
    },function(err, data){
        console.log(err || JSON.stringify(data, null, '    '));
    });
}

function putBucketDomain() {
    cos.putBucketDomain({
        Bucket: config.Bucket,
        Region: config.Region,
        DomainRule:[{
            Status: "DISABLED",
            Name: "www.testDomain1.com",
            Type: "REST"
        }, {
            Status: "DISABLED",
            Name: "www.testDomain2.com",
            Type: "WEBSITE"
        }]
    },function(err, data){
        console.log(err || data);
    });
}

function getBucketDomain() {
    cos.getBucketDomain({
        Bucket: config.Bucket,
        Region: config.Region
    },function(err, data){
        console.log(err || data);
    });
}

function deleteBucketDomain() {
    cos.deleteBucketDomain({
        Bucket: config.Bucket,
        Region: config.Region
    },function(err, data){
        console.log(err || data);
    });
}

function putBucketOrigin() {
    cos.putBucketOrigin({
        Bucket: config.Bucket,
        Region: config.Region,
        OriginRule: [{
            OriginType: 'Mirror',
            OriginCondition: {HTTPStatusCode: 404, Prefix: ''},
            OriginParameter: {
                Protocol: 'HTTP',
                FollowQueryString: 'true',
                HttpHeader: {
                    NewHttpHeader: {
                        Header: [{
                            Key: 'a',
                            Value: 'a'
                        }]
                    }
                },
                FollowRedirection: 'true',
                HttpRedirectCode: ['301', '302']
            },
            OriginInfo: {
                HostInfo: {HostName: 'qq.com'},
                FileInfo: {
                    PrefixConfiguration: {Prefix: '123/'},
                    SuffixConfiguration: {Suffix: '.jpg'}
                }
            },
            RulePriority: 1
        }]
    },function(err, data){
        console.log(err || data);
    });
}

function getBucketOrigin() {
    cos.getBucketOrigin({
        Bucket: config.Bucket,
        Region: config.Region,
    }, function(err, data){
        console.log(err || data);
    });
}

function deleteBucketOrigin() {
    cos.deleteBucketOrigin({
        Bucket: config.Bucket,
        Region: config.Region,
    },function(err, data){
        console.log(err || data);
    });
}

function putBucketLogging() {
    var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
    cos.putBucketLogging({
        Bucket: config.Bucket,
        Region: config.Region,
        BucketLoggingStatus: {
            LoggingEnabled: {
                TargetBucket: 'bucket-logging-' + AppId,
                TargetPrefix: 'logging'
            }
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketLogging() {
    cos.getBucketLogging({
        Bucket: config.Bucket,
        Region: config.Region
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteBucketLogging() {
    cos.putBucketLogging({
        Bucket: config.Bucket,
        Region: config.Region,
        BucketLoggingStatus: {
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function putBucketInventory() {
    var AppId = config.Bucket.substr(config.Bucket.lastIndexOf('-') + 1);
    cos.putBucketInventory({
        Bucket: config.Bucket,
        Region: config.Region,
        Id: 'inventory_test',
        InventoryConfiguration: {
            Id: 'inventory_test',
            IsEnabled: 'true',
            Destination: {
                COSBucketDestination: {
                    Format: 'CSV',
                    AccountId: config.Uin,
                    Bucket: 'qcs::cos:ap-guangzhou::bucket-logging-' + AppId,
                    Prefix: 'inventory',
                    Encryption: {
                        SSECOS: ''
                    }
                }
            },
            Schedule: {
                Frequency: 'Daily'
            },
            Filter: {
                Prefix: 'myPrefix'
            },
            IncludedObjectVersions: 'All',
            OptionalFields: [
                'Size',
                'LastModifiedDate',
                'ETag',
                'StorageClass',
                'IsMultipartUploaded',
                'ReplicationStatus'
            ]
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketInventory() {
    cos.getBucketInventory({
        Bucket: config.Bucket,
        Region: config.Region,
        Id: 'inventory_test'
    }, function(err, data) {
        console.log(err || JSON.stringify(data));
    });
}

function deleteBucketInventory() {
    cos.deleteBucketInventory({
        Bucket: config.Bucket,
        Region: config.Region,
        Id: 'inventory_test'
    }, function(err, data) {
        console.log(err || JSON.stringify(data));
    });
}

function listBucketInventory() {
    cos.listBucketInventory({
        Bucket: config.Bucket,
        Region: config.Region
    }, function(err, data) {
        console.log(err || JSON.stringify(data));
    });
}

function putBucketAccelerate() {
    cos.putBucketAccelerate({
        Bucket: config.Bucket,
        Region: config.Region,
        AccelerateConfiguration: {
            Status: 'Enabled'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getBucketAccelerate() {
    cos.getBucketAccelerate({
        Bucket: config.Bucket,
        Region: config.Region,
    }, function(err, data) {
        console.log(err || data);
    });
}

function putBucketEncryption() {
    cos.putBucketEncryption({
        Bucket: config.Bucket,
        Region: config.Region,
        ServerSideEncryptionConfiguration: {
            Rule: [{
                ApplySideEncryptionConfiguration: {
                    SSEAlgorithm: 'AES256',
                },
            }],
        },
    }, function(err, data) {
        console.log(JSON.stringify(err || data, null, 2));
    });
}

function getBucketEncryption() {
    cos.getBucketEncryption({
        Bucket: config.Bucket,
        Region: config.Region
    }, function(err, data) {
        console.log(err || JSON.stringify(data));
    });
}

function deleteBucketEncryption() {
    cos.deleteBucketEncryption({
        Bucket: config.Bucket,
        Region: config.Region
    }, function(err, data) {
        console.log(err || JSON.stringify(data));
    });
}

function putObject() {
    // 创建测试文件
    var filename = '1mb.zip';
    var filepath = path.resolve(__dirname, filename);
    util.createFile(filepath, 1024 * 1024, function (err) {
      // 调用方法
      cos.putObject({
          Bucket: config.Bucket, /* 必须 */
          Region: config.Region,
          Key: filename, /* 必须 */
          onTaskReady: function (tid) {
              TaskId = tid;
          },
          onProgress: function (progressData) {
              console.log(JSON.stringify(progressData));
          },
          // 格式1. 传入文件内容
          // Body: fs.readFileSync(filepath),
          // 格式2. 传入文件流，必须需要传文件大小
          Body: fs.createReadStream(filepath),
          ContentLength: fs.statSync(filepath).size,
          Headers: {
              // 万象持久化接口，上传时持久化
              // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
          },
      }, function (err, data) {
          console.log(err || data);
          fs.unlinkSync(filepath);
      });
  });
}

function putObject_base64ToBuffer() {
  // 创建测试文件
  var filename = 'test.png';
  var filepath = path.resolve(__dirname, filename);
  var base64Url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAABRFBMVEUAAAAAo/8Ao/8Ao/8Ao/8ApP8Aov8Ao/8Abv8Abv8AyNwAyNwAo/8Ao/8Ao/8Abv8Ao/8AivgAo/8AyNwAbv8Abv8AydwApf8Abf8Ao/8AbP8Ao/8AyNwAydwAbv8AydwApP8Ao/8AyNwAo/8AyNwAydsAyNwAxd8Aov8AyNwAytsAo/8Abv8AyNwAbv8Av+MAo/8AytsAo/8Abv8AyNwAo/8Abv8AqfkAbv8Aov8Abv8AyNwAov8Abv8Ao/8Abv8Ao/8AydwAo/8Ao/8Ate8Ay9oAvOcAof8AveAAyNwAyNwAo/8AyNwAy9kAo/8AyNwAyNwAo/8AqP8Aaf8AyNwAbv0Abv8Abv8AaP8Ao/8Ao/8Ao/8Ao/8Abv8AyNwAgvcAaP8A0dkAo/8AyNwAav8Abv8Ao/8Abv8AyNwAy9sAvOUAtePdkYxjAAAAZnRSTlMAw/co8uAuJAn8+/Tt29R8DAX77+nZz87Jv6CTh3lxTklAPjouJRsL5tjAuLiyr62roaCakYp0XVtOQTMyLiohICAcGRP49vTv5+PJurawq6mnnJuYl4+OiIB7eXVvX15QSDgqHxNcw3l6AAABe0lEQVQ4y82P11oCQQxGIy5FUJpKk6aAhV6k92LvvXedDfj+92ZkYQHxnnMxu3/OfJMEJo6y++baXf5XVw22GVGcsRmq431mQZRYyIzRGgdXi+HwIv86NDBKisrRAtU1hSj9pkZ9jpo/9YKbRsmNNKCHDXI00BxfMMirKNpMcjQ5Lm4/YZArUXyBYUwg40nsdr5jb3LBe25VWpNeKa1GENsEnq52C80z1uW48estiKjb19G54QdCrScnKAU69U3KJ4jzrsBawDWPuOcBqMyRvlcb1Y+zjMUBVsivAKe4gXgEKiVjSh9wlunGMmwiOqFL3RI0cj+nkgp3jC1BELVFkGiZSuvkp3tZZWZ2sKCuDj185PXqfmwI7AAOUctHkJoOeXg3sxA4ES+l7CVvrYHMEmNp8GtR+wycPG0+1RrwWQUzl4CvgQmPP5Ddofl8tWkJVT7J+BIAaxEktrYZoRAUfXgOGYHfcOqw3WF/EdLccz5cMfvUCPb4QwUmhB8+v12HZPCkbgAAAABJRU5ErkJggg==';
  var body = Buffer.from(base64Url.split(',')[1] , 'base64');
  util.createFile(filepath, 1024 * 1024, function (err) {
    // 调用方法
    cos.putObject({
        Bucket: config.Bucket, /* 必须 */
        Region: config.Region,
        Key: filename, /* 必须 */
        onTaskReady: function (tid) {
            TaskId = tid;
        },
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        },
        // 格式1. 传入文件内容
        // Body: fs.readFileSync(filepath),
        // 格式2. 传入文件流，必须需要传文件大小
        Body: body,
        ContentLength: body.length,
        Headers: {
            // 万象持久化接口，上传时持久化
            // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
        },
    }, function (err, data) {
        console.log(err || data);
        fs.unlinkSync(filepath);
    });
});
}

function putObjectCopy() {
    cos.putObjectCopy({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.copy.zip',
        CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + camSafeUrlEncode('1mb.zip').replace(/%2F/g, '/'),
    }, function (err, data) {
        console.log(err || data);
    });
}

function getObject() {
    var filepath1 = path.resolve(__dirname, '1mb.out1.zip');
    var filepath2 = path.resolve(__dirname, '1mb.out2.zip');
    var filepath3 = path.resolve(__dirname, '1mb.out3.zip');

    // file1 获取对象字节到内存变量
    cos.getObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        }
    }, function (err, data) {
        if(data){
          fs.writeFileSync(filepath1, data.Body);
        } else {
          console.log(err);
        }
    });

}

function headObject() {
    cos.headObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip'
    }, function (err, data) {
        console.log(err || data);
    });
}

function listObjectVersions() {
    cos.listObjectVersions({
        Bucket: config.Bucket,
        Region: config.Region,
        // Prefix: "",
        // Delimiter: '/'
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, '    '));
    });
}

function putObjectAcl() {
    cos.putObjectAcl({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
        // GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantWriteAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantReadAcp: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
        // ACL: 'public-read-write',
        // ACL: 'public-read',
        // ACL: 'private',
        ACL: 'default', // 继承上一级目录权限
        // AccessControlPolicy: {
        //     "Owner": { // AccessControlPolicy 里必须有 owner
        //         "ID": 'qcs::cam::uin/459000000:uin/459000000' // 459000000 是 Bucket 所属用户的 QQ 号
        //     },
        //     "Grants": [{
        //         "Grantee": {
        //             "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
        //         },
        //         "Permission": "READ"
        //     }]
        // }
    }, function (err, data) {
        console.log(err || data);
    });
}

function getObjectAcl() {
    cos.getObjectAcl({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip'
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteObject() {
    cos.deleteObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip'
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteMultipleObject() {
    cos.deleteMultipleObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Objects: [
            {Key: '中文/中文.txt'},
            {Key: '中文/中文.zip',VersionId: 'MTg0NDY3NDI1MzM4NzM0ODA2MTI'},
        ]
    }, function (err, data) {
        console.log(err || data);
    });
}

function restoreObject() {
    cos.restoreObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1.txt',
        RestoreRequest: {
            Days: 1,
            CASJobParameters: {
                Tier: 'Expedited'
            }
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

var selectCsvOpt = {
    Bucket: config.Bucket,
    Region: config.Region,
    Key: '1.csv',
    SelectType: 2,
    SelectRequest: {
        // Expression: "select * from cosobject s limit 100",
        Expression: "Select * from COSObject",
        ExpressionType: "SQL",
        InputSerialization: {
            CSV: {
                FileHeaderInfo: "IGNORE",
                RecordDelimiter: "\\n",
                FieldDelimiter: ",",
                QuoteCharacter: "\"",
                QuoteEscapeCharacter: "\"",
                Comments: "#",
                AllowQuotedRecordDelimiter: "FALSE"
            }
        },
        OutputSerialization: {
            CSV: {
                QuoteFields: "ASNEEDED",
                RecordDelimiter: "\\n",
                FieldDelimiter: ",",
                QuoteCharacter: "\"",
                QuoteEscapeCharacter: "\""
            }
        },
        RequestProgress: {Enabled: "FALSE"}
    },
};

var selectJsonOpt = {
    Bucket: config.Bucket,
    Region: config.Region,
    Key: '1.json',
    SelectType: 2,
    SelectRequest: {
        Expression: "Select * from COSObject",
        ExpressionType: "SQL",
        InputSerialization: {JSON: {Type: "DOCUMENT"}},
        OutputSerialization: {JSON: {RecordDelimiter: "\n"}},
        RequestProgress: {Enabled: "FALSE"}
    },
};

function selectObjectContentStream() {
    // 查询 JSON
    var opt = Object.assign({
        // DataType: 'raw',
    }, selectJsonOpt);
    var selectStream = cos.selectObjectContentStream(opt, function (err, data) {
        console.log(err || data);
    });
    var outFile = './result.txt';
    selectStream.pipe(fs.createWriteStream(outFile));
    selectStream.on('end', () => console.log(fs.readFileSync(outFile).toString()))
}

function selectObjectContent() {
    // // 如果返回结果很大，可以用 selectObjectContentStream 处理
    // // 查询 CSV
    // cos.selectObjectContent(selectCsvOpt, function (err, data) {
    //     console.log(err || data);
    // });

    // 查询 JSON
    cos.selectObjectContent(selectJsonOpt, function (err, data) {
        console.log(err || data);
    });
}

function multipartList() {
    cos.multipartList({
        Bucket: config.Bucket,
        Region: config.Region,
        Prefix: '',
        MaxUploads: 1,
        Delimiter: '/'
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function multipartListPart() {
    cos.multipartListPart({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: "10mb.zip",
        MaxParts: 1,
        UploadId: 'xxx',
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function multipartInit() {
    cos.multipartInit({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: "10mb.zip",
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function multipartUpload() {
    cos.multipartUpload({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: "10mb.zip",
        UploadId: 'xxx',
        PartNumber: 1,
        Body: '123',
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function multipartCom() {
    cos.multipartComplete({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1.zip',
        UploadId: 'xxx',
        Parts: [{
            PartNumber: 1,
            ETag: 'xxx',
        }],
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function multipartAbort() {
    cos.multipartAbort({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: "10mb.zip",
        UploadId: 'xxx',
    }, function (err, data) {
        console.log(err || JSON.stringify(data, null, 2));
    });
}

function abortUploadTask() {
    cos.abortUploadTask({
        Bucket: config.Bucket, /* 必须 */
        Region: config.Region, /* 必须 */
        // 格式1，删除单个上传任务
        // Level: 'task',
        // Key: '10mb.zip',
        // UploadId: '14985543913e4e2642e31db217b9a1a3d9b3cd6cf62abfda23372c8d36ffa38585492681e3',
        // 格式2，删除单个文件所有未完成上传任务
        Level: 'file',
        Key: '10mb.zip',
        // 格式3，删除 Bucket 下所有未完成上传任务
        // Level: 'bucket',
    }, function (err, data) {
        console.log(err || data);
    });
}

function sliceUploadFile() {
    // 创建测试文件
    var filename = '10mb.zip';
    var filepath = path.resolve(__dirname, filename);
    util.createFile(filepath, 1024 * 1024 * 10, function (err) {
        // 调用方法
        cos.sliceUploadFile({
            Bucket: config.Bucket, /* 必须 */
            Region: config.Region,
            Key: filename, /* 必须 */
            FilePath: filepath, /* 必须 */
            onTaskReady: function (tid) {
                TaskId = tid;
            },
            onHashProgress: function (progressData) {
                console.log(JSON.stringify(progressData));
            },
            onProgress: function (progressData) {
                console.log(JSON.stringify(progressData));
            },
            Headers: {
                // 万象持久化接口，上传时持久化
                // 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
            },
        }, function (err, data) {
            console.log(err || data);
            fs.unlinkSync(filepath);
        });
    });
}

function cancelTask() {
    cos.cancelTask(TaskId);
    console.log('canceled');
}

function pauseTask() {
    cos.pauseTask(TaskId);
    console.log('paused');
}

function restartTask() {
    cos.restartTask(TaskId);
    console.log('restart');
}

function uploadFile() {
  var filename = '3mb.zip';
  var filepath = path.resolve(__dirname, filename);
  util.createFile(filepath, 1024 * 1024 * 3, function (err) {
      cos.uploadFile({
          Bucket: config.Bucket,
          Region: config.Region,
          Key: filename,
          FilePath: filepath,
          SliceSize: 1024 * 1024 * 5, // 大于5mb才进行分块上传
          onProgress: function (info) {
              var percent = Math.floor(info.percent * 10000) / 100;
              var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
              console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
          },
      }, function (err, data) {
          console.log('上传' + (err ? '失败' : '完成'));
          console.log(err || data);
          fs.unlinkSync(filepath);
      });
  });
}

function uploadFiles() {
    var filepath = path.resolve(__dirname, '1mb.zip');
    util.createFile(filepath, 1024 * 1024 * 10, function (err) {
        var filename = 'mb.zip';
        cos.uploadFiles({
            files: [{
                Bucket: config.Bucket,
                Region: config.Region,
                Key: '1' + filename,
                FilePath: filepath,
            }, {
                Bucket: config.Bucket,
                Region: config.Region,
                Key: '2' + filename,
                FilePath: filepath,
            // }, {
            //     Bucket: config.Bucket,
            //     Region: config.Region,
            //     Key: '3' + filename,
            //     FilePath: filepath,
            }],
            SliceSize: 1024 * 1024,
            onProgress: function (info) {
                var percent = Math.floor(info.percent * 10000) / 100;
                var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
                console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
            },
            onFileFinish: function (err, data, options) {
                console.log(options.Key + ' 上传' + (err ? '失败' : '完成'));
            },
        }, function (err, data) {
            console.log(err || data);
            fs.unlinkSync(filepath);
        });
    });
}

function sliceCopyFile() {
    // 创建测试文件
    var sourceName = '3mb.zip';
    var Key = '3mb.copy.zip';

    var sourcePath = config.Bucket + '.cos.' + config.Region + '.myqcloud.com/'+ camSafeUrlEncode(sourceName).replace(/%2F/g, '/');

    cos.sliceCopyFile({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: Key,
        CopySource: sourcePath,
        CopySliceSize: 2 * 1024 * 1024, // 大于2M的文件用分片复制，小于则用单片复制
        onProgress: function (info) {
            var percent = Math.floor(info.percent * 10000) / 100;
            var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
            console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
        }
    },function (err,data) {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
    });
}

function putObjectTagging() {
    cos.putObjectTagging({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
        Tags: [
            {Key: 'k1', Value: 'v1'},
            {Key: 'k2', Value: 'v2'},
        ],
    }, function (err, data) {
        console.log(err || data);
    });
}

function getObjectTagging() {
    cos.getObjectTagging({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
    }, function (err, data) {
        console.log(err || data);
    });
}

function deleteObjectTagging() {
    cos.getObjectTagging({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: '1mb.zip',
    }, function (err, data) {
        console.log(err || data);
    });
}

/* 移动对象*/
function moveObject() {
    // COS 没有对象重命名或移动的接口，移动对象可以通过复制/删除对象实现
    var source = 'source.txt';
    var target = 'target.txt';
    var copySource = config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + camSafeUrlEncode(source).replace(/%2F/g, '/');
    cos.putObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: source,
        Body: 'hello!',
    }, function (err, data) {
        if (err) return logger.log(err);
        cos.putObjectCopy({
            Bucket: config.Bucket,
            Region: config.Region,
            Key: target,
            CopySource: copySource,
        }, function (err, data) {
            if (err) return logger.log(err);
            cos.deleteObject({
                Bucket: config.Bucket,
                Region: config.Region,
                Key: source,
            }, function (err, data) {
                logger.log(err || data);
            });
        });
    });
}

/* 上传本地文件夹 */
function uploadFolder() {
    var localFolder = '../test/';
    var remotePrefix = 'folder/';
    util.fastListFolder(localFolder, function (err, list) {
        if (err) return console.error(err);
        var files = list.map(function (file) {
            var filename = pathLib.relative(localFolder, file.path).replace(/\\/g, '/');
            if (filename && file.isDir && !filename.endsWith('/'))
                filename += '/';
            var Key = remotePrefix + filename;
            return {
                Bucket: config.Bucket,
                Region: config.Region,
                Key: Key,
                FilePath: file.path,
            };
        });
        cos.uploadFiles({
            files: files,
            SliceSize: 1024 * 1024,
            onProgress: function (info) {
                var percent = Math.floor(info.percent * 10000) / 100;
                var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
                console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
            },
            onFileFinish: function (err, data, options) {
                console.log(options.Key + ' 上传' + (err ? '失败' : '完成'));
            },
        }, function (err, data) {
            console.log(err || data);
        });
    });
}

/* 创建文件夹 */
function createFolder() {
    cos.getBucket({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: 'folder/', // 对象存储没有实际的文件夹，可以创建一个路径以 / 结尾的空对象表示，能在部分场景中满足文件夹使用需要
        Body: '',
    }, function(err, data) {
        console.log(err || data);
    });
}

/* 列出文件夹下的文件 */
function listFolder() {
    var _listFolder = function(params, callback) {
        var Contents = [];
        var CommonPrefixes = [];
        var marker;
        var next = function() {
            params.Marker = marker;
            cos.getBucket(params, function(err, data) {
                if (err) return callback(err);
                data && data.CommonPrefixes && data.CommonPrefixes.forEach(function (item) {
                    CommonPrefixes.push(item);
                });
                data && data.Contents && data.Contents.forEach(function (item) {
                    Contents.push(item);
                });
                if (data.IsTruncated === 'true') {
                    marker = data.NextMarker;
                    next();
                } else {
                    callback(null, {
                        CommonPrefixes: CommonPrefixes,
                        Contents: Contents,
                    });
                }
            });
        };
        next();
    };
    _listFolder({
        Bucket: config.Bucket,
        Region: config.Region,
        Delimiter: '/', // 如果按目录列出文件传入该分隔符，如果要深度列出文件不传改参数
        Prefix: 'folder/', // 要列出的目录前缀
    }, function (err, data) {
        console.log(err || data);
    });
}

/* 删除指定文件夹下的所有对象（删除存储桶里指定前缀所有对象） */
function deleteFolder() {
    var _deleteFolder = function(params, callback) {
        var deletedList = [];
        var errorList = [];
        var marker;
        var next = function() {
            params.Marker = marker;
            cos.getBucket(params, function(err, data) {
                if (err) return callback(err);
                var Objects = [];
                if (data && data.Contents && data.Contents.length) {
                    data.Contents.forEach(function (item) {
                        Objects.push({Key: item.Key});
                    });
                }
                var afterDeleted = function () {
                    if (data.IsTruncated === 'true') {
                        marker = data.NextMarker;
                        next();
                    } else {
                        callback(null, { Deleted: deletedList, Error: errorList });
                    }
                };
                if (Objects.length) {
                    cos.deleteMultipleObject({
                        Bucket: params.Bucket,
                        Region: params.Region,
                        Objects: Objects,
                    }, function (err, data) {
                        data.Deleted && data.Deleted.forEach(function (item) {
                            deletedList.push(item);
                        });
                        data.Error && data.Error.forEach(function (item) {
                            errorList.push(item);
                        });
                        afterDeleted();
                    });
                } else {
                    afterDeleted();
                }
            });
        };
        next();
    };
    _deleteFolder({
        Bucket: config.Bucket,
        Region: config.Region,
        Prefix: 'folder/', // 要列出的目录前缀
    }, function (err, data) {
        console.log(err || data);
    });
}

/* 分片下载文件 */
function downloadFile() {
    // 单文件分片并发下载
    var Key = 'windows_7_ultimate_x64.iso';
    cos.downloadFile({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: Key,
        FilePath: './' + Key,
        ChunkSize: 1024 * 1024 * 8, // 文件大于 8MB 用分片下载
        ParallelLimit: 5, // 分片并发数
        RetryTimes: 3, // 分片失败重试次数
        onTaskReady: function (taskId) {
            console.log(taskId);
        },
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        },
    }, function (err, data) {
        console.log(err || data);
    });

    // 取消下载任务
    // cos.emit('inner-kill-task', {TaskId: '123'});
}

// 追加上传
function appendObject() {
  cos.appendObject({
      Bucket: config.Bucket, // Bucket 格式：test-1250000000
      Region: config.Region,
      Key: 'append1.txt', /* 必须 */
      Body: '12345',
      Position: 0,
  },
  function(err, data) {
      console.log(err || data);
  })
}

// 继续追加上传
function appendObject_continue() {
  cos.headObject({
      Bucket: config.Bucket, // Bucket 格式：test-1250000000
      Region: config.Region,
      Key: 'append1.txt', /* 必须 */
  }, function(err, data) {
      if (err) return console.log(err);
      // 首先取到要追加的文件当前长度，即需要上送的Position
      var position = data.headers['content-length'];
      cos.appendObject({
          Bucket: config.Bucket, // Bucket 格式：test-1250000000
          Region: config.Region,
          Key: 'append1.txt', /* 必须 */
          Body: '66666',
          Position: position,
      },
      function(err, data) {
          // 也可以取到下一次上传的position继续追加上传
          var nextPosition = data.headers['x-cos-next-append-position'];
          console.log(err || data);
      })
  });
}



function request() {
    // 对云上数据进行图片处理
    var filename = 'example_photo.png';
    cos.request({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: filename,
        Method: 'POST',
        Action: 'image_process',
        Headers: {
            // 万象持久化接口，上传时持久化
            'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "example_photo_ci_result.png", "rule": "imageMogr2/thumbnail/200x/"}]}'
        },
    }, function (err, data) {
        console.log(err || data);
    });
}

/**
 * function CIExample1
 * @description 上传时使用图片处理
 */
function CIExample1(){
    var filename = 'example_photo.png'
    var filepath = path.resolve(__dirname, filename);
    cos.putObject({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Key: filename,
        Body: fs.readFileSync(filepath),
        Headers: {
            // 通过 imageMogr2 接口使用图片缩放功能：指定图片宽度为 100，宽度等比压缩
            'Pic-Operations':
            '{"is_pic_info": 1, "rules": [{"fileid": "example_photo_ci_result.png", "rule": "imageMogr2/thumbnail/200x/"}]}',
        },
        onTaskReady: function (tid) {
            TaskId = tid;
        },
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        },
    }, function (err, data) {
        console.log(err || data);
    });
}

/**
 * function CIExample2
 * @description 对云上数据进行图片处理
 */
function CIExample2(){
    var filename = 'example_photo.png';
    cos.request({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: filename,
        Method: 'POST',
        Action: 'image_process',
        Headers: {
            // 通过 imageMogr2 接口使用图片缩放功能：指定图片宽度为 200，宽度等比压缩
            'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "example_photo_ci_result.png", "rule": "imageMogr2/thumbnail/200x/"}]}'
        },
    }, function (err, data) {
        console.log(err || data);
    });
}

/**
 * function CIExample3
 * @description 下载时使用图片处理
 */
function CIExample3(){
    var filepath = path.resolve(__dirname, 'example_photo_ci_result.png');
    cos.getObject({
            Bucket: config.Bucket,
            Region: config.Region,
            Key: 'example_photo.png',
            QueryString: 'imageMogr2/thumbnail/200x/',
        },
        function (err, data) {
            if(data){
              fs.writeFileSync(filepath, data.Body);
            } else {
              console.log(err);
            }
        },
    );
}

/**
 * function CIExample4
 * @description 生成带图片处理参数的签名 URL
 */
function CIExample4(){

    // 生成带图片处理参数的文件签名URL，过期时间设置为 30 分钟。
    cos.getObjectUrl({
            Bucket: config.Bucket,
            Region: config.Region,
            Key: 'photo.png',
            QueryString: 'imageMogr2/thumbnail/200x/',
            Expires: 1800,
            Sign: true,
        },
        function (err, data) {
            console.log(err || data);
        },
    );

    // 生成带图片处理参数的文件URL，不带签名。
    cos.getObjectUrl({
            Bucket: config.Bucket,
            Region: config.Region,
            Key: 'photo.png',
            QueryString: 'imageMogr2/thumbnail/200x/',
            Sign: false,
        },
        function (err, data) {
            console.log(err || data);
        },
    );
}


/**
 * 查询已经开通数据万象功能的存储桶
 */
function DescribeCIBuckets() {
    var host = 'ci.' + config.Region + '.myqcloud.com';
    var url = 'https://' + host + '/mediabucket';
    cos.request({
        Bucket: config.Bucket,
        Region: config.Region,
        Method: 'GET',
        Key: 'mediabucket', /** 固定值，必须 */
        Url: url,
        Query: {
            pageNumber: '1', /** 第几页，非必须 */
            pageSize: '10', /** 每页个数，非必须 */
            // regions: 'ap-chengdu', /** 地域信息，例如'ap-beijing'，支持多个值用逗号分隔如'ap-shanghai,ap-beijing'，非必须 */
            // bucketNames: 'test-1250000000', /** 存储桶名称，精确搜索，例如'test-1250000000'，支持多个值用逗号分隔如'test1-1250000000,test2-1250000000'，非必须 */
            // bucketName: 'test', /** 存储桶名称前缀，前缀搜索，例如'test'，支持多个值用逗号分隔如'test1,test2'，非必须 */
        }
    },
    function(err, data){
        // var CIStatus = data.CIStatus;
        console.log(err || data);
    });
}


/**
* 获取媒体文件信息
*/
function GetMediaInfo() {
    cos.request({
      Bucket: config.Bucket,
      Region: config.Region,
      Method: 'GET',
      Key: 'test.mp4',
      Query: {
          'ci-process': 'videoinfo' /** 固定值，必须 */
      }
    },
    function (err, data) {
        console.log(err || data);
    });
}

/**
 * 获取媒体文件某个时间的截图
 */
function GetSnapshot() {
    cos.request({
        Bucket: config.Bucket,
        Region: config.Region,
        Method: 'GET',
        Key: 'test.mp4',
        Query: {
            'ci-process': 'snapshot', /** 固定值，必须 */
            time: 1, /** 截图的时间点，单位为秒，必须 */
            // width: 0, /** 截图的宽，非必须 */
            // height: 0, /** 截图的高，非必须 */
            // format: 'jpg', /** 截图的格式，支持 jpg 和 png，默认 jpg，非必须 */
            // rotate: 'auto', /** 图片旋转方式，默认为'auto'，非必须 */
            // mode: 'exactframe', /** 截帧方式，默认为'exactframe'，非必须 */
        },
        RawBody: true,
    },
    function (err, data) {
      // var Body = data.Body;
      console.log(err || data);
  });
}


/**
 * 对多种文件类型生成图片格式或html格式预览
 */
function GetDocProcess() {
    cos.request({
        Bucket: config.Bucket,  // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'test.pptx',
        Query: {
            'ci-process': 'doc-preview',
            'page': '1',
            'dstType': 'jpg',
            'ImageParams': 'imageMogr2/thumbnail/!50p|watermark/2/text/5pWw5o2u5LiH6LGh/fill/I0ZGRkZGRg==/fontsize/30/dx/20/dy/20'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 查询文档转码队列
 */
function DescribeDocProcessQueues() {
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/docqueue'
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'docqueue',
        Url: url,
        Query: {
            state: 'Active'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 更新文档转码队列
 */
function UpdateDocProcessQueue() {
    let queueId = 'p31299c0b3f4742dda2fc1be3ea40xxxx'   // 需要更新的队列ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/docqueue/' + queueId;
    let body = {        // 填上队列修改参数
        Request: {
            Name: '1',
            QueueID: queueId,
            State: 'Active',
            NotifyConfig: {
                Url: 'http://your.callkback.address/index.php',
                Type: 'Url',
                State: 'On',
                Event: 'TaskFinish'
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'PUT',
        Key: 'docqueue/' + queueId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 创建文档转码任务
 */
function CreateDocProcessJobs() {
    let queueId = 'p31299c0b3f4742dda2fc1be3ea40xxxx'   // 队列ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/doc_jobs';
    let body = {        // 填上任务参数
        Request: {
            Tag: 'DocProcess',
            Input: {
                Object: 'test.pptx'
            },
            QueueId: queueId,
            Operation: {
                DocProcess: {
                    StartPage: 3,
                    EndPage: 4,
                    TgtType: 'png'
                },
                Output: {
                    Region: config.Region,
                    Bucket: config.Bucket,
                    Object: 'doc_${Page}.png'
                }
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'POST',
        Key: 'doc_jobs',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 查询文档转码任务
 */
function DescribeDocProcessJob() {
    let jobId = 'd2c6c620a415811ecb31b51515222xxxx'
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/doc_jobs/' + jobId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'doc_jobs/' + jobId,
        Url: url
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 文档转码任务列表
 */
function DescribeDocProcessJobs() {
    let queueId = 'p31299c0b3f4742dda2fc1be3ea40xxxx'
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/doc_jobs';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'doc_jobs',
        Url: url,
        Query: {
            tag: 'DocProcess',
            queueId: queueId,
            states: 'Failed'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}



/**
 * 查询已经开通媒体处理功能的存储桶
 */
function DescribeMediaBuckets() {
    let host = 'ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/mediabucket'
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'mediabucket',
        Url: url,
        Query: {
            pageNumber: '1',
            pageSize: '10'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 查询存储桶的媒体处理队列
 */
function DescribeMediaQueues() {
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/queue'
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'queue',
        Url: url
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 更新媒体处理队列
 */
function UpdateMediaQueue() {
    let queueId = 'p5ad1499214024af2bfaa4401d529xxxx'   // 需要更新的队列ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/queue/' + queueId;
    let body = {        // 填上队列修改参数
        Request: {
            Name: '1',
            QueueID: queueId,
            State: 'Active',
            NotifyConfig: {
                Url: 'http://your.callkback.address/index.php',
                Type: 'Url',
                Event: 'TaskFinish',
                State: 'On'
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'PUT',
        Key: 'queue/' + queueId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 创建媒体处理的各种模版（以截帧模版为例）
 */
function CreateMediaTemplate() {
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/template';
    let body = {        // 填上模板参数
        Request: {
            Tag: 'Snapshot',
            Name: 'test-template',
            Snapshot: {
                Mode: 'Interval',
                Start: '1',
                TimeInterval: '5',
                Count: '3',
                Width: '1280'
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'POST',
        Key: 'template',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 删除模版
 */
function DeleteMediaTemplate() {
    let templateId = 't1b11b39d3a91949d6804c08399186xxxx';      // 待删除的模版ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/template/' + templateId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'DELETE',
        Key: 'template/' + templateId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 查看模版详情
 */
function DescribeMediaTemplates() {
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/template';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'template',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Query: {
            tag: 'Snapshot',
            name: 'test'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 更新模版信息
 */
function UpdateMediaTemplate() {
    let templateId = 't12cf1cde8d8a845eebc0a5c6047bfxxxx'   // 需要更新的模版ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/template/' + templateId;
    let body = {        // 填上模版修改参数
        Request: {
            Tag: 'Snapshot',
            Name: 'test-new',
            Snapshot: {
                Mode: 'Average',
                Start: '0',
                Count: '3',
                Height: '1280'
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'PUT',
        Key: 'template/' + templateId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 提交媒体处理任务
 */
function CreateMediaJobs() {
    let templateId = 't12cf1cde8d8a845eebc0a5c6047bfxxxx'   // 模版ID
    let queueId = 'p5ad1499214024af2bfaa4401d529xxxx'   // 队列ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/jobs';
    let body = {        // 填上任务参数
        Request: {
            Tag: 'Snapshot',
            Input: {
                Object: 'test-input.mp4'
            },
            QueueId: queueId,
            Operation: {
                TemplateId: templateId,
                Output: {
                    Region: config.Region,
                    Bucket: config.Bucket,
                    Object: 'test-output${Number}'
                }
                },
            CallBack: 'http://your.task.callkback.address/index.php'
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'POST',
        Key: 'jobs',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 取消媒体处理任务
 */
function CancelMediaJob() {
    let jobId = 'j14596fda409c11eca160977fff35xxxx';      // 待取消的任务ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/jobs/' + jobId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'PUT',
        Key: 'jobs/' + jobId,
        Url: url
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 查看媒体处理任务
 */
function DescribeMediaJob() {
    let jobId = 'j14596fda409c11eca160977fff35xxxx';      // 任务ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/jobs/' + jobId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'jobs/' + jobId,
        Url: url
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 媒体处理任务列表
 */
function DescribeMediaJobs() {
    let queueId = 'p5ad1499214024af2bfaa4401d529xxxx'   // 队列ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/jobs';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'jobs',
        Url: url,
        Query: {
            queueId: queueId,
            tag: 'Snapshot',
            states: 'Failed'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 创建工作流
 */
function CreateWorkflow() {
    let queueId = 'p5ad1499214024af2bfaa4401d529xxxx';
    let callbackUrl = 'http://your.callback.com/index.php';
    let snapshotTemplate = 't0a60a2bc71a4b40c7b3d7f7e8a277xxxx';
    let transcodeTemplate = 't04e1ab86554984f1aa17c062fbf6cxxxx';
    let animationTemplate = 't0341b0ab2b8a340ff826e9cb4f3a7xxxx';
    let concatTemplate = 't19e96c43b0c05444f9b2facc9dcf5xxxx';
    let voiceSeparateTemplate = 't1c101e2bc074c4506837714edc99axxxx';
    let videoMontageTemplate = 't1ec0b3871d5e340da84536688b810xxxx';
    let watermarkTemplate = 't1ea62f7810d0142c195313330bdd4xxxx';
    let videoProcessTemplate = 't1d945b6de362f4d4db9bd8659bc5exxxx';
    let superResolutionTemplate = 't1d9d5ae4450824427bccc495ed0b0xxxx';
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflow';
    let body = {
        Request: {
            MediaWorkflow: {
                Name: 'demo',
                State: 'Active',    // 创建并开启工作流
                Topology: {
                    Dependencies: {
                        Start: 'Snapshot_1581665960536,Transcode_1581665960537,Animation_1581665960538,Concat_1581665960539,VoiceSeparate_1581665960551,VideoMontage_1581665960551,SDRtoHDR_1581665960553,VideoProcess_1581665960554,SuperResolution_1581665960583,Segment_1581665960667',
                        'Snapshot_1581665960536': 'End',
                        'Transcode_1581665960537': 'End',
                        'Animation_1581665960538': 'End',
                        'Concat_1581665960539': 'End',
                        'VideoMontage_1581665960551': 'End',
                        'SDRtoHDR_1581665960553': 'End',
                        'VideoProcess_1581665960554': 'End',
                        'SuperResolution_1581665960583': 'End',
                        'Segment_1581665960667': 'End',
                        'VoiceSeparate_1581665960551': 'End'
                    },
                    Nodes: {
                        Start: {
                            Type: 'Start',
                            Input: {
                                QueueId: queueId,
                                ObjectPrefix: 'test-',
                                NotifyConfig: {
                                    Type: 'Url',
                                    Url:callbackUrl,
                                    Event: 'TaskFinish,WorkflowFinish'
                                },
                                ExtFilter: {
                                    State: 'On',
                                    Audio: 'true',
                                    Custom: 'true',
                                    CustomExts: 'mp4/mp3',
                                    AllFile: 'false'
                                }
                            }
                        },
                        'Snapshot_1581665960536': {
                            Type: 'Snapshot',
                            Operation: {
                                TemplateId: snapshotTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/snapshot-${number}.${Ext}',
                                    SpriteObject: 'worlflow-test/${RunId}/snapshot-sprite-${number}.jpg'
                                }
                            }
                        },
                        'Transcode_1581665960537': {
                            Type: 'Transcode',
                            Operation: {
                                TemplateId: transcodeTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/trans.mp4'
                                }
                            }
                        },
                        'Animation_1581665960538': {
                            Type: 'Animation',
                            Operation: {
                                TemplateId: animationTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/bcd.gif'
                                }
                            }
                        },
                        'Concat_1581665960539': {
                            Type: 'Concat',
                            Operation: {
                                TemplateId: concatTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/abc.${ext}'
                                }
                            }
                        },
                        'VoiceSeparate_1581665960551': {
                            Type: 'VoiceSeparate',
                            Operation: {
                                TemplateId: voiceSeparateTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/background.mp3',
                                    AuObject: 'worlflow-test/${RunId}/audio.mp3'
                                }
                            }
                        },
                        'VideoMontage_1581665960551': {
                            Type: 'VideoMontage',
                            Operation: {
                                TemplateId: videoMontageTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/montage.mp4'
                                }
                            }
                        },
                        'SDRtoHDR_1581665960553': {
                            Type: 'SDRtoHDR',
                            Operation: {
                                SDRtoHDR: {
                                    HdrMode: 'HLG'
                                },
                                TranscodeTemplateId: transcodeTemplate,
                                WatermarkTemplateId: watermarkTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/SDRtoHDR.mp4'
                                }
                            }
                        },
                        'VideoProcess_1581665960554': {
                            Type: 'VideoProcess',
                            Operation: {
                                TemplateId: videoProcessTemplate,
                                TranscodeTemplateId: transcodeTemplate,
                                WatermarkTemplateId: watermarkTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/videoProcess.mp4'
                                }
                            }
                        },
                        'SuperResolution_1581665960583': {
                            Type: 'SuperResolution',
                            Operation: {
                                TemplateId: superResolutionTemplate,
                                TranscodeTemplateId: transcodeTemplate,
                                WatermarkTemplateId: watermarkTemplate,
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/SuperResolution.mkv'
                                }
                            }
                        },
                        'Segment_1581665960667': {
                            Type: 'Segment',
                            Operation: {
                                Segment: {
                                    Format: 'mp4',
                                    Duration: '5'
                                },
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/segment-trans${Number}'
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'POST',
        Key: 'workflow',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 删除工作流
 */
function DeleteWorkflow() {
    let workflowId = 'wad8a9e26e1864a3793446fd9a686xxxx';      // 待删除的工作流ID
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflow/' + workflowId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'DELETE',
        Key: 'workflow/' + workflowId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 工作流列表
 */
function DescribeWorkflow() {
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflow';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'workflow',
        Url: url,
        Query: {
            ids: ''
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 执行实例详情
 */
function DescribeWorkflowExecution() {
    let runId = 'ieed8aec4413a11ec913f52540003xxxx';
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflowexecution/' + runId;
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'workflowexecution/' + runId,
        Url: url
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 执行实例列表
 */
function DescribeWorkflowExecutions() {
    let workflowId = 'w093b29cfef824bd0922743a6f0afxxxx';
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflowexecution';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'workflowexecution',
        Url: url,
        Query: {
            workflowId: workflowId,
            size: '3',
            states: 'Failed'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 更新工作流配置
 */
function UpdateWorkflow() {
    let workflowId = 'w14404e66c27b4e0aafae6bc96acfxxxx';
    let queueId = 'p5ad1499214024af2bfaa4401d529xxxx';
    let callbackUrl = 'http://your.callback.com/index.php';
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/workflow/' + workflowId;
    let body = {        // 填上模版修改参数
        Request: {
            MediaWorkflow: {
                Name: 'test1',
                State: 'Active',    // 创建并开启工作流
                Topology: {
                    Dependencies: {
                        Start: 'SmartCover_1581665960539',
                        'SmartCover_1581665960539': 'End'
                    },
                    Nodes: {
                        Start: {
                            Type: 'Start',
                            Input: {
                                QueueId: queueId,
                                ObjectPrefix: 'test/',
                                NotifyConfig: {
                                    Type: 'Url',
                                    Url: callbackUrl,
                                    Event: 'TaskFinish,WorkflowFinish'
                                },
                                ExtFilter: {
                                    State: 'On',
                                    Video: 'true',
                                    Custom: 'true',
                                    CustomExts: 'mp4/mp3',
                                    AllFile: 'false'
                                }
                            }
                        },
                        'SmartCover_1581665960539': {
                            Type: 'SmartCover',
                            Operation: {
                                Output: {
                                    Region: config.Region,
                                    Bucket: config.Bucket,
                                    Object: 'worlflow-test/${RunId}/cover-${Number}.jpg'
                                },
                                SmartCover: {
                                    Format: 'png',
                                    Width: '128',
                                    Height: '128',
                                    Count: '3',
                                    DeleteDuplicates: 'false'
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'PUT',
        Key: 'workflow/' + workflowId,
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml(body)
    }, function (err, data) {
        console.log(err || data);
    });
}


/**
 * 触发工作流
 */
function TriggerWorkflow() {
    let workflowId = 'w093b29cfef824bd0922743a6f0afxxxx';
    let host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
    let url = 'https://' + host + '/triggerworkflow';
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'POST',
        Key: 'triggerworkflow',
        Url: url,
        Headers: {
            'content-type': 'application/xml'
        },
        Query: {
            workflowId: workflowId,
            object: 'test.mp4'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

// 同步审核存储桶里的图片对象
function SyncAuditImageObject() {
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Key: 'audit/1.jpg',
        Method: 'GET',
        Query: {
            'ci-process': 'sensitive-content-recognition',
            // 'detect-url': '<url>',
            // 'biz-type': '<type>', // 审核策略 id
            // 'detect-type': 'porn,ads', // 审核类型 porn,ads
            // 'interval': 5, // gif截取间隔帧数
            // 'max-frames': 5, // gif最大截帧数
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

/**
 * 获取私有 M3U8 ts 资源的下载授权
 */
function GetPrivateM3U8() {
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Key: 'test.m3u8',
        Query: {
            'ci-process': 'pm3u8',
            expires: '3600'
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

// 同步审核任意图片 Url
function SyncAuditImageUrl() {
    cos.request({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Method: 'GET',
        Query: {
            'ci-process': 'sensitive-content-recognition',
            'detect-url': 'https://ftp.bmp.ovh/imgs/2021/09/ee4e63607465ed8d.jpg',
            // 'biz-type': '<type>', // 审核策略 id
            // 'detect-type': 'porn,ads', // 审核类型 porn,ads
            // 'interval': 5, // gif截取间隔帧数
            // 'max-frames': 5, // gif最大截帧数
        }
    }, function (err, data) {
        console.log(err || data);
    });
}

// 批量同步审核任意图片 Url
function SyncAuditImageUrls() {
    cos.request({
        Url: `https://${config.Bucket}.ci.${config.Region}.myqcloud.com/image/auditing`,
        Method: 'POST',
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml({
            Request: {
                Input: [{
                    Object: 'audit/1.jpg',
                    // DataId: '1', // 审核序号
                    // Url: '<url>',
                    // Interval: 5,
                    // MaxFrames: 5,
                }, {
                    Object: 'audit/2.jpg',
                }],
                Conf: {
                    DetectType: 'Porn,Ads',
                    // Callback: '<url>', // 回调地址
                    // BizType: '', // 审核策略
                },
            },
        }),
    }, function (err, data) {
        console.log(err || data.Response.JobsDetail);
    });
}

// 审核文本内容
function SyncAuditTextContent() {
    cos.request({
        Url: `https://${config.Bucket}.ci.${config.Region}.myqcloud.com/text/auditing`,
        Method: 'POST',
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml({
            Request: {
                Input: {
                    Content: Buffer.from('高潮').toString('base64'),
                },
                Conf: {
                    DetectType: 'Porn,Terrorism,Politics,Ads,Illegal,Abuse',
                    // Callback: '<url>', // 回调地址
                    // BizType: '', // 审核策略
                },
            },
        }),
    }, function (err, data) {
        console.log(err || data.Response.JobsDetail);
    });
}

// 提交图片审核任务
function CreateAuditJob() {
    var objectKey = 'audit/1.jpg';
    var objectType = 'image'; // image/audio/video/text/document
    cos.request({
        Url: `https://${config.Bucket}.ci.${config.Region}.myqcloud.com/${objectType}/auditing`,
        Method: 'POST',
        Headers: {
            'content-type': 'application/xml'
        },
        Body: json2xml({
            Request: {
                Input: {
                    Object: objectKey,
                },
                Conf: {
                    DetectType: 'Porn,Ads',
                    // Callback: '<url>', // 回调地址
                    // BizType: '', // 审核策略
                },
            },
        }),
    }, function (err, data) {
        console.log(err || data.Response.JobsDetail);
    });
}

// 查询审核任务结果
function DescribeAuditJob() {
    var jobId = 'st3bb560af647911ec919652540024deb5';
    cos.request({
        Url: `https://${config.Bucket}.ci.${config.Region}.myqcloud.com/text/auditing/${jobId}`,
    }, function (err, data) {
        console.log(err || data.Response.JobsDetail);
    });
}

// 存储桶操作
// getService();
// getAuth();
// getV4Auth();
// getObjectUrl();
// putBucket();
// getBucket();
// headBucket();
// putBucketAcl();
// getBucketAcl();
// putBucketCors();
// getBucketCors();
// deleteBucketCors();
// putBucketTagging();
// getBucketTagging();
// deleteBucketTagging();
// putBucketPolicy();
// getBucketPolicy();
// deleteBucketPolicy();
// getBucketLocation();
// getBucketLifecycle();
// putBucketLifecycle();
// deleteBucketLifecycle();
// putBucketVersioning();
// getBucketVersioning();
// listObjectVersions();
// getBucketReplication();
// putBucketReplication();
// deleteBucketReplication();
// putBucketWebsite();
// getBucketWebsite();
// deleteBucketWebsite();
// putBucketReferer();
// getBucketReferer();
// putBucketDomain();
// getBucketDomain();
// deleteBucketDomain();
// putBucketOrigin();
// getBucketOrigin();
// deleteBucketOrigin();
// putBucketLogging();
// getBucketLogging();
// deleteBucketLogging();
// putBucketInventory();
// getBucketInventory();
// deleteBucketInventory();
// listBucketInventory();
// putBucketAccelerate();
// getBucketAccelerate();
// putBucketEncryption();
// getBucketEncryption();
// deleteBucketEncryption();
// deleteBucket();


// 对象操作
// putObjectCopy();
// getObjectStream();
// getObject();
// headObject();
// putObjectAcl();
// getObjectAcl();
// deleteObject();
// deleteMultipleObject();
// restoreObject();
// abortUploadTask();
// selectObjectContentStream();
// selectObjectContent();
// sliceUploadFile();
// uploadFile();
// uploadFiles();
// cancelTask();
// pauseTask();
// restartTask();
// putObject();
// putObject_base64();
// sliceCopyFile();
// putObjectTagging();
// getObjectTagging();
// deleteObjectTagging();
// appendObject();
// appendObject_continue();

// 其他示例
// moveObject();
// uploadFolder();
// createFolder();
// listFolder();
// deleteFolder();
// downloadFile();
// request();

// 数据处理
// DescribeCIBuckets();
// GetMediaInfo();
// GetSnapshot();


//DescribeDocProcessBuckets();
//GetDocProcess()
//DescribeDocProcessQueues()
//UpdateDocProcessQueue()
//CreateDocProcessJobs();
//DescribeDocProcessJob();
//DescribeDocProcessJobs();
//DescribeMediaBuckets();
//DescribeMediaQueues();
//UpdateMediaQueue();
//CreateMediaTemplate();
//DeleteMediaTemplate();
//DescribeMediaTemplates()
//UpdateMediaTemplate()
//CreateMediaJobs();
//CancelMediaJob();
//DescribeMediaJob();
//DescribeMediaJobs();

//CreateWorkflow();
//DeleteWorkflow();
//DescribeWorkflow();
//DescribeWorkflowExecution();
//DescribeWorkflowExecutions();
//UpdateWorkflow();
//TriggerWorkflow();
//GetPrivateM3U8();

// SyncAuditImageObject()
// SyncAuditImageUrl()
// SyncAuditImageUrls()
// SyncAuditTextContent()
// CreateAuditJob()
// DescribeAuditJob()
