summaryrefslogtreecommitdiff
path: root/src/lib/api/youtube.ts
blob: 8ade3c5435bc8439c2340949cc1b8340fb2dea28 (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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
export interface VideoThumbnail {
  url: string;
  width?: number;
  height?: number;
}

export interface VideoInfo {
  videoId: string;
  title: string;
  author: string;
  authorId: string;
  videoThumbnails: VideoThumbnail[];
  description: string;
  viewCount: number;
  publishedText: string;
  lengthSeconds: number;
}

export interface VideoFormat {
  formatId: string;
  url: string;
  ext: string;
  resolution?: string;
  height?: number;
  width?: number;
  qualityLabel?: string;
}

export interface VideoDetails extends VideoInfo {
  likeCount?: number;
  formats: VideoFormat[];
}

export interface ChannelInfo {
  author: string;
  authorId: string;
  authorThumbnails: VideoThumbnail[];
  subCount: number;
  description: string;
  videos: VideoInfo[];
}

interface YtdlpSearchResult {
  id: string;
  title: string;
  channel: string;
  channel_id: string;
  thumbnail: string;
  thumbnails: { url: string; width?: number; height?: number }[];
  duration: number;
  view_count: number;
  upload_date: string;
}

interface YtdlpVideo {
  id: string;
  title: string;
  description: string;
  channel: string;
  channel_id: string;
  thumbnail: string;
  thumbnails: { url: string; width?: number; height?: number }[];
  duration: number;
  view_count: number;
  upload_date: string;
  like_count?: number;
  formats: {
    format_id: string;
    url: string;
    ext: string;
    resolution?: string;
    height?: number;
    width?: number;
    format_note?: string;
  }[];
}

interface YtdlpChannel {
  id: string;
  channel: string;
  channel_id: string;
  description: string;
  channel_follower_count: number;
  thumbnails: { url: string; width?: number; height?: number }[];
  entries?: YtdlpSearchResult[];
}

function formatUploadDate(dateStr: string): string {
  if (!dateStr || dateStr.length !== 8) return '';
  const year = dateStr.slice(0, 4);
  const month = dateStr.slice(4, 6);
  const day = dateStr.slice(6, 8);
  const date = new Date(`${year}-${month}-${day}`);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) return 'Today';
  if (days === 1) return 'Yesterday';
  if (days < 7) return `${days} days ago`;
  if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
  if (days < 365) return `${Math.floor(days / 30)} months ago`;
  return `${Math.floor(days / 365)} years ago`;
}

function transformSearchResult(item: YtdlpSearchResult): VideoInfo {
  return {
    videoId: item.id,
    title: item.title,
    author: item.channel,
    authorId: item.channel_id,
    videoThumbnails: item.thumbnails?.length
      ? item.thumbnails
      : [{ url: item.thumbnail }],
    description: '',
    viewCount: item.view_count || 0,
    publishedText: formatUploadDate(item.upload_date),
    lengthSeconds: item.duration || 0
  };
}

function transformVideo(item: YtdlpVideo): VideoDetails {
  return {
    videoId: item.id,
    title: item.title,
    author: item.channel,
    authorId: item.channel_id,
    videoThumbnails: item.thumbnails?.length
      ? item.thumbnails
      : [{ url: item.thumbnail }],
    description: item.description || '',
    viewCount: item.view_count || 0,
    publishedText: formatUploadDate(item.upload_date),
    lengthSeconds: item.duration || 0,
    likeCount: item.like_count,
    formats: item.formats.map(f => ({
      formatId: f.format_id,
      url: f.url,
      ext: f.ext,
      resolution: f.resolution,
      height: f.height,
      width: f.width,
      qualityLabel: f.format_note || (f.height ? `${f.height}p` : undefined)
    }))
  };
}

function transformChannel(item: YtdlpChannel): ChannelInfo {
  return {
    author: item.channel,
    authorId: item.channel_id,
    authorThumbnails: item.thumbnails || [],
    subCount: item.channel_follower_count || 0,
    description: item.description || '',
    videos: (item.entries || []).map(transformSearchResult)
  };
}

export async function search(query: string): Promise<VideoInfo[]> {
  const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
  if (!response.ok) {
    throw new Error('Search failed');
  }
  const results: YtdlpSearchResult[] = await response.json();
  return results.map(transformSearchResult);
}

export async function getVideo(videoId: string): Promise<VideoDetails> {
  const response = await fetch(`/api/video/${videoId}`);
  if (!response.ok) {
    throw new Error('Failed to fetch video');
  }
  const video: YtdlpVideo = await response.json();
  return transformVideo(video);
}

export async function getChannel(channelId: string): Promise<ChannelInfo> {
  const response = await fetch(`/api/channel/${encodeURIComponent(channelId)}`);
  if (!response.ok) {
    throw new Error('Failed to fetch channel');
  }
  const channel: YtdlpChannel = await response.json();
  return transformChannel(channel);
}

export async function getTrending(): Promise<VideoInfo[]> {
  const response = await fetch('/api/trending');
  if (!response.ok) {
    throw new Error('Failed to fetch trending');
  }
  const results: YtdlpSearchResult[] = await response.json();
  return results.map(transformSearchResult);
}

export async function getRelatedVideos(videoId: string): Promise<VideoInfo[]> {
  const response = await fetch(`/api/related/${videoId}`);
  if (!response.ok) {
    throw new Error('Failed to fetch related videos');
  }
  const results: YtdlpSearchResult[] = await response.json();
  return results.map(transformSearchResult);
}

export interface ImportedPlaylist {
  id: string;
  title: string;
  channel: string;
  channelId: string;
  videos: VideoInfo[];
}

export async function importPlaylist(playlistUrl: string): Promise<ImportedPlaylist> {
  const response = await fetch(`/api/playlist?url=${encodeURIComponent(playlistUrl)}`);
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || 'Failed to import playlist');
  }
  const data = await response.json();
  return {
    id: data.id,
    title: data.title,
    channel: data.channel,
    channelId: data.channel_id,
    videos: data.entries.map(transformSearchResult)
  };
}

export function formatDuration(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`;
}

export function formatViews(views: number): string {
  if (views >= 1000000) {
    return `${(views / 1000000).toFixed(1)}M views`;
  }
  if (views >= 1000) {
    return `${(views / 1000).toFixed(1)}K views`;
  }
  return `${views} views`;
}

export function getBestThumbnail(thumbnails: VideoThumbnail[]): string {
  if (!thumbnails || thumbnails.length === 0) return '';
  const sorted = [...thumbnails].sort((a, b) => (b.width || 0) - (a.width || 0));
  return sorted[0]?.url || '';
}