get-anti-theft-url.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const crypto = require('crypto');
  18. const { antiTheftKey, antiTheftExpires } = require('./config');
  19. /**
  20. * 获取云点播文件防盗链链接
  21. * 更多信息请访问 https://cloud.tencent.com/document/product/266/14047
  22. * @param {object} params - 参数包装对象
  23. * @param {string} params.mediaUrl - 云点播文件地址
  24. * @return {string} 云点播文件完整url(包含签名)
  25. */
  26. function getAntiTheftURL({ mediaUrl }) {
  27. // 配置校验
  28. if (!antiTheftKey) {
  29. throw new Error('请在云函数VOD模块中配置有效的antiTheftKey');
  30. }
  31. if (isNaN(antiTheftExpires) || antiTheftExpires <= 0) {
  32. throw new Error('请在云函数VOD模块中配置有效的antiTheftExpires');
  33. }
  34. // 生成包含签名的url
  35. const result = new RegExp('^https?://[^/]*(.*/)[^/]*$').exec(mediaUrl);
  36. if (!result) {
  37. throw new Error('无效的媒体文件Url');
  38. }
  39. const dir = result[1];
  40. const t = Math.floor(new Date().getTime() / 1000 + antiTheftExpires * 60).toString(16);
  41. const sign = crypto.createHash('md5').update(`${antiTheftKey}${dir}${t}`).digest('hex');
  42. return `${mediaUrl}?t=${t}&sign=${sign}`;
  43. }
  44. module.exports = getAntiTheftURL;