audios.js 11.9 KB
import * as all from "./config";
require('./../css/test.css')
// Init Vue
const Audio = {
  data() {
    return {
      testLabel: '唱\xa0\xa0\xa0\xa0\xa0\xa0\xa0歌',
      form: {
        channelId: null,
        songName: null,
        singer: null,
        lyricist: null,
        songwriter: null,
        redact: null,
        mixing: null,
        lyric: null,
        phone: null,
        name: null,
        audioId: null,
        audioFile: null,
      },
      labels: all.formLabels,
      rules: {
        songName: [
          {
            required: true,
            trigger: "change",
            message: "请填写歌曲名字",
          },
        ],
        name: [
          { required: true, trigger: "change", message: "请填写联系人姓名" },
        ],
        phone: [
          {
            required: true,
            trigger: "change",
            message: "请填写格式正确的手机号码",
            validator: all.validatePhone,
          },
        ],
        audioFile: [
          { required: true, trigger: "change", message: "请上传音频" },
        ],
        channelId: [
          { required: true, trigger: "change", message: "请选择作品类型" },
        ],
        audioId: [
          {
            required: true,
            trigger: "change",
            message: "请上传音频文件以获取音频ID",
          },
        ],
      },

      uploadUrl: "",
      fileList: [],
      token: "",
      btnDisabled: false,
      submitDisabled: false,
      msgText:
        "只能上传一个mp3/flac/wav/ogg格式的音频文件,且不超过500mb。上传过程中请勿刷新页面。",
      percent: 0,
      curFile: "",
    };
  },
  methods: {
    // 作品类型为【词】的时候可以不上传文件
    handleChange(data) {
      if (data == 1279) {
        this.rules.audioFile[0].required = false;
        this.rules.audioId[0].required = false;
      } else {
        this.rules.audioFile[0].required = true;
        this.rules.audioId[0].required = true;
      }
    },
    // 文件数量超上限响应
    exceed(e, d) {
      this.$message.error("只能上传一个文件");
    },
    // 表单重置按钮响应
    reset() {
      for (let i in this.form) {
        this.form[i] = null;
      }
      this.percent = 0;
      this.btnDisabled = false;
      this.submitDisabled = false;
    },
    // 文件移除响应,暂未启用
    handleRemove(file, list) {
      if (this.percent < 100) {
        this.$message({
          type: "error",
          duration: 5000,
          message: "上传中的文件不可被删除",
        });
        return false;
      } else {
        this.form.audioId = null;
        this.percent = 0;
      }
    },
    // 校验Md5
    initMd5(fileObj) {
      return new Promise((resolve, reject) => {
        const fileName = fileObj.name.split(".")[0];
        const fileType = fileObj.name.split(".")[1];
        const fileSize = fileObj.size;
        const fileModifyDate = fileObj.lastModifiedDate;
        const md5Str = all
          .initVideoMd5(
            [fileType, fileSize, fileModifyDate || fileName].join("_")
          )
          .toLowerCase();
        if (md5Str) {
          resolve(md5Str);
        } else {
          reject("校验失败");
        }
      });
    },
    // 确认提交按钮响应,上传视频到七牛
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitDisabled = true;
          this.btnDisabled = true;
          if (this.form.channelId == 1279) {
            this.postCms();
          } else {
            const fileName = this.form.audioFile.raw.name.split(".");
            fileName.splice(fileName.length - 1, 1);
            this.curFile = this.form.audioFile.name;
            this.form.audioId = null;
            const that = this;
            const fileBaseObj = {
              videoName: fileName.join("."),
              md5: null,
            };
            const fileSaveObj = {
              videoId: null,

              multipleCategory: 100005,
              tag: "test",
              ts: this.getTs(),
              timestamp: this.getTimeStamp(),
              masterId: all.secretUrls.masterIdMaster,
              // masterId: all.secretUrls.masterIdDev,
            };
            const fileInitObj = {
              gfmt: this.form.audioFile.raw.name.split(".").reverse().shift(),
              fileSize: this.form.audioFile.raw.size,
              ts: this.getTs(),
              timestamp: this.getTimeStamp(),
              multipleCategory: 100005,
              // masterId: all.secretUrls.masterIdDev,
              masterId: all.secretUrls.masterIdMaster,
            };
            const fileWholeObj = {
              file: this.form.audioFile.raw,
              uploadStatus: "ready",
              proCount: 0,
              fileKey: null,
              observable: null,
              subscription: null,
            };

            const observer = {
              next(res) {
                if (res.total.percent >= 99) {
                  that.percent = 99;
                } else {
                  that.percent = Math.ceil(res.total.percent);
                }
              },
              error(err) {
                console.log(err);
              },
              complete(res) {
                let apiDone = all.secretUrls.base + all.secretUrls.finish;
                let apiStringSignDone = all.signFunction(
                  apiDone,
                  that.getParamsList({
                    hash: res.hash,
                    key: res.key,
                    vid: fileSaveObj.videoId,
                    timestamp: that.getTimeStamp(),
                  })
                );
                all
                  .request({
                    url: apiDone,
                    method: "get",
                    params: all.parseQueryString(apiStringSignDone),
                  })
                  .then((res) => {
                    let apiComplete = all.secretUrls.base + all.secretUrls.callback;
                    let apiStringSignComplete = all.signFunction(
                      apiComplete,
                      that.getParamsList({ ...fileBaseObj, ...fileSaveObj, ...{timestamp: that.getTimeStamp()} })
                    );
                    return all.request({
                      url: apiComplete,
                      method: 'get',
                      params: all.parseQueryString(apiStringSignComplete),
                    })
                  }).then(data => {
                    that.form.audioId = data.data.data.obj;
                    that.percent = 100;
                    that.postCms()
                  })
              },
            };

            Promise.all([
              all.validateVideoSize(fileInitObj.fileSize),
              all.validateVideoFormat(fileInitObj.gfmt),
              all.validateNameLength(fileBaseObj.videoName),
            ])
              .then((check) => {
                return this.getToken();
              })
              .then((d) => {
                if (d && d.data && typeof d.data == 'string') {
                  this.token = d.data;
                } 
                return this.initMd5(this.form.audioFile.raw);
              })
              .then((n) => {
                if (!this.token) {
                  this.$message({
                    type: "error",
                    message: "鉴权失败",
                    duration: 5000,
                  });
                  return false;
                }
                fileBaseObj.md5 = n;
                let apiInit = all.secretUrls.base + all.secretUrls.init;
                let apiStringSignInit = all.signFunction(
                  apiInit,
                  this.getParamsList({ ...fileBaseObj, ...fileInitObj })
                );
                return all.request({
                  url: all.secretUrls.base + all.secretUrls.init,
                  method: "get",
                  params: all.parseQueryString(apiStringSignInit),
                });
              })
              .then((res) => {
                if (res && res.data && res.data.data && res.data.data.code == 0) {
                  fileSaveObj.videoId = res.data.data.obj.vid;
                  fileWholeObj.fileKey = res.data.data.obj.originPath;
                  all.putExtra.params["x:name"] = fileWholeObj.fileKey;
                  fileWholeObj.observable = qiniu.upload(
                    this.form.audioFile.raw,
                    fileWholeObj.fileKey,
                    this.token,
                    all.putExtra,
                    all.cdnConfig
                  );
                  fileWholeObj.subscription =
                    fileWholeObj.observable.subscribe(observer);
                } else {
                  this.$message({
                    type: "error",
                    duration: 0,
                    message: "未知错误,请联系管理员。",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: error,
                  duration: 0,
                });
              });
          }
        } else {
          this.$message.error("请检查表单内容");
          this.submitDisabled = false;
          this.btnDisabled = false;
          return false;
        }
      });
    },
    // 对象参数转数组格式
    getParamsList(params) {
      let list = [];
      for (let i in params) {
        if(i == 'hash' || i == 'key' || i == 'x:name') {
          list.push(`${i}=${encodeURI(params[i])}`)
        } else {
          list.push(`${i}=${params[i]}`);
        }
      }
      return list;
    },
    // 获取时间戳
    getTimeStamp() {
      return Math.round(new Date().getTime() / 1000);
    },
    // 获取时间戳加四位随机数
    getTs() {
      return (
        this.getTimeStamp().toString() +
        Math.floor(Math.random() * 10000).toString()
      );
    },
    // 获取认证token
    getToken() {
      let api = all.secretUrls.base + all.secretUrls.auth;
      let apiStringSign = all.signFunction(api, [
        "ts=" + this.getTs(),
        "timestamp=" + this.getTimeStamp(),
      ]);
      return all.request({
        url: all.secretUrls.base + all.secretUrls.auth,
        method: "get",
        params: all.parseQueryString(apiStringSign),
      });
    },
    // cms接口提交videoId和表单内容
    postCms() {
      this.form.lyric = this.form.lyric ? this.form.lyric.trim() : "";
      all
        .request({
          url: "http://cmstest.cnlive.com:8768/contentApi/audioSave",
          method: "post",
          params: this.form,
          withCredentials: true,
          headers: {
            "X-Requested-With": "XMLHttpRequest",
            "Access-Control-Allow-Origin": "*",
            "content-type": "application/json;charset=UTF-8",
          },
        })
        .then((res) => {
          if (res.data) {
            setTimeout(() => {
              // console.log("jump");
              window.location.replace("./success.html");
            }, 1000);
          } else {
            setTimeout(() => {
              // console.log("jump");
              window.location.replace("./failed.html");
            }, 1000);
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => {
          this.btnDisabled = false;
          this.submitDisabled = false;
        });
    },
    // 获取txt文件内容,暂未启用
    getTxt(e) {
      this.form.txtFile = e.raw;
      let file = e.raw;
      (reader = new FileReader()), (that = this);
      reader.onload = function (evt) {
        var data = evt.target.result;
        console.log(data);
        console.log(String.fromCharCode.apply(null, new Uint16Array(data)));
      };
      reader.readAsArrayBuffer(file);
    },
    // 选择上传文件
    getMp3(file) {
      this.form.audioFile = file;
    },
  },
};

Vue.createApp(Audio).use(ElementPlus).mount("#audioPage");