File size: 2,389 Bytes
6967c22
 
f42b4a1
1185ec1
6967c22
 
 
 
 
 
 
 
f276512
6967c22
 
 
 
f276512
 
6967c22
 
 
 
f276512
 
 
 
6967c22
 
 
f276512
 
6967c22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f276512
 
 
 
 
 
 
 
6967c22
 
 
 
 
 
 
 
 
 
 
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
"use server"

import { Credentials, listDatasets, whoAmI } from "@/lib/huggingface/hub/src"
import { ChannelInfo } from "@/types/general"

import { adminCredentials } from "../config"
import { parseChannel } from "./parseChannel"

export async function getPrivateChannels(options: {
  channelId?: string
  apiKey?: string
  owner?: string
  // ownerId?: string
  renewCache?: boolean
} = {}): Promise<ChannelInfo[]> {
  // console.log("getChannels")
  let credentials: Credentials = adminCredentials
  let owner = options?.owner || ""
  // let ownerId = options?.ownerId || ""

  if (options?.apiKey) {
    try {
      credentials = { accessToken: options.apiKey }
      const { id: userId, name: username } = await whoAmI({ credentials })
      if (!userId) {
        throw new Error(`couldn't get the id`)
      }
      if (!username) {
        throw new Error(`couldn't get the username`)
      }
      // everything is in order
      // ownerId = userId
      owner = username
    } catch (err) {
      console.error(err)
      return []
    }
  }

  let channels: ChannelInfo[] = []
  
  const prefix = "ai-tube-"

  let search = owner
    ? { owner } // search channels of a specific user
    : prefix // global search (note: might be costly?)

  // console.log("search:", search)
  
  for await (const { id, name, likes, updatedAt } of listDatasets({
    search,
    credentials,
    requestInit: options?.renewCache
    ? { cache: "no-store" }
    : undefined
  })) {
    if (options.channelId && options.channelId !== id) {
      continue
    }

    // TODO: need to handle better cases where the username is missing

    const chunks = name.split("/")
    const [_datasetUser, datasetName] = chunks.length === 2
      ? chunks
      : [name, name]

    // console.log(`found a candidate dataset "${datasetName}" owned by @${datasetUser}`)
    
    // ignore channels which don't start with ai-tube
    if (!datasetName.startsWith(prefix)) {
      continue
    }

    // ignore the video index
    if (datasetName === "ai-tube-index") {
      continue
    }

    const channel = await parseChannel({
      ...options,

      id,
      name,
      likes,
      updatedAt,

      // nope that doesn't work, it's the wrong owner
      // ownerId,
    })

    channels.push(channel)

    if (options.channelId && options.channelId === id) {
      break
    }
  }

  return channels
}