File size: 5,322 Bytes
2276d59
62527b4
2276d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62527b4
2276d59
62527b4
2276d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Response } from 'express';
import { logger } from '../infra/logger.util.js';
import {
  VideoInfo,
  SpotifyMetadata,
  FinalResponse,
} from '../../types/index.js';
import { FinalResponseSchema } from '../../../../shared/schemas/media.schema.js';
import {
  processVideoFormats,
  processAudioFormats,
} from '../media/format.util.js';
import {
  normalizeTitle,
  normalizeArtist,
  getBestThumbnail,
  proxyThumbnailIfNeeded,
} from '../../services/social.service.js';

async function _resolveThumbnail(
  info: VideoInfo,
  isSpotify: boolean,
  spotifyData: SpotifyMetadata | null,
  videoURL: string
): Promise<string> {
  const spotifyImg =
    spotifyData?.cover ||
    spotifyData?.thumbnail ||
    info?.thumbnail ||
    info?.cover;
  let finalThumbnail = getBestThumbnail(info);

  if (isSpotify && spotifyImg) {
    finalThumbnail = await proxyThumbnailIfNeeded(spotifyImg, videoURL);
  } else {
    finalThumbnail = await proxyThumbnailIfNeeded(finalThumbnail, videoURL);
  }
  return finalThumbnail || '/logo.webp';
}

function _getSpotifyPayload(
  info: VideoInfo,
  spotifyData: SpotifyMetadata,
  videoURL: string
) {
  return {
    id: info.id || spotifyData.id || videoURL,
    title: spotifyData.title || info.title,
    artist: spotifyData.artist || info.artist || 'Unknown',
    uploader: spotifyData.artist || info.artist || info.uploader,
    album: spotifyData.album || info.album || '',
    previewUrl: spotifyData.previewUrl || info.previewUrl,
  };
}

function _mapFinalMetadata(
  info: VideoInfo,
  spotifyData: SpotifyMetadata | null,
  finalTitle: string,
  finalArtist: string,
  finalThumbnail: string,
  isSpotify: boolean,
  videoURL: string
): FinalResponse {
  const isPartial = Boolean(info.isPartial);
  const isIsrcMatch = Boolean(info.isIsrcMatch);
  const isJsInfo = Boolean(info.isJsInfo);

  // youtube keeps raw title; social normalized
  const isYouTube =
    videoURL.includes('youtube.com') || videoURL.includes('youtu.be');

  const base =
    isSpotify && spotifyData
      ? _getSpotifyPayload(info, spotifyData, videoURL)
      : {
          id: info.id || videoURL,
          title: isYouTube
            ? info.title || finalTitle
            : finalTitle || info.title,
          artist: finalArtist || info.artist || 'Unknown',
          uploader: finalArtist || info.artist || info.uploader,
          album: info.album || '',
          previewUrl: info.previewUrl || null,
        };

  const payload = {
    ...base,
    cover: finalThumbnail,
    thumbnail: finalThumbnail,
    duration: info.duration,
    formats: processVideoFormats(info),
    // keep audio split out by normalizers
    audioFormats: info.audioFormats?.length
      ? info.audioFormats
      : processAudioFormats(info),
    spotifyMetadata: spotifyData
      ? { ...spotifyData, type: 'spotify' as const }
      : undefined,
    isPartial,
    isrc: spotifyData?.isrc || info.isrc,
    isIsrcMatch,
    isJsInfo,
    webpageUrl: videoURL,
  };

  return FinalResponseSchema.parse(payload);
}

export async function prepareFinalResponse(
  info: VideoInfo,
  isSpotify: boolean,
  spotifyData: SpotifyMetadata | null,
  videoURL: string
): Promise<FinalResponse> {
  const finalThumbnail = await _resolveThumbnail(
    info,
    isSpotify,
    spotifyData,
    videoURL
  );
  const finalTitle = normalizeTitle(info);
  const finalArtist = normalizeArtist(info);

  if (isSpotify) {
    const preview = spotifyData?.previewUrl || info.previewUrl;
    if (preview) {
      logger.info(`[Response] Sending Preview: ${preview.substring(0, 50)}...`);
    } else {
      logger.info(
        `[Response] No Preview found for ${spotifyData?.title || info.title}`
      );
    }
  }

  return _mapFinalMetadata(
    info,
    spotifyData,
    finalTitle,
    finalArtist,
    finalThumbnail,
    isSpotify,
    videoURL
  );
}

export function prepareBrainResponse(spotifyData: SpotifyMetadata) {
  const duration =
    spotifyData.duration ||
    (spotifyData.audioFeatures?.duration_ms
      ? spotifyData.audioFeatures.duration_ms / 1000
      : 0);

  return {
    title: spotifyData.title,
    artist: spotifyData.artist,
    album: spotifyData.album,
    cover: spotifyData.cover || '/logo.webp',
    thumbnail: spotifyData.thumbnail || '/logo.webp',
    duration,
    previewUrl: spotifyData.previewUrl,
    formats: spotifyData.formats ?? [],
    audioFormats: spotifyData.audioFormats ?? [],
    spotifyMetadata: spotifyData,
  };
}

export function setupConvertResponse(
  res: Response,
  filename: string,
  format: string,
  _size = 0
) {
  const mimeTypes: Record<string, string> = {
    mp3: 'audio/mpeg',
    m4a: 'audio/mp4',
    mp4: 'video/mp4',
    opus: 'audio/opus',
    ogg: 'audio/ogg',
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    png: 'image/png',
  };

  const safeName = encodeURIComponent(filename);
  const asciiName = filename.replaceAll(/[^\u0020-\u007E]/gu, '');

  res.setHeader(
    'Content-Disposition',
    `attachment; filename="${asciiName.replaceAll('"', '')}"; filename*=UTF-8''${safeName}`
  );
  res.setHeader(
    'Content-Type',
    mimeTypes[format] || 'application/octet-stream'
  );

  res.setHeader(
    'Cache-Control',
    'no-store, no-cache, must-revalidate, proxy-revalidate'
  );
  res.setHeader('Accept-Ranges', 'bytes');
}