All files / Rindu/utils playCurrentTrack.ts

95.23% Statements 40/42
82.6% Branches 19/23
83.33% Functions 5/6
97.56% Lines 40/41

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    45x 45x         45x   2x                           2x 1x 1x       1x     2x 1x                                     1x 1x 1x 1x       5x 5x   5x 5x 5x 5x           5x                                         9x                           7x   7x 1x         1x     6x 1x           5x     5x   5x   5x         5x         5x       5x   5x 3x   2x 1x   1x    
import { SetStateAction } from "react";
 
import { BadRequestError, NotFoundError } from "./errors";
import { templateReplace } from "./templateReplace";
import { AudioPlayer } from "hooks/useSpotifyPlayer";
import { ITrack } from "types/spotify";
import { NewToast } from "types/toast";
import { ITranslations } from "types/translations";
import { play } from "utils/spotifyCalls";
 
export function handlePlayCurrentTrackError(
  error: unknown,
  {
    player,
    addToast,
    setReconnectionError,
    translations,
  }: {
    player: Spotify.Player;
    addToast: (toast: NewToast) => void;
    setReconnectionError: (value: SetStateAction<boolean>) => void;
    translations: ITranslations;
  }
): void {
  if (NotFoundError.isThisError(error)) {
    player.disconnect();
    addToast({
      variant: "error",
      message: translations.toastMessages.unableToPlayReconnecting,
    });
    setReconnectionError(true);
  }
 
  if (BadRequestError.isThisError(error)) {
    addToast({
      variant: "error",
      message: templateReplace(translations.toastMessages.errorPlayingThis, [
        translations.contentType.track,
      ]),
    });
  }
}
 
interface IhandleStandardPlay {
  player: AudioPlayer;
  previewUrl: string;
  allTracks: ITrack[];
}
function handleStandardPlay({
  player,
  previewUrl,
  allTracks,
}: IhandleStandardPlay) {
  player.currentTime = 0;
  player.src = previewUrl;
  player.play();
  player.allTracks = allTracks;
}
 
function filterTracksByUri(allTracks: ITrack[]) {
  const allTracksUris: string[] = [];
  const positionOfTracksWithoutUri: number[] = [];
 
  allTracks.forEach((track, i) => {
    if (track.uri) {
      allTracksUris.push(track.uri);
      return;
    }
 
    positionOfTracksWithoutUri.push(i);
  });
 
  return { allTracksUris, positionOfTracksWithoutUri };
}
 
interface IPlayConfig {
  allTracks: ITrack[];
  isPremium: boolean;
  deviceId: string | undefined;
  playlistUri: string | undefined;
  player: AudioPlayer | Spotify.Player | undefined;
  isSingleTrack?: boolean;
  position?: number;
  uri?: string;
  uris?: string[];
}
 
interface ITrackInfo {
  preview_url?: string | null;
  position?: number;
  uri?: string;
}
 
export async function playCurrentTrack(
  trackInfo: ITrackInfo,
  config: IPlayConfig
): Promise<string | undefined> {
  const {
    player,
    isPremium,
    allTracks,
    deviceId,
    playlistUri,
    isSingleTrack,
    position,
    uri,
    uris,
  } = config;
 
  if (!isPremium && trackInfo?.preview_url) {
    handleStandardPlay({
      player: player as AudioPlayer,
      allTracks,
      previewUrl: trackInfo.preview_url,
    });
    return;
  }
 
  if (!deviceId) {
    throw new BadRequestError("Play Track", {
      details: { isPremium, message: "Missing deviceId" },
    });
  }
 
  const { allTracksUris, positionOfTracksWithoutUri } =
    filterTracksByUri(allTracks);
 
  const numberOfTracksWithoutUriLowerThanPosition =
    positionOfTracksWithoutUri.filter((p) => p < (position ?? 0)).length;
  const positionInUrisArray =
    (position ?? 0) - numberOfTracksWithoutUriLowerThanPosition;
 
  const singleTrackConfiguration = {
    uris: uris ?? (uri ? [uri] : allTracksUris),
    offset: uri ? 0 : positionInUrisArray,
  };
 
  const trackConfiguration = {
    context_uri: playlistUri,
    offset: trackInfo?.position ?? 0,
  };
 
  const playConfig = isSingleTrack
    ? singleTrackConfiguration
    : trackConfiguration;
 
  const res = await play(deviceId, playConfig);
 
  if (res.ok) {
    return;
  }
  if (res.status === 404) {
    throw new NotFoundError(res.url);
  }
  throw new BadRequestError();
}