upload-video.component.ts 6.6 KB
Newer Older
范雪寒's avatar
范雪寒 committed
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
import {Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SecurityContext, ViewChild} from '@angular/core';
import {NzMessageService, UploadChangeParam, UploadFile, UploadFileStatus} from 'ng-zorro-antd';
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';


@Component({
  selector: 'app-upload-video',
  templateUrl: './upload-video.component.html',
  styleUrls: ['./upload-video.component.scss']
})
export class UploadVideoComponent implements OnChanges, OnDestroy {
  uploading = false;
  checking = false;
  checkVideoExists = false;
  uploadClicked = false;

  @Input()
  videoFile = null;
  uploaderInst = null;

  progress = 0;
  // @Input()
  // setCovering = false;

  @Input()
  videoUrl = '';
  @ViewChild('videoNode', {static: true })
  videoNode: ElementRef;




  // @Input()
  // extractCoverFunc = null;

  @Output()
  videoUploaded = new EventEmitter();
  @Output()
  videoUploadFailure = new EventEmitter();
  @Output()
  extractVideoCover = new EventEmitter();


  @Input()
  showUploadBtn = true;
  @Input()
  item: any;
  // videoItem = null;

  uploadUrl;
  uploadData;

  constructor(private nzMessageService: NzMessageService,
              private sanitization: DomSanitizer
              // private cwService: _coursewareService,
              // private resService: ResourceService
              ) {
    this.uploading = false;
    this.videoFile = null;


    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();

    window['air'].getUploadCallback = (url, data) => {

      this.uploadUrl = url;
      this.uploadData = data;
    };

  }
  ngOnChanges() {
    // if (!this.videoFile || this.showUploadBtn) {
    //   return;
    // }
    // this.beforeUpload(this.videoFile);
    // this.handleUpload();
  }
  ngOnDestroy(): void {
    URL.revokeObjectURL(this.videoUrl);
  }

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
  httpHeadCall(requsetUrl: string, callback) {
    let xhr = new XMLHttpRequest();
    console.log("Status: Send Post Request to " + requsetUrl);
    try {
      xhr.onreadystatechange = () => {
        try {
          console.log('xhr.readyState: ', xhr.readyState);
          if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 400)) {
              callback(true);
            } else {
              callback(false);
            }
          }

        } catch (e) {
          console.log(e)
        }
      };
      xhr.open("HEAD", requsetUrl, true);
      xhr.send();
      xhr.timeout = 15000;
      xhr.onerror = (e) => {
        callback(false);
      };
      xhr.ontimeout = (e) => {
        callback(false);
      };
    } catch (e) {
      console.log("Send Get Request error: ", e)
    }
  }

范雪寒's avatar
范雪寒 committed
116
  safeVideoUrl(url) {
117 118
    const _url = url.replace("_l.", ".");
    return this.sanitization.bypassSecurityTrustResourceUrl(_url); // `${url}`;
范雪寒's avatar
范雪寒 committed
119 120 121 122 123 124
  }
  videoLoadedMetaData() {

  }


125
  handleChange(info: UploadChangeParam): void {
范雪寒's avatar
范雪寒 committed
126 127 128 129 130 131 132 133 134
    switch (info.type) {
      case 'start':
        if (!this.checkSelectFile(info.file)) {
          return;
        }
        this.uploading = true;
        this.progress = 0;
        break;
      case 'success':
135 136 137
        let url = info.file.response.url;
        url = url.substring(0, url.lastIndexOf(".")) + "_l.mp4";
        info.file.response.url = url;
范雪寒's avatar
范雪寒 committed
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
        this.uploadSuccess(info.file);
        break;
      case 'progress':
        this.progress = info.event.percent;
        this.doProgress(this.progress);
        break;
    }
  }

  checkSelectFile(file) {
    if (!file.lastModified) {
      return false;
    }
    const delta = 500;
    const isOverSize = (file.size / 1024 / 1024) < delta;
    if (!isOverSize) {
      this.nzMessageService.error(`video must smaller than ${delta}MB!`);
      return false;
    }
    return true;
  }
  checkHashFinish = (hash) => {
    this.checking = false;
    this.uploading = true;
  }

  uploadSuccess = (file) => {

    this.nzMessageService.info('Upload Success');
    // this.updateStatus(false);
    this.uploading = false;
    this.videoFile = null;
    // this.updateSource(url);
    this.videoUrl = file.response.url;
    // console.log(this.picUrl)
    // this.uploadFinished(url);
    // if (!inOSS) {
      const vid = document.createElement('video');
      vid.addEventListener('loadedmetadata', () => {
        const height = vid.videoHeight;
        const width = vid.videoWidth;
        let duration = vid.duration;
        if (duration) {
          duration = duration * 1000;
        }
        file.height = height;
        file.width = width;
        file.duration = duration;
        vid.preload = 'none';
        vid.src = '';
        vid.remove();

        this.videoUploaded.emit(file.response);

        // this.resService.updateVideo(id, {width, height, duration}).then( () => {
        //   this.videoUploaded.emit({res_id: id, id, name, hash, url});
        // });

      });
      vid.src = file.response.url;
    // } else {
    //   this.videoUploaded.emit(file.response);
    // }



  }



  uploadFailure = (err, file) => {
    this.uploading = false;
    if (err.name && err.name === 'cancel') {
      return;
    }
    console.log(err);
    this.nzMessageService.error('Upload Error ' + err.message);
    this.videoUploadFailure.emit(file);
  }

  doProgress =  (p) => {
    if (p > 1) {
      p = 1;
    }
    if (p < 0) {
      p = 0;
    }
    // console.log(Math.floor(p * 100));
    this.progress =  Math.floor(p * 100);
  }
liujiangnan's avatar
liujiangnan committed
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

  linkInputed (url, name) {
    const file = {
      response: {url}
    };
    const vid = document.createElement('video');
    vid.addEventListener('loadedmetadata', () => {
      const height = vid.videoHeight;
      const width = vid.videoWidth;
      let duration = vid.duration;
      if (duration) {
        duration = duration * 1000;
      }
      file["height"] = height;
      file["width"] = width;
      file["duration"] = duration;
      vid.preload = 'none';
      vid.src = '';
      vid.remove();
      this.videoUploaded.emit(file.response);
    });
    vid.src = file.response.url;
    this.videoUrl = url;
  }

  handle_dragover(e) {
    e.preventDefault();
  }

  handle_drop(e) {
    const dt = e.dataTransfer.getData("text/plain");
    console.log("handle_drop===", dt);
    if (!dt) {
      return;
    }
    try {
      const {url, name} = JSON.parse(dt);
      if (url.indexOf("teach")<0 || url.indexOf("cdn")<0) {
        return;
      }
      const white = [".mp4"];
      if (!white.includes(url.substr(url.lastIndexOf(".")))) {
        return;
      }

      this.linkInputed(url, name);
    } catch (error) {
      console.warn("handle_drop拖拽在线视频传递参数不合法,应该是{url:'', name:''}");
    }
  }
范雪寒's avatar
范雪寒 committed
278 279
}