1
Watch for new listenings Trigger
One script reply has been approved by the moderators Verified

GET /api/v1/history/listenings

Created by jaller94 814 days ago Viewed 9376 times
0
Submitted by jaller94 Deno
Verified 814 days ago
1
import {
2
  getState,
3
  setState,
4
} from "https://deno.land/x/windmill@v1.85.0/mod.ts";
5

6
/**
7
 * **IMPORTANT:** This does not return listenings on the first run.
8
 *
9
 * You can read more about the Listenings History API at
10
 * https://docs.funkwhale.audio/swagger/#/User%20activity/get_api_v1_history_listenings
11
 */
12
type Funkwhale = {
13
  baseUrl: string;
14
  token: string;
15
};
16
export async function main(
17
  auth: Funkwhale,
18
  query?: string,
19
  scope = "all",
20
  page_size = 10,
21
) {
22
  const previousState = await getState();
23
  const url = new URL("/api/v1/history/listenings", auth.baseUrl);
24
  const params = { query, scope, page_size };
25
  Object.entries(params).forEach(([key, value]) => {
26
    value && url.searchParams.append(key, encodeURIComponent(value));
27
  });
28
  const response = await fetch(url, {
29
    headers: {
30
      Authorization: `Bearer ${auth.token}`,
31
    },
32
  });
33

34
  const data = await response.json();
35
  data.results.reverse();
36

37
  const newListenings = [];
38
  let latestId;
39
  for (const listening of data.results) {
40
    if (latestId === undefined || listening.id > latestId) {
41
      latestId = listening.id;
42
    }
43
    if (
44
      previousState?.latestId !== undefined &&
45
      listening.id <= previousState.latestId
46
    ) {
47
      continue;
48
    }
49
    newListenings.push(listening);
50
  }
51

52
  if (latestId !== undefined) {
53
    await setState({
54
      latestId,
55
    });
56
  }
57
  return newListenings;
58
}
59