audio.js 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
import 'babel-polyfill'
import * as all from "./config";
import './../css/reui.css';
var Main = {
  data() {
    return {
      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,
        agree: []
      },
      labels: all.formLabels,
      rules: {
        songName: [
          {
            required: true,
            trigger: "change",
            message: "请填写歌曲名字",
          },
        ],
        name: [
          { required: true, trigger: "change", message: "请填写联系人姓名" },
        ],
        agree: [
          { 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",
          },
        ],
        singer: [
          { required: false, trigger: "change", message: "请输入歌手名字" },
        ],
        lyricist: [
          { required: false, trigger: "change", message: "请输入作词人名字" },
        ],
        songwriter: [
          { required: false, trigger: "change", message: "请输入作曲人名字" },
        ],
        lyric: [
          {
            required: false,
            trigger: "change",
            message: "请输入符合要求的歌词,至少20个字,最多不能超过2500个字",
            validator: all.validateLyric,
          },
        ],
      },

      uploadUrl: "",
      fileList: [],
      token: "",
      btnDisabled: false,
      submitDisabled: false,
      msgText:
        "只能上传一个mp3/flac/wav/ogg/mpg/wma/aac/acc/m4a格式的音频文件,且不超过500mb。上传过程中请勿刷新页面。",
      percent: 0,
      curFile: "",
      errorMsg: "",
      banAgree: false
    };
  },
  methods: {
    // 作品类型为【词】的时候可以不上传文件
    handleChange(data) {
      if (data == 1279) {
        // 优秀作词榜
        this.rules.audioFile[0].required = false;
        this.rules.audioId[0].required = false;
        this.rules.singer[0].required = false;
        this.rules.songwriter[0].required = false;
        this.rules.lyricist[0].required = true;
        this.rules.lyric[0].required = true;
      } else if (data == 1278) {
        // 成品
        this.rules.singer[0].required = true;
        this.rules.audioFile[0].required = true;
        this.rules.audioId[0].required = true;
        this.rules.lyricist[0].required = false;
        this.rules.songwriter[0].required = false;
        this.rules.lyric[0].required = false;
      } else if (data == 1280) {
        // 作曲
        this.rules.songwriter[0].required = true;
        this.rules.audioFile[0].required = true;
        this.rules.audioId[0].required = true;
        this.rules.singer[0].required = false;
        this.rules.lyricist[0].required = false;
        this.rules.lyric[0].required = false;
      } else if (data == 1281) {
        // 其他
        this.rules.songwriter[0].required = false;
        this.rules.audioFile[0].required = true;
        this.rules.audioId[0].required = true;
        this.rules.singer[0].required = false;
        this.rules.lyricist[0].required = false;
        this.rules.lyric[0].required = false;
      }
    },
    // 文件数量超上限响应
    exceed(e, d) {
      this.$message.error("只能上传一个文件");
      this.errorMsg = "只能上传一个文件";
    },
    // 表单重置按钮响应
    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.errorMsg = "上传中的文件不可删除";
        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.errorMsg = ''
          this.banAgree = true
          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 + "/" + this.getCategoryText(this.form.channelId),
              tag: this.getChannelText(this.form.channelId),
              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 + "/" + this.getCategoryText(this.form.channelId),
              // 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) => {
                    if (
                      res &&
                      res.data &&
                      res.data.errorCode &&
                      res.data.errorCode != 0
                    ) {
                      that.errorMsg = "系统错误,请联系管理员";
                      // that.reset();
                      this.submitDisabled = false;
                      this.btnDisabled = false;
                      this.banAgree = false
                      return false;
                    } else {
                      let apiComplete =
                        all.secretUrls.base + all.secretUrls.callback;
                      let apiStringSignComplete = all.signFunction(
                        apiComplete,
                        // that.getParamsList({
                        //   ...fileBaseObj,
                        //   ...fileSaveObj,
                        //   ...{ timestamp: that.getTimeStamp() },
                        // })
                        that.getParamsList(Object.assign(fileBaseObj, fileSaveObj, {timestamp: that.getTimeStamp()}))
                      );
                      return all.request({
                        url: apiComplete,
                        method: "get",
                        params: all.parseQueryString(apiStringSignComplete),
                      });
                    }
                  })
                  .then((data) => {
                    if (
                      data &&
                      data.data &&
                      data.data.data &&
                      data.data.data.obj
                    ) {
                      that.form.audioId = data.data.data.obj;
                      that.percent = 100;
                      that.postCms();
                    } else {
                      that.errorMsg = "系统错误,请联系管理员";
                      // that.reset()
                      this.submitDisabled = false;
                      this.btnDisabled = false;
                      this.banAgree = false
                    }
                  })
                  .catch((error) => {
                    that.errorMsg = error ? error : "系统错误,请联系管理员";
                    // that.reset();
                    this.submitDisabled = false;
                    this.btnDisabled = false;
                    this.banAgree = false
                  });
              },
            };

            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,
                  // });
                  this.errorMsg = "鉴权失败";
                  // this.reset();
                  this.submitDisabled = false;
                  this.btnDisabled = false;
                  this.banAgree = false
                  return false;
                }
                fileBaseObj.md5 = n;
                let apiInit = all.secretUrls.base + all.secretUrls.init;
                let apiStringSignInit = all.signFunction(
                  apiInit,
                  // this.getParamsList({ ...fileBaseObj, ...fileInitObj })
                  this.getParamsList(Object.assign(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 {
                  if (
                    res &&
                    res.data &&
                    res.data.errorCode &&
                    res.data.errorCode != 0
                  ) {
                    this.errorMsg = "系统错误,请联系管理员";
                    // this.reset();
                    this.submitDisabled = false;
                    this.btnDisabled = false;
                    this.banAgree = false
                  }
                }
              })
              .catch((error) => {
                this.errorMsg = error ? error : "系统错误,请联系管理员";
                // this.reset()
                this.submitDisabled = false;
                this.btnDisabled = false;
                this.banAgree = false
              });
          }
        } else {
          // this.$message.error("请检查表单内容");
          this.errorMsg = '请检查表单内容'
          this.submitDisabled = false;
          this.btnDisabled = false;
          this.banAgree = 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()
      );
    },
    // 通过作品类型id获取作品分类,用于上传视频的??参数
    getCategoryText(id) {
      if (id == 1278) {
        return "533";
      }
      if (id == 1280) {
        return "534";
      }
      if (id == 1281) {
        return "532";
      }
    },
    // 通过作品类型id获取作品类型,用于上传视频的tag
    getChannelText(id) {
      if (id == 1278) {
        return "热歌榜";
      }
      if (id == 1279) {
        return "优秀作词榜";
      }
      if (id == 1280) {
        return "优秀作曲榜";
      }
      if (id == 1281) {
        return "其他";
      }
    },
    // 获取认证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() {
      all
        .request({
          // url: "http://cmstest.cnlive.com:8768/contentApi/audioSave",
          url: "https://cms.cnlive.com/api/contentApi/audioSave",
          method: "post",
          params: {
            channelId: this.form.channelId,
            songName: this.form.songName,
            singer: this.form.singer,
            lyric: this.addBr(this.form.lyric),
            phone: this.form.phone,
            name: this.form.name,
            audioId: this.form.audioId,
            lyricist: this.form.lyricist,
            songwriter: this.form.songwriter,
            redact: this.form.redact,
            mixing: this.form.mixing,
          },
          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 success");
              window.location.replace("./success.html");
            }, 1000);
          } else {
            setTimeout(() => {
              // console.log("jump");
              window.location.replace("./failed.html");
            }, 1000);
          }
        })
        .catch((error) => {
          console.log(error);
          setTimeout(() => {
            // console.log("jump");
            window.location.replace("./failed.html");
          }, 1000);
        })
        .finally(() => {
          setTimeout(() => {
            this.btnDisabled = false;
            this.submitDisabled = false;
            this.banAgree = false            
          }, 1000);
        });
    },
    // 获取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) {
      console.log(file)
      this.form.audioFile = file;
      this.errorMsg = "";
    },
    // textarea换行转br
    addBr(str) {
      var reg = new RegExp("\r\n","g");
      var regr = new RegExp("\r","g");
      var regn = new RegExp("\n","g");
      if(str) {
        str = str.trim()
        str = str.replace(regr,"<br/>")
        str = str.replace(regn,"<br/>")
        str = str.replace(reg,"<br/>")
      } else {
        str = ''
      }
      return str
    }
  },
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#mainPage')