七牛第三方资源抓取以及私有资源下载

最近项目中有这么一个需求,因为咱们用的腾讯直播软件(TClass,腾讯云互动课堂)老师录制的视频存储在腾讯那边,可是腾讯保存视频只有三天有效期,所以,咱们须要抓取视频到咱们的七牛云上面,要求低频存储,要求存储到私有空间。node

同步抓取第三方资源

const qiniu = require('qiniu');
const accessKey = 'your accessKey';
const secretKey = 'your secretKey';
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z0;

let bucketManager = new qiniu.rs.BucketManager(mac, config);

let resUrl = 'https://blog.adityasui.com/_nuxt/img/user.85831cd.jpg';
let bucket = 'cris-store';
let key = 'sync.png';
bucketManager.fetch(resUrl, bucket, key, function (err, respBody, respInfo) {
  if (err) {
    console.log(err);
  } else {
    if (respInfo.statusCode === 200) {
      console.log(respBody.key);
      console.log(respBody.hash);
      console.log(respBody.fsize);
      console.log(respBody.mimeType);
    } else {
      console.log(respInfo.statusCode);
      console.log(respBody);
    }
  }
});

第三方资源抓取json

异步抓取第三方资源

可是同步抓取第三方资源的方式不支持不能传递参数,所以不能知足咱们低频存储的需求,而异步抓取第三方的资源是支持传递参数的api

const qiniu = require('qiniu');

const accessKey = 'your accessKey';

const secretKey = 'your secretKey';

let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

let bucket = 'cris-store'; 

let resUrl = 'https://blog.adityasui.com/_nuxt/img/user.85831cd.jpg';

let key = 'async.png';

let fetchUrl = "http://api-z0.qiniu.com/sisyphus/fetch";

const reqBody = {
  url: resUrl,
  bucket,
  file_type: 1, // 0:标准存储(默认),1:低频存储,2:归档存储
  key,
};

const reqBodyStr = JSON.stringify(reqBody);

qiniu.rpc.post(fetchUrl, reqBodyStr, {
  Authorization: qiniu.util.generateAccessTokenV2(mac, fetchUrl, 'POST', 'application/json', reqBodyStr),
  'Content-Type': 'application/json',
},
  function (error, response, body) {
    try {
      if (error) throw error;
      console.log(body);
    } catch (e) {
      console.log(e);
    }
  }
);

其中低频存储只须要传递file_type为1就能够了。app

异步第三方资源抓取异步

真的很想吐槽一下七牛的文档,明明API都已经写好了,可是就是没有把API写到文档里async

私有资源下载

访问私有资源URL与公开资源URL相比只是增长了两个参数etoken,分别表示过时时间和下载凭证,由于七牛已经提供了生成下载凭证的例子,这里直接上代码post

const qiniu = require('qiniu');

const accessKey = 'your accessKey';
const secretKey = 'your secretKey';

let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

let config = new qiniu.conf.Config();

let bucketManager = new qiniu.rs.BucketManager(mac, config);
let privateBucketDomain = 'http://qagyyccko.bkt.clouddn.com';
let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过时 采用Unix时间戳,单位为秒
let privateDownloadUrl = bucketManager.privateDownloadUrl(privateBucketDomain, 'whq.mp4', deadline);

console.log('@privateDownloadUrl', privateDownloadUrl);

可是后来又遇到一个问题,就是明明设置有效期20秒后,发现过了20秒,资源仍是能够访问,因而Google了好久才发现,测试域名不能用于私有空间和自定义域名必须开启回源鉴权。按照官网配置便可。测试

私有空间的注意事项
私有资源下载
下载文件fetch

相关文章
相关标签/搜索