aboutsummaryrefslogtreecommitdiff
path: root/users/ryan/modules/simple-bar/simple-bar-source/lib/components/data/spotify.jsx
blob: bc9f6e6101d78e425b59d09e188bd46efd287acc (plain)
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
import * as Uebersicht from "uebersicht";
import * as DataWidget from "./data-widget.jsx";
import * as DataWidgetLoader from "./data-widget-loader.jsx";
import useWidgetRefresh from "../../hooks/use-widget-refresh";
import useServerSocket from "../../hooks/use-server-socket";
import { useSimpleBarContext } from "../simple-bar-context.jsx";
import * as Icons from "../icons/icons.jsx";
import * as Utils from "../../utils";

export { spotifyStyles as styles } from "../../styles/components/data/spotify";

const { React } = Uebersicht;

const DEFAULT_REFRESH_FREQUENCY = 10000;

/**
 * Spotify widget component.
 * @returns {JSX.Element|null} The Spotify widget.
 */
export const Widget = React.memo(() => {
  const { displayIndex, settings } = useSimpleBarContext();
  const { widgets, spotifyWidgetOptions } = settings;
  const { spotifyWidget } = widgets;
  const {
    refreshFrequency,
    showSpecter,
    showOnDisplay,
    showIcon,
    showSpotifyMetadata,
  } = spotifyWidgetOptions;

  // Determine the refresh frequency for the widget
  const refresh = React.useMemo(
    () =>
      Utils.getRefreshFrequency(refreshFrequency, DEFAULT_REFRESH_FREQUENCY),
    [refreshFrequency],
  );

  // Determine if the widget should be visible
  const visible =
    Utils.isVisibleOnDisplay(displayIndex, showOnDisplay) && spotifyWidget;

  const [state, setState] = React.useState();
  const [loading, setLoading] = React.useState(visible);
  const [isSpotifyActive, setIsSpotifyActive] = React.useState(false);

  /**
   * Resets the widget state.
   */
  const resetWidget = () => {
    setState(undefined);
    setLoading(false);
    setIsSpotifyActive(false);
  };

  /**
   * Fetches the current Spotify state.
   */
  const getSpotify = React.useCallback(async () => {
    if (!visible) return;
    const isRunning = await Utils.cachedRun(
      `pgrep -fq '[S]potify Helper' && echo "true" || echo "false"`,
      refresh,
    );
    if (Utils.cleanupOutput(isRunning) === "false") {
      setLoading(false);
      setIsSpotifyActive(false);
      setState({
        playerState: "",
        trackName: "",
        artistName: "",
      });
      return;
    }
    // if showSpotifyMetadata is enabled, retrieves all information
    if (showSpotifyMetadata) {
      const output = await Utils.cachedRun(
        `osascript -e 'tell application "Spotify"' -e 'set output to (player state as string) & "|" & (name of current track as string) & "|" & (artist of current track as string)' -e 'end tell' 2>/dev/null || echo "stopped||"`,
        refresh,
      );
      const [playerState, trackName, artistName] =
        Utils.cleanupOutput(output).split("|");
      setState({
        playerState,
        trackName,
        artistName,
      });
      // else, only playerState
    } else {
      const playerState = await Utils.cachedRun(
        `osascript -e 'tell application "Spotify" to player state as string' 2>/dev/null || echo "stopped"`,
        refresh,
      );
      setState({
        playerState: Utils.cleanupOutput(playerState),
        trackName: "",
        artistName: "",
      });
    }

    setIsSpotifyActive(true);
    setLoading(false);
  }, [visible, showSpotifyMetadata, refresh]);

  // Set up server socket and widget refresh hooks
  useServerSocket("spotify", visible, getSpotify, resetWidget, setLoading);
  useWidgetRefresh(visible, getSpotify, refresh);

  if (loading) return <DataWidgetLoader.Widget className="spotify" />;
  if (!state || !isSpotifyActive) return null;
  const { playerState, trackName, artistName } = state;

  if (!trackName.length && showSpotifyMetadata) return null;

  const label = artistName.length ? `${trackName} - ${artistName}` : trackName;
  const isPlaying = playerState === "playing";
  const Icon = getIcon(playerState);

  /**
   * Handles click event to toggle play/pause.
   * @param {React.MouseEvent} e - The click event.
   */
  const onClick = (e) => {
    Utils.clickEffect(e);
    togglePlay(!isPlaying);
    getSpotify();
  };

  /**
   * Handles right-click event to skip to the next track.
   * @param {React.MouseEvent} e - The right-click event.
   */
  const onRightClick = (e) => {
    Utils.clickEffect(e);
    Uebersicht.run(`osascript -e 'tell application "Spotify" to Next Track'`);
    getSpotify();
  };

  /**
   * Handles middle-click event to open Spotify.
   * @param {React.MouseEvent} e - The middle-click event.
   */
  const onMiddleClick = (e) => {
    Utils.clickEffect(e);
    Uebersicht.run(`open -a 'Spotify'`);
    getSpotify();
  };

  const classes = Utils.classNames("spotify", {
    "spotify--hidden-metadata": !showSpotifyMetadata,
    "spotify--playing": isPlaying,
  });

  return (
    <DataWidget.Widget
      classes={classes}
      Icon={showIcon ? Icon : null}
      onClick={onClick}
      onRightClick={onRightClick}
      onMiddleClick={onMiddleClick}
      showSpecter={showSpecter && isPlaying}
      disableSlider={!showSpotifyMetadata}
    >
      {showSpotifyMetadata && label}
    </DataWidget.Widget>
  );
});

Widget.displayName = "Spotify";

/**
 * Toggles play/pause state of Spotify.
 * @param {boolean} isPaused - Whether the player is paused.
 */
function togglePlay(isPaused) {
  const state = isPaused ? "play" : "pause";
  Uebersicht.run(`osascript -e 'tell application "Spotify" to ${state}'`);
}

/**
 * Gets the appropriate icon based on the player state.
 * @param {string} playerState - The current state of the player.
 * @returns {JSX.Element} The icon component.
 */
function getIcon(playerState) {
  if (playerState === "stopped") return Icons.Stopped;
  if (playerState === "playing") return Icons.Playing;
  return Icons.Paused;
}