All files / Rindu/hooks useMediaSession.ts

58.62% Statements 34/58
43.47% Branches 20/46
35.71% Functions 5/14
58.62% Lines 34/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 16819x   19x     19x   41x                                         41x 41x 41x 41x         41x   41x         41x                       41x 41x 3x 3x               3x       3x       3x               3x               3x                 3x     3x                               41x 41x 41x     41x 41x   41x 41x       41x     41x       41x 41x                                 41x                      
import { Dispatch, RefObject, SetStateAction, useEffect } from "react";
 
import { useAuth } from "hooks";
import { AudioPlayer } from "hooks/useSpotifyPlayer";
import { ITrack } from "types/spotify";
import { callPictureInPicture } from "utils";
 
export function useMediaSession({
  currentlyPlaying,
  currentlyPlayingPosition,
  player,
  isPlaying,
  setIsPlaying,
  videoRef,
  pictureInPictureCanvas,
  isPictureInPictureLyircsCanvas,
  syncLyricsLine,
}: {
  currentlyPlaying: ITrack | undefined;
  currentlyPlayingPosition: number | undefined;
  player: Spotify.Player | AudioPlayer | undefined;
  isPlaying: boolean;
  setIsPlaying: Dispatch<SetStateAction<boolean>>;
  videoRef: RefObject<HTMLVideoElement | null>;
  pictureInPictureCanvas: RefObject<HTMLCanvasElement | null>;
  isPictureInPictureLyircsCanvas: boolean;
  syncLyricsLine: () => void;
}): void {
  const { user, isPremium } = useAuth();
  useEffect(() => {
    const duration = (currentlyPlaying?.duration_ms ?? 0) / 1000;
    if (
      navigator.mediaSession &&
      "setPositionState" in navigator.mediaSession
    ) {
      const currentPlayingPositionSeconds =
        (currentlyPlayingPosition ?? 0) / 1000;
      const position =
        currentPlayingPositionSeconds &&
        currentPlayingPositionSeconds <= (duration ?? 0)
          ? currentPlayingPositionSeconds
          : 0;
 
      navigator.mediaSession.setPositionState({
        duration: duration,
        playbackRate: 1,
        position: position,
      });
    }
  }, [
    currentlyPlayingPosition,
    currentlyPlaying,
    currentlyPlaying?.duration_ms,
  ]);
 
  useEffect(() => {
    if (player && "mediaSession" in navigator) {
      try {
        navigator.mediaSession.setActionHandler("play", function () {
          setIsPlaying(true);
          Iif (!isPremium) {
            player?.togglePlay();
            return;
          }
          (player as Spotify.Player)?.resume();
        });
        navigator.mediaSession.setActionHandler("pause", function () {
          player?.pause();
          setIsPlaying(false);
        });
        navigator.mediaSession.setActionHandler("stop", function () {
          player.pause();
          setIsPlaying(false);
        });
        navigator.mediaSession.setActionHandler("seekbackward", function () {
          player.seek(
            !currentlyPlayingPosition || currentlyPlayingPosition <= 10 * 1000
              ? 0
              : currentlyPlayingPosition - 10 * 1000
          );
          syncLyricsLine();
        });
        navigator.mediaSession.setActionHandler("seekforward", function () {
          player.seek(
            !currentlyPlayingPosition
              ? 10 * 1000
              : currentlyPlayingPosition + 10 * 1000
          );
          syncLyricsLine();
        });
        navigator.mediaSession.setActionHandler(
          "seekto",
          function (mediaSessionActions) {
            Iif (mediaSessionActions.seekTime) {
              player.seek(mediaSessionActions.seekTime * 1000);
              syncLyricsLine();
            }
          }
        );
        navigator.mediaSession.setActionHandler("previoustrack", function () {
          player.previousTrack();
        });
        navigator.mediaSession.setActionHandler("nexttrack", function () {
          player.nextTrack();
        });
      } catch (error) {
        console.error("useMediaSession", error);
      }
    }
  }, [
    currentlyPlayingPosition,
    isPremium,
    player,
    user,
    setIsPlaying,
    syncLyricsLine,
  ]);
 
  useEffect(() => {
    if ("mediaSession" in navigator) {
      Iif (isPlaying) {
        navigator.mediaSession.playbackState = "playing";
      }
      if (!isPlaying) {
        navigator.mediaSession.playbackState = "paused";
      }
      if (!isPlaying && !currentlyPlaying) {
        navigator.mediaSession.playbackState = "none";
      }
    }
 
    Iif (isPlaying) {
      videoRef.current?.play();
    } else {
      videoRef.current?.pause();
    }
  }, [currentlyPlaying, isPlaying, videoRef]);
 
  useEffect(() => {
    Iif (currentlyPlaying && "mediaSession" in navigator) {
      navigator.mediaSession.metadata = new MediaMetadata({
        title: currentlyPlaying.name,
        artist: currentlyPlaying.artists?.[0]?.name,
        album: currentlyPlaying.album?.name,
        artwork: currentlyPlaying.album?.images?.map(
          ({ url, width, height }) => {
            return {
              src: url ?? "",
              sizes: `${width ?? 0}x${height ?? 0}`,
              type: "",
            };
          }
        ),
      });
    }
 
    Iif (
      pictureInPictureCanvas.current &&
      videoRef.current &&
      document.pictureInPictureElement &&
      !isPictureInPictureLyircsCanvas
    ) {
      callPictureInPicture(pictureInPictureCanvas.current, videoRef.current);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentlyPlaying, isPictureInPictureLyircsCanvas, isPlaying]);
}