index.js 17.4 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
import React, { useEffect, useRef, useContext, useState, useImperativeHandle } from 'react';
import { LoadingOutlined } from '@ant-design/icons';
import { message, ConfigProvider, Progress, Slider, Spin } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import Empty from '@wisdom-components/empty';
import empty_icon from '../../assets/缺省页.png';
import backward_icon from './assets/backward.svg';
import forward_icon from './assets/forward.svg';
import expend_icon from './assets/expend.svg';
import mute_icon from './assets/mute.svg';
import play_icon from './assets/play.svg';
import stop_icon from './assets/stop.svg';
import volume_icon from './assets/volume.svg';
import reload_icon from './assets/reload.svg';
import play_big_icon from './assets/play_big.svg';
import TimeSlider from '../TimeSlider';
import { hiswsUrl } from '../../apis';
import './index.less';

const HKh5player = (props, ref) => {
  const IS_MOVE_DEVICE = document.body.clientWidth < 992; // 是否移动设备
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('hk-h5-player-view');
25
  const { VideoInfo = {}, JessibucaObj, ProgressBar, EmptyIcon = '' } = props;
李纪文's avatar
李纪文 committed
26
  const videoID = VideoInfo?.id || `VIDEO_PLAY_BACK${Date.now().toString(36)}`;
李纪文's avatar
李纪文 committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
  const [showId, setShowId] = useState(VideoInfo?.id || ''); //视频ID
  const [peridos, setPeridos] = useState([]); //可播放视频时间段
  const [hoursRuler, setHoursRuler] = useState(VideoInfo.hoursRuler || 24);
  const [playTimestamp, setPlayTimestamp] = useState(
    VideoInfo?.playTime ? moment(VideoInfo?.playTime).valueOf() : null,
  ); //当前正在播放时间段
  const [minTimestamp, setMinTimestamp] = useState(null); //时间轴最小时间
  const [maxTimestamp, setMaxTimestamp] = useState(null); //时间轴最大时间
  const [loading, setLoading] = useState(false); // 初始化加载状态
  const [sping, setSping] = useState(false); // 视频加载状态
  const [percent, setPercent] = useState(0);
  const [playStatus, setPlayStatus] = useState(false);
  const [playSpeed, setPlaySpeed] = useState(1);
  const [mutedStatus, setMutedStatus] = useState(false);
  const [soundSize, setSoundSize] = useState(50);
  const [fullStatus, setFullStatus] = useState(false);
  const [streamEnd, setStreamEnd] = useState(false);
  const videoUrl = useRef(null);
  const timeRef = useRef(null);
  const player = useRef(null);

  useEffect(() => {
李纪文's avatar
李纪文 committed
49 50
    setShowId(props?.VideoInfo?.id || '');
    setHoursRuler(props?.VideoInfo.hoursRuler || 24);
李纪文's avatar
李纪文 committed
51 52 53
    const playTimes = props?.VideoInfo?.playTime
      ? moment(props?.VideoInfo?.playTime).valueOf()
      : null;
李纪文's avatar
李纪文 committed
54 55
    setPlayTimestamp(playTimes);
    changeReplayCfg?.(playTimes);
李纪文's avatar
李纪文 committed
56 57 58 59
    // 设置播放容器的宽高并监听窗口大小变化
    window.addEventListener('resize', resizeVideo);
    return () => {
      window.removeEventListener('resize', resizeVideo);
李纪文's avatar
李纪文 committed
60
      player.current?.removeAllListeners?.();
李纪文's avatar
李纪文 committed
61
      player.current?.JS_Destroy?.();
李纪文's avatar
李纪文 committed
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
      player.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.VideoInfo]);

  useEffect(() => {
    if (peridos.length && player.current && playTimestamp) {
      const endTime = moment(peridos?.[0].endTime).format('YYYY-MM-DD HH:mm:ss');
      const beginTime = moment(playTimestamp).format('YYYY-MM-DD HH:mm:ss');
      playbackToSeek({ beginTime: beginTime, endTime: endTime });
      player.current?.JS_Resize?.();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playTimestamp]);

  useEffect(() => {
    let current = percent;
    if (loading)
      timeRef.current = setInterval(() => {
        current = current + 1;
        setPercent(current > 99 ? 99 : current);
      }, 20);

    return () => {
      if (timeRef.current) {
        clearInterval(timeRef.current);
        timeRef.current = null;
        setPercent(0);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loading]);

  // 设置播放容器的宽高并监听窗口大小变化
  const resizeVideo = () => {
    player.current?.JS_Resize?.();
  };

  // 更改播放配置
李纪文's avatar
李纪文 committed
101
  const changeReplayCfg = (playTimes) => {
李纪文's avatar
李纪文 committed
102 103 104 105
    const {
      beginTime = moment().format('YYYY-MM-DD 00:00:00'),
      endTime = moment().format('YYYY-MM-DD 23:59:59'),
      id = '',
李纪文's avatar
李纪文 committed
106
    } = props?.VideoInfo || {};
李纪文's avatar
李纪文 committed
107 108 109
    if (!id) return setShowId(null);
    const hoursPerRuler = calculateHours(beginTime, endTime) || 24;
    const stTimes = moment(beginTime).format('YYYY-MM-DD HH:mm:ss');
110 111 112 113
    const edTimes =
      moment(new Date()).valueOf() >= moment(endTime).valueOf()
        ? moment(endTime).format('YYYY-MM-DD HH:mm:ss')
        : moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
李纪文's avatar
李纪文 committed
114 115 116 117 118 119 120 121 122 123
    const params = {
      id: id,
      startTime: stTimes,
      endTime: edTimes,
      'site-code':
        window?.globalConfig?.userInfo?.LocalSite || window?.globalConfig?.userInfo?.site || '',
    };
    setHoursRuler(hoursPerRuler);
    setMinTimestamp(moment(stTimes).valueOf());
    setMaxTimestamp(moment(edTimes).valueOf());
李纪文's avatar
李纪文 committed
124
    setPlayTimestamp(playTimes ? playTimes : moment(stTimes).valueOf());
李纪文's avatar
李纪文 committed
125 126 127 128 129 130 131 132
    setPeridos([
      {
        beginTime: moment(beginTime).valueOf(),
        endTime: moment(endTime).valueOf(),
        style: { background: '#637DEC' },
      },
    ]);
    setLoading(true);
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    hiswsUrl(params)
      .then((res) => {
        setLoading(false);
        if (res.code === 200) {
          const data = res?.data || '';
          const url = data.split('?')[0].split('/').pop() || '';
          if (!url) return setShowId(null);
          videoUrl.current = url;
          getVideoReplayInfo({
            beginTime: playTimestamp
              ? moment(playTimestamp).format('YYYY-MM-DD HH:mm:ss')
              : stTimes,
            endTime: edTimes,
          });
        } else {
          setShowId(null);
          message.warn(res.msg);
        }
      })
      .catch((err) => {
        setLoading(false);
李纪文's avatar
李纪文 committed
154
        setShowId(null);
155
      });
李纪文's avatar
李纪文 committed
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
  };

  // 获取计算小时数
  const calculateHours = (time1, time2) => {
    const date1 = new Date(time1);
    const date2 = new Date(time2);
    const diff = Math.abs(date1.getTime() - date2.getTime());
    return Math.ceil(diff / (1000 * 60 * 60));
  };

  // 获取视频配置信息
  const getVideoReplayInfo = (times) => {
    createPlayer();
    playbackStart({ beginTime: times.beginTime, endTime: times.endTime });
    player.current?.JS_Resize?.();
  };

  // 创建视频播放
  const createPlayer = () => {
    player.current = new window.JSPlugin({
      szId: videoID,
      szBasePath: JessibucaObj?.decoder || '/h5player',
      iMaxSplit: 1,
      iCurrentSplit: 1,
      openDebug: false,
      oStyle: {
        borderSelect: IS_MOVE_DEVICE ? '#000' : '#000',
      },
    });

    // 事件回调绑定
    player.current?.JS_SetWindowControlCallback?.({
      windowEventSelect: (iWndIndex) => {
        //插件选中窗口回调
      },
      pluginErrorHandler: (iWndIndex, iErrorCode, oError) => {
        //插件错误回调
        playbackReload();
      },
      windowEventOver: (iWndIndex) => {
        //鼠标移过回调
      },
      windowEventOut: (iWndIndex) => {
        //鼠标移出回调
      },
      windowEventUp: (iWndIndex) => {
        //鼠标mouseup事件回调
      },
      windowFullCcreenChange: (bFull) => {
        //全屏切换回调
      },
      firstFrameDisplay: (iWndIndex, iWidth, iHeight) => {
        //首帧显示回调
      },
      performanceLack: () => {
        //性能不足回调
      },
      StreamEnd: () => {
        setStreamEnd(true);
        setPlayStatus(false);
        setPlayTimestamp(null);
      },
    });

    player.current?.JS_SetConnectTimeOut?.(0, 10)?.then(
      () => {},
      (err) => {},
    );
  };

  // 视频开始播放
  const playbackStart = (times) => {
    const index = 0;
229 230
    const defaultUrl = `ws://${window?.location?.host || ''}`;
    const playURL = `${getVideoUrl() || defaultUrl}/openUrl/${videoUrl.current}`;
李纪文's avatar
李纪文 committed
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
    const beginTime = times.beginTime.replaceAll(' ', 'T') + 'Z';
    const endTime = times.endTime.replaceAll(' ', 'T') + 'Z';
    setSping(true);
    setPlaySpeed(1);
    setMutedStatus(false);
    setSoundSize(50);
    player.current?.JS_Play?.(playURL, { playURL, mode: 1 }, index, beginTime, endTime)?.then(
      () => {
        setSping(false);
        setPlayStatus(true);
      },
      (e) => {
        setSping(false);
        // console.error(e);
      },
    ) || setSping(false);
  };

  // 视频定位播放
  const playbackToSeek = (times) => {
    const beginTime = times.beginTime.replaceAll(' ', 'T') + 'Z';
    const endTime = times.endTime.replaceAll(' ', 'T') + 'Z';
    player.current?.JS_Seek?.(0, beginTime, endTime)?.then(
      () => {},
      (e) => {
        // console.error(e);
      },
    );
  };

  // 视频刷新播放
  const playbackReload = () => {
    setPlayStatus(false);
    const {
      beginTime = moment().format('YYYY-MM-DD 00:00:00'),
      endTime = moment().format('YYYY-MM-DD 23:59:59'),
李纪文's avatar
李纪文 committed
267
    } = props?.VideoInfo || {};
李纪文's avatar
李纪文 committed
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
    const bgTimes = moment(beginTime).format('YYYY-MM-DD HH:mm:ss');
    const edTimes = moment(endTime).format('YYYY-MM-DD HH:mm:ss');
    player.current?.JS_GetOSDTime?.()?.then(
      (time) => {
        playbackStart({
          beginTime: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          endTime: edTimes,
        });
      },
      (e) => {
        playbackStart({
          beginTime: bgTimes,
          endTime: edTimes,
        });
      },
    );
  };

  // 视频播放状态
  const handVideoPlay = () => {
    if (!player.current) return false;
    if (playStatus) {
      // 暂停播放
      player.current?.JS_Pause?.()?.then(
        () => {
          setPlayStatus(false);
        },
        (e) => {
          // console.error(e);
        },
      );
    } else {
      // 恢复播放
      player.current?.JS_Resume?.().then(
        () => {
          setPlayStatus(true);
        },
        (e) => {
          // console.error(e);
        },
      );
    }
  };

  // 视频慢放
  const handVideoSpeedSlow = () => {
    if (!player.current) return false;
    player.current?.JS_Slow?.()?.then(
      (rate) => {
        if (rate > 0) {
          setPlaySpeed(rate);
        } else {
          setPlaySpeed(1 / Math.abs(rate));
        }
      },
      (e) => {
        // console.error(e);
      },
    );
  };

  // 视频快放
  const handVideoSpeedFast = () => {
    if (!player.current) return false;
    player.current?.JS_Fast?.()?.then(
      (rate) => {
        if (rate > 0) {
          setPlaySpeed(rate);
        } else {
          setPlaySpeed(1 / Math.abs(rate));
        }
      },
      (e) => {
        // console.error(e);
      },
    );
  };

  // 视频声音控制
  const handVideoSound = () => {
    if (!player.current) return false;
    if (mutedStatus) {
      player.current?.JS_CloseSound?.()?.then(
        () => {
          setMutedStatus(false);
          setSoundSize(50);
        },
        (e) => {
          // console.error(e)
        },
      );
    } else {
      player.current?.JS_OpenSound?.()?.then(
        () => {
          setMutedStatus(true);
          setSoundSize(50);
        },
        (e) => {
          // console.error(e)
        },
      );
    }
  };

  // 视频声音改变
  const changeVideoSlider = (value) => {
    if (!player.current || !mutedStatus) return false;
    player.current?.JS_SetVolume?.(0, value)?.then(
      () => {
        setSoundSize(value);
      },
      (e) => {
        // console.error(e)
      },
    );
  };

  // 视频全屏
  const handVideoFull = () => {
    if (!player.current) return false;
    // 全屏
    player.current?.JS_FullScreenSingle?.(0)?.then(
      () => {},
      (e) => {
        // console.error(e);
      },
    );
  };

  // 视频刷新
  const handVideoReload = () => {
    playbackReload();
  };

  // 视频重新播放
  const handReloadVideo = () => {
    setStreamEnd(false);
    const {
      beginTime = moment().format('YYYY-MM-DD 00:00:00'),
      endTime = moment().format('YYYY-MM-DD 23:59:59'),
李纪文's avatar
李纪文 committed
408
    } = props?.VideoInfo || {};
李纪文's avatar
李纪文 committed
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
    const bgTimes = moment(beginTime).format('YYYY-MM-DD HH:mm:ss');
    const edTimes = moment(endTime).format('YYYY-MM-DD HH:mm:ss');
    playbackStart({
      beginTime: bgTimes,
      endTime: edTimes,
    });
  };

  // 视频容器渲染
  const videoBoxRender = () => {
    return (
      <>
        <div className={classNames(`${prefixCls}-content`)}>
          <div
            id={videoID}
            className={classNames(`${prefixCls}-video`)}
            style={{ width: '100%', height: '600px' }}
          />
          <ul className={classNames(`${prefixCls}-control`)}>
            <li className={classNames(`${prefixCls}-control-play`)}>
              <img src={playStatus ? stop_icon : play_icon} onClick={handVideoPlay} />
            </li>
            <li className={classNames(`${prefixCls}-control-speed`)}>
              <div
                className={classNames(
                  `${prefixCls}-control-speed-btn`,
                  playSpeed === 0.25 ? `${prefixCls}-control-speed-none` : '',
                )}
                onClick={handVideoSpeedSlow}
              >
                <img src={backward_icon} />
              </div>
              <span className={classNames(`${prefixCls}-control-speed-value`)}>{playSpeed}x</span>
              <div
                className={classNames(
                  `${prefixCls}-control-speed-btn`,
                  playSpeed === 4 ? `${prefixCls}-control-speed-none` : '',
                )}
                onClick={handVideoSpeedFast}
              >
                <img src={forward_icon} />
              </div>
            </li>
            <li className={classNames(`${prefixCls}-control-sound`)}>
              <img src={mutedStatus ? volume_icon : mute_icon} onClick={handVideoSound} />
              <div className={classNames(`${prefixCls}-control-sound-slider`)}>
                <Slider
                  className={classNames(`${prefixCls}-control-sound-slider-list`)}
                  vertical
                  onChange={changeVideoSlider}
                  value={soundSize}
                />
              </div>
            </li>
            <li className={classNames(`${prefixCls}-control-full`)} onClick={handVideoFull}>
              <img src={expend_icon} />
            </li>
            <li className={classNames(`${prefixCls}-control-reload`)} onClick={handVideoReload}>
              <img src={reload_icon} />
            </li>
          </ul>
        </div>
        {/* 时间轴 */}
        <div className={classNames(`${prefixCls}-time`)}>
          {peridos.length ? (
            <TimeSlider
李纪文's avatar
李纪文 committed
475
              key={JSON.stringify(props?.VideoInfo || {})}
李纪文's avatar
李纪文 committed
476 477 478 479 480 481 482 483
              minTimestamp={minTimestamp}
              maxTimestamp={maxTimestamp}
              hoursPerRuler={hoursRuler || 24}
              playTimestamp={playTimestamp ? playTimestamp : peridos?.[0]?.beginTime}
              playTimestampChange={(time, recordInfo, playOffset) => {
                if (recordInfo && playOffset) {
                  setPlayTimestamp(time);
                } else {
484
                  message.warn('当前时间节点超出回放时间区间!');
李纪文's avatar
李纪文 committed
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
                }
              }}
              timecell={peridos}
            />
          ) : null}
        </div>
        {streamEnd && (
          <div className={classNames(`${prefixCls}-stream`)}>
            <img src={play_big_icon} onClick={handReloadVideo} />
            <span>视频回放播放结束,可点击播放重新查看回放</span>
          </div>
        )}
        {sping && (
          <div className={classNames(`${prefixCls}-spin`)}>
            <Spin
              className={classNames(`${prefixCls}-spin-box`)}
              tip="视频回放正在加载中..."
              indicator={
                <LoadingOutlined
                  style={{
                    fontSize: 48,
                  }}
                />
              }
            />
            ;
          </div>
        )}
      </>
    );
  };

  // 加载容器渲染
  const loadBoxRender = () => {
    return (
      <>
        <div className={classNames(`${prefixCls}-load`)}>
          <Progress
            className={classNames(`${prefixCls}-progress`)}
            strokeColor={ProgressBar?.strokeColor || ''}
            format={(percent) => {
              return (
                <span style={{ color: ProgressBar?.textColor || 'unset' }}>{percent + '%'}</span>
              );
            }}
            strokeWidth={14}
            percent={percent}
          />
          <span style={{ color: ProgressBar?.textColor || 'unset' }}>
            视频回放信息获取中,请稍后...
          </span>
        </div>
      </>
    );
  };

  // 缺省页容器渲染
  const emptyBoxRender = () => {
    return (
      <div className={classNames(`${prefixCls}-empty`)}>
545 546 547 548 549
        <Empty
          image={EmptyIcon || empty_icon}
          theme={'dark'}
          description={'咦~暂时没有查询到视频回放信息呢~'}
        />
李纪文's avatar
李纪文 committed
550 551 552 553 554 555 556 557 558 559 560
      </div>
    );
  };

  return (
    <div className={classNames(`${prefixCls}`)}>
      {loading ? loadBoxRender() : showId ? videoBoxRender() : emptyBoxRender()}
    </div>
  );
};

561 562 563 564 565 566 567
export const getVideoUrl = () => {
  const protocol = window.location.protocol;
  const port = window.location.port ? '' : ':443';
  const address = protocol === "https:" ? `${window.location.origin.replace(protocol, 'wss:')}${port}` : window.location.origin.replace(protocol, 'ws:');
  return `${address}`;
};

李纪文's avatar
李纪文 committed
568
export default HKh5player;