@vyla-entertainment/sdk 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,113 +1,187 @@
1
1
  import { USER_AGENT } from '../utils/helpers.js';
2
2
 
3
- const BASE_URL = "https://vidvault.ru";
3
+ const BASE_URL = 'https://vidvault.to';
4
+ const API_BASE = `${BASE_URL}/api`;
5
+ const DL_PROXY_BASE = 'https://dl.gemlelispe.workers.dev';
6
+ const SUB_PROXY_BASE = 'https://sub.k5s7sjozpn.workers.dev';
7
+
4
8
  const HEADERS = {
5
- "Referer": `${BASE_URL}/`,
6
- "Origin": BASE_URL,
7
- "User-Agent": USER_AGENT,
9
+ 'Referer': `${BASE_URL}/`,
10
+ 'Origin': BASE_URL,
11
+ 'User-Agent': USER_AGENT,
12
+ 'Accept': 'application/json, text/plain, */*',
13
+ 'Accept-Language': 'en-US,en;q=0.9',
8
14
  };
9
15
 
16
+ function formatBytes(bytes, decimals = 2) {
17
+ if (!bytes || bytes <= 0) return '0 B';
18
+ const k = 1024;
19
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
20
+ const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
21
+ return `${(bytes / Math.pow(k, i)).toFixed(decimals)} ${sizes[i]}`;
22
+ }
23
+
10
24
  async function getToken() {
11
- const res = await fetch(`${BASE_URL}/api/get-token`, {
12
- method: "GET",
13
- headers: HEADERS
25
+ const res = await fetch(`${API_BASE}/get-token`, {
26
+ method: 'GET',
27
+ headers: HEADERS,
28
+ signal: AbortSignal.timeout(10000),
14
29
  });
30
+ if (!res.ok) throw new Error(`Token fetch failed: ${res.status}`);
15
31
  const data = await res.json();
16
- return data.t;
32
+ return data?.t;
17
33
  }
18
34
 
19
35
  function getCaptionType(url) {
20
- return url.toLowerCase().includes(".vtt") ? "vtt" : "srt";
36
+ return String(url).toLowerCase().includes('.vtt') ? 'vtt' : 'srt';
21
37
  }
22
38
 
23
39
  export async function getStream(args) {
24
40
  const { id, s, e } = args;
25
- const type = (s != null && e != null) ? "tv" : "movie";
41
+ const isTv = s != null && e != null;
42
+ const type = isTv ? 'tv' : 'movie';
26
43
 
27
44
  try {
28
45
  const token = await getToken();
46
+ if (!token) return null;
47
+
48
+ const payload = {
49
+ type,
50
+ tmdbId: String(id),
51
+ };
29
52
 
30
- const payload = { type, tmdbId: String(id) };
31
- if (type === "tv") {
32
- payload.season = String(s);
33
- payload.episode = String(e);
53
+ if (isTv) {
54
+ payload.season = Number(s);
55
+ payload.episode = Number(e);
34
56
  }
35
57
 
36
- const res = await fetch(`${BASE_URL}/api/download-proxy`, {
37
- method: "POST",
58
+ const res = await fetch(`${API_BASE}/download-proxy`, {
59
+ method: 'POST',
38
60
  headers: {
39
61
  ...HEADERS,
40
- "Content-Type": "application/json",
41
- "x-request-token": token
62
+ 'Content-Type': 'application/json',
63
+ 'x-request-token': token,
42
64
  },
43
- body: JSON.stringify(payload)
65
+ body: JSON.stringify(payload),
66
+ signal: AbortSignal.timeout(15000),
44
67
  });
68
+
69
+ if (!res.ok) return null;
45
70
  const data = await res.json();
46
71
 
47
72
  const allUrls = [];
48
73
  const subtitles = [];
74
+ const titleTag = encodeURIComponent(isTv ? `Show_${id}_S${s}E${e}` : `Movie_${id}`);
49
75
 
50
76
  const mp4 = data?.mp4Data;
51
- if (mp4) {
52
- const country = mp4.country || "";
53
- const lanName = mp4.lanName || "";
54
- const detailPath = mp4.detailPath || "";
55
-
56
- const downloads = mp4.downloadInfo?.data?.downloads || [];
57
- for (const d of downloads) {
58
- if (!d?.url) continue;
77
+ const downloadData = mp4?.downloadInfo?.data || mp4?.data?.data || mp4?.data || mp4;
78
+
79
+ if (downloadData) {
80
+ const streams = downloadData.streams || downloadData.downloads || [];
81
+ for (const item of streams) {
82
+ if (!item?.url) continue;
83
+
84
+ const res = item.resolutions || item.resolution || 'Auto';
85
+ const sizeStr = item.size ? ` (${typeof item.size === 'number' ? formatBytes(item.size) : item.size})` : '';
86
+ const proxiedUrl = `${DL_PROXY_BASE}/${encodeURIComponent(item.url)}?n=${titleTag}`;
87
+
59
88
  allUrls.push({
60
- quality: `${d.resolution}p ${detailPath} ${country} ${lanName}`.trim(),
61
- url: d.url,
62
- type: "mp4",
63
- headers: HEADERS
89
+ url: proxiedUrl,
90
+ server: `VidVault - MP4 ${res}p${sizeStr}`.trim(),
91
+ quality: typeof res === 'number' ? `${res}p` : res,
92
+ type: 'mp4',
93
+ headers: HEADERS,
64
94
  });
65
95
  }
66
96
 
67
- const srtCaptions = mp4.downloadInfo?.data?.captions || [];
68
- for (const c of srtCaptions) {
69
- if (!c?.url) continue;
97
+ const captions = downloadData.captions || [];
98
+ for (const cap of captions) {
99
+ if (!cap?.url) continue;
100
+ const subUrl = `${SUB_PROXY_BASE}/?url=${encodeURIComponent(cap.url)}&title=${titleTag}`;
70
101
  subtitles.push({
71
- label: c.lanName || c.lan || "Unknown",
72
- type: getCaptionType(c.url),
73
- language: c.lan || "",
74
- url: c.url
102
+ label: cap.lanName || cap.lan || 'Unknown',
103
+ type: getCaptionType(cap.url),
104
+ language: cap.lan || '',
105
+ url: subUrl,
75
106
  });
76
107
  }
77
108
  }
78
109
 
79
110
  const mkvFiles = data?.mkvData?.files || [];
80
- for (const f of mkvFiles) {
81
- if (!f?.url) continue;
111
+ for (const file of mkvFiles) {
112
+ if (!file?.url) continue;
113
+ const sizeStr = file.size ? ` (${typeof file.size === 'number' ? formatBytes(file.size) : file.size})` : '';
82
114
  allUrls.push({
83
- quality: `MKV ${f.size || ""}`.trim(),
84
- url: f.url,
85
- type: "mp4",
86
- headers: HEADERS
115
+ url: file.url,
116
+ server: `VidVault - MKV 480p${sizeStr}`.trim(),
117
+ quality: '480p',
118
+ type: 'mp4',
119
+ headers: HEADERS,
87
120
  });
88
121
  }
89
122
 
90
123
  const mkvV2 = data?.mkvV2Data;
91
- if (mkvV2?.url) {
124
+ const mkvV2List = Array.isArray(mkvV2)
125
+ ? mkvV2
126
+ : Array.isArray(mkvV2?.files)
127
+ ? mkvV2.files
128
+ : (mkvV2?.url ? [mkvV2] : []);
129
+
130
+ for (const file of mkvV2List) {
131
+ if (!file?.url) continue;
132
+ const quality = file.quality ? String(file.quality).replace(/p$/i, '') : 'Auto';
133
+ const sizeStr = file.size ? ` (${typeof file.size === 'number' ? formatBytes(file.size) : file.size})` : '';
134
+ const meta = [file.country, file.language].filter(Boolean).join(' • ');
135
+ const metaStr = meta ? ` [${meta}]` : '';
136
+
92
137
  allUrls.push({
93
- quality: `${mkvV2.quality || ""} ${mkvV2.language || ""} ${mkvV2.country || ""} (${mkvV2.size || ""})`.trim(),
94
- url: mkvV2.url,
95
- type: "mp4",
96
- headers: HEADERS
138
+ url: file.url,
139
+ server: `VidVault - MKV v2 ${quality}p${sizeStr}${metaStr}`.trim(),
140
+ quality: `${quality}p`,
141
+ type: 'mp4',
142
+ headers: HEADERS,
97
143
  });
98
144
  }
99
145
 
100
146
  const mkvV3 = data?.mkvV3Data;
101
- if (mkvV3?.url) {
102
- allUrls.push({
103
- quality: `${mkvV3.quality || ""} ${mkvV3.language || ""} ${mkvV3.country || ""} (${mkvV3.size || ""})`.trim(),
104
- url: mkvV3.url,
105
- type: "mp4",
106
- headers: HEADERS
107
- });
147
+ if (mkvV3?.downloads && Array.isArray(mkvV3.downloads)) {
148
+ const country = mkvV3.country || '';
149
+ const language = mkvV3.language || '';
150
+
151
+ for (const down of mkvV3.downloads) {
152
+ if (Array.isArray(down?.qualities)) {
153
+ for (const qObj of down.qualities) {
154
+ for (const ep of qObj?.episodes || []) {
155
+ if (!ep?.url) continue;
156
+ const quality = qObj.quality ? String(qObj.quality).replace(/p$/i, '') : 'Auto';
157
+ const sizeStr = ep.size ? ` (${typeof ep.size === 'number' ? formatBytes(ep.size) : ep.size})` : '';
158
+ const meta = [ep.country || country, ep.language || language].filter(Boolean).join(' • ');
159
+ const metaStr = meta ? ` [${meta}]` : '';
160
+
161
+ allUrls.push({
162
+ url: ep.url,
163
+ server: `VidVault - MKV v3 ${quality}p${sizeStr}${metaStr}`.trim(),
164
+ quality: `${quality}p`,
165
+ type: 'mp4',
166
+ headers: HEADERS,
167
+ });
168
+ }
169
+ }
170
+ } else if (down?.url) {
171
+ const quality = down.quality ? String(down.quality).replace(/p$/i, '') : 'Auto';
172
+ const sizeStr = down.size ? ` (${typeof down.size === 'number' ? formatBytes(down.size) : down.size})` : '';
173
+ allUrls.push({
174
+ url: down.url,
175
+ server: `VidVault - MKV v3 ${quality}p${sizeStr}`.trim(),
176
+ quality: `${quality}p`,
177
+ type: 'mp4',
178
+ headers: HEADERS,
179
+ });
180
+ }
181
+ }
108
182
  }
109
183
 
110
- return allUrls.length ? { allUrls, subtitles } : null;
184
+ return allUrls.length ? { allUrls, subtitles: subtitles.length ? subtitles : undefined } : null;
111
185
  } catch (err) {
112
186
  return null;
113
187
  }
@@ -0,0 +1,129 @@
1
+ const BASE_URL = 'https://www.films365.org';
2
+ const HEADERS = {
3
+ Authorization: 'Bearer 79a02956be35835728a044b11e2ae793149d45fb2c89cb6d029ec01aac19bfdb',
4
+ 'Content-Type': 'application/json',
5
+ 'User-Agent': 'MovieDownloader/1.0',
6
+ };
7
+
8
+ async function resolveTitle(sdk, id, isTv) {
9
+ const apiKey = sdk?.tmdbApiKey || process.env.TMDB_API_KEY;
10
+ if (!apiKey) return null;
11
+ const type = isTv ? 'tv' : 'movie';
12
+ try {
13
+ const res = await fetch(`https://api.themoviedb.org/3/${type}/${id}?api_key=${apiKey}`, {
14
+ signal: AbortSignal.timeout(6000),
15
+ });
16
+ if (!res.ok) return null;
17
+ const data = await res.json();
18
+ return isTv ? data.name : data.title;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ export async function getStream({ id, s, e, sdk }) {
25
+ const isTv = Boolean(s && e);
26
+ const targetType = isTv ? 'tv' : 'movie';
27
+
28
+ const title = await resolveTitle(sdk, id, isTv);
29
+ const query = title || String(id);
30
+
31
+ const searchRes = await fetch(`${BASE_URL}/api/mobile/search`, {
32
+ method: 'POST',
33
+ headers: HEADERS,
34
+ body: JSON.stringify({ query }),
35
+ signal: AbortSignal.timeout(8000),
36
+ });
37
+
38
+ if (!searchRes.ok) return null;
39
+ const searchJson = await searchRes.json();
40
+ const resultsObj = searchJson?.results;
41
+ if (!resultsObj) return null;
42
+
43
+ const items = resultsObj.all || (targetType === 'tv' ? resultsObj.tvs : resultsObj.movies) || [];
44
+ if (!Array.isArray(items) || items.length === 0) return null;
45
+
46
+ const cleanSearchTitle = query.toLowerCase().replace(/[^a-z0-9]/g, '');
47
+ let matchedItem = null;
48
+
49
+ for (const item of items) {
50
+ const itemType = String(item?.type || '').toLowerCase();
51
+ if (itemType && itemType !== targetType) continue;
52
+
53
+ const itemTitle = String(item?.title || '');
54
+ const cleanItemTitle = itemTitle.toLowerCase().replace(/[^a-z0-9]/g, '');
55
+
56
+ if (cleanItemTitle === cleanSearchTitle || cleanItemTitle.includes(cleanSearchTitle)) {
57
+ matchedItem = item;
58
+ break;
59
+ }
60
+ }
61
+
62
+ if (!matchedItem) {
63
+ matchedItem = items.find(i => String(i?.type || '').toLowerCase() === targetType) || items[0];
64
+ }
65
+
66
+ const itemId = matchedItem?.id || matchedItem?.tmdbId;
67
+ if (!itemId) return null;
68
+
69
+ const detailsRes = await fetch(`${BASE_URL}/api/mobile/details?id=${itemId}&type=${targetType}`, {
70
+ headers: HEADERS,
71
+ signal: AbortSignal.timeout(8000),
72
+ });
73
+
74
+ if (!detailsRes.ok) return null;
75
+ const detailsJson = await detailsRes.json();
76
+ const data = detailsJson?.data;
77
+ if (!data) return null;
78
+
79
+ const spoken = Array.isArray(data.spokenLanguages)
80
+ ? data.spokenLanguages.map(l => String(l).trim()).filter(Boolean)
81
+ : [];
82
+ const langSuffix = spoken.length > 0 ? ` · ${spoken.join(', ')}` : '';
83
+
84
+ const allUrls = [];
85
+
86
+ if (!isTv) {
87
+ const streamUrl = data.downloadUrl || data.videoUrl;
88
+ if (streamUrl && typeof streamUrl === 'string') {
89
+ allUrls.push({
90
+ url: streamUrl.trim(),
91
+ label: `X-Downloader${langSuffix}`,
92
+ headers: {
93
+ 'User-Agent': HEADERS['User-Agent'],
94
+ },
95
+ });
96
+ }
97
+ } else {
98
+ const seasonNum = Number(s);
99
+ const episodeNum = Number(e);
100
+ const seasons = Array.isArray(data.seasons) ? data.seasons : [];
101
+ const targetSeason = seasons.find(sn => Number(sn.seasonNumber) === seasonNum);
102
+
103
+ if (targetSeason) {
104
+ const episodes = Array.isArray(targetSeason.episodes) ? targetSeason.episodes : [];
105
+ const targetEp = episodes.find(ep => Number(ep.episodeNumber) === episodeNum);
106
+
107
+ if (targetEp) {
108
+ const streamUrl = targetEp.downloadUrl || targetEp.videoUrl;
109
+ if (streamUrl && typeof streamUrl === 'string') {
110
+ allUrls.push({
111
+ url: streamUrl.trim(),
112
+ label: `X-Downloader (S${seasonNum}E${episodeNum})${langSuffix}`,
113
+ headers: {
114
+ 'User-Agent': HEADERS['User-Agent'],
115
+ },
116
+ });
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ if (allUrls.length === 0) return null;
123
+
124
+ return {
125
+ url: allUrls[0].url,
126
+ allUrls,
127
+ headers: allUrls[0].headers,
128
+ };
129
+ }
package/src/subtitles.js CHANGED
@@ -3,36 +3,24 @@ import { getUA } from './utils/helpers.js';
3
3
  const SUBTITLE_BASES = [
4
4
  'https://sub.vdrk.site/v1',
5
5
  'https://sub.vdrk.site/v2',
6
- 'https://fed-subs.pstream.mov'
6
+ 'https://opensubtitles-v3.strem.io'
7
7
  ];
8
- const VYLIAN_MESSAGES = [
9
- "Thanks for using Vyla!"
10
- ];
11
-
12
- function generateVylianVtt() {
13
- let vttContent = 'WEBVTT\n\n';
14
-
15
- let currentTime = 1;
16
- while (currentTime <= 7200) {
17
- const duration = Math.floor(Math.random() * 4) + 1;
18
- const message = VYLIAN_MESSAGES[Math.floor(Math.random() * VYLIAN_MESSAGES.length)];
19
-
20
- const startTime = formatVttTime(currentTime);
21
- const endTime = formatVttTime(currentTime + duration);
22
8
 
23
- vttContent += `${startTime} --> ${endTime}\n${message}\n\n`;
24
-
25
- currentTime += duration + Math.floor(Math.random() * 60) + 30;
9
+ async function resolveImdbId(id, isTv) {
10
+ if (typeof id === 'string' && id.startsWith('tt')) return id;
11
+ const apiKey = process.env.TMDB_API_KEY;
12
+ if (!apiKey) return `tt${id}`;
13
+ const type = isTv ? 'tv' : 'movie';
14
+ try {
15
+ const res = await fetch(`https://api.themoviedb.org/3/${type}/${id}?api_key=${apiKey}&append_to_response=external_ids`, {
16
+ signal: AbortSignal.timeout(5000),
17
+ });
18
+ if (!res.ok) return `tt${id}`;
19
+ const data = await res.json();
20
+ return data.imdb_id || data.external_ids?.imdb_id || `tt${id}`;
21
+ } catch {
22
+ return `tt${id}`;
26
23
  }
27
-
28
- return vttContent;
29
- }
30
-
31
- function formatVttTime(seconds) {
32
- const hours = Math.floor(seconds / 3600);
33
- const minutes = Math.floor((seconds % 3600) / 60);
34
- const secs = seconds % 60;
35
- return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}.000`;
36
24
  }
37
25
 
38
26
  export async function fetchSubtitles(paths = []) {
@@ -42,7 +30,7 @@ export async function fetchSubtitles(paths = []) {
42
30
  try {
43
31
  const res = await fetch(`${base}${path}`, {
44
32
  headers: { 'User-Agent': getUA() },
45
- signal: AbortSignal.timeout(5000),
33
+ signal: AbortSignal.timeout(6000),
46
34
  });
47
35
 
48
36
  if (!res.ok) {
@@ -63,6 +51,20 @@ export async function fetchSubtitles(paths = []) {
63
51
  : [];
64
52
  }
65
53
 
54
+ if (base.includes('opensubtitles-v3.strem.io')) {
55
+ if (!Array.isArray(data?.subtitles)) return [];
56
+ return data.subtitles.map(sub => {
57
+ if (!sub?.url) return null;
58
+ const isSrt = sub.url.toLowerCase().endsWith('.srt');
59
+ return {
60
+ label: sub.lang ? sub.lang.toUpperCase() : 'OpenSubtitles',
61
+ file: sub.url,
62
+ type: isSrt ? 'srt' : 'vtt',
63
+ source: 'opensubtitles'
64
+ };
65
+ }).filter(Boolean);
66
+ }
67
+
66
68
  if (base.includes('fed-subs.pstream.mov')) {
67
69
  if (!data?.subtitles || typeof data.subtitles !== 'object') return [];
68
70
 
@@ -93,34 +95,27 @@ export async function fetchSubtitles(paths = []) {
93
95
  })
94
96
  );
95
97
 
96
- const val = results.flat();
97
-
98
- val.push({
99
- label: 'Vylian',
100
- file: 'data:text/vtt;base64,' + Buffer.from(generateVylianVtt()).toString('base64'),
101
- type: 'vtt',
102
- source: 'easter-egg'
103
- });
104
-
105
- return val;
98
+ return results.flat();
106
99
  } catch {
107
100
  return [];
108
101
  }
109
102
  }
110
103
 
111
104
  export async function getSubPathsMovie(id) {
105
+ const imdbId = await resolveImdbId(id, false);
112
106
  return [
113
107
  { base: SUBTITLE_BASES[0], path: `/movie/${id}` },
114
108
  { base: SUBTITLE_BASES[1], path: `/movie/${id}` },
115
- { base: SUBTITLE_BASES[2], path: `/movie/tt${id}` }
109
+ { base: SUBTITLE_BASES[2], path: `/subtitles/movie/${imdbId}.json` }
116
110
  ];
117
111
  }
118
112
 
119
113
  export async function getSubPathsTv(id, season, episode) {
114
+ const imdbId = await resolveImdbId(id, true);
120
115
  return [
121
116
  { base: SUBTITLE_BASES[0], path: `/tv/${id}/${season}/${episode}` },
122
117
  { base: SUBTITLE_BASES[1], path: `/tv/${id}/${season}/${episode}` },
123
- { base: SUBTITLE_BASES[2], path: `/tv/tt${id}/${season}/${episode}` }
118
+ { base: SUBTITLE_BASES[2], path: `/subtitles/series/${imdbId}:${season}:${episode}.json` }
124
119
  ];
125
120
  }
126
121
 
@@ -1,63 +0,0 @@
1
- const BASE = "https://trendimovies.com";
2
-
3
- const HEADERS = {
4
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
5
- Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
6
- "Accept-Language": "en-US,en;q=0.9",
7
- "Referer": "https://trendimovies.com/",
8
- };
9
-
10
- async function fetchPage(path) {
11
- const res = await fetch(`${BASE}${path}`, { headers: HEADERS });
12
- if (!res.ok) throw new Error(`trendimovies ${res.status}`);
13
- return res.text();
14
- }
15
-
16
- function parseLinks(html) {
17
- const m = html.match(/DownloadSection[^>]*props="([^"]+)"/s) ||
18
- html.match(/props="([^"]+)"[^>]*ssr[^>]*client="load"[^>]*opts="[^"]*DownloadSection/s);
19
- if (!m) {
20
- const alt = html.match(/&quot;DownloadSection&quot;/);
21
- if (!alt) return [];
22
- const propsMatch = html.match(/props="({[^"]*DownloadSection[^"]*})"/s);
23
- if (!propsMatch) return [];
24
- return extractLinks(propsMatch[1].replace(/&quot;/g, '"').replace(/&#39;/g, "'"));
25
- }
26
- return extractLinks(m[1].replace(/&quot;/g, '"').replace(/&#39;/g, "'"));
27
- }
28
-
29
- function extractLinks(propsJson) {
30
- try {
31
- const parsed = JSON.parse(propsJson);
32
- const rawLinks = parsed?.links?.[1];
33
- if (!Array.isArray(rawLinks)) return [];
34
- return rawLinks
35
- .map(item => item?.[1])
36
- .filter(l => l && typeof l === "object")
37
- .map(l => ({
38
- url: unwrap(l.url),
39
- quality: unwrap(l.quality) || "HD",
40
- size: unwrap(l.file_size) || null,
41
- type: "mkv",
42
- active: unwrap(l.is_active) !== false,
43
- }))
44
- .filter(l => l.url && l.active);
45
- } catch {
46
- return [];
47
- }
48
- }
49
-
50
- function unwrap(v) {
51
- if (Array.isArray(v) && v.length === 2 && (v[0] === 0 || v[0] === 1)) return v[1];
52
- return v;
53
- }
54
-
55
- export async function getDownloads(tmdbId) {
56
- const html = await fetchPage(`/movie/${tmdbId}`);
57
- return parseLinks(html);
58
- }
59
-
60
- export async function getDownloadsTv(tmdbId, season, episode) {
61
- const html = await fetchPage(`/tv/${tmdbId}/season/${season}/episode/${episode}`);
62
- return parseLinks(html);
63
- }
@@ -1,70 +0,0 @@
1
- import { getTmdbInfo, fetchJson } from '../utils/helpers.js';
2
-
3
- const BASE_URL = "https://ani.pm";
4
-
5
- function cleanTitle(t) { return t ? t.toLowerCase().replace(/[^a-z0-9]/g, '') : ''; }
6
-
7
- async function searchCatalog(query) {
8
- try {
9
- const data = await fetchJson(`${BASE_URL}/api/anime/catalog?q=${encodeURIComponent(query)}&page=1`, { signal: AbortSignal.timeout(6000) });
10
- return Array.isArray(data?.items) ? data.items : [];
11
- } catch { return []; }
12
- }
13
-
14
- async function resolveEntry(titles, year) {
15
- const orderedTitles = titles.length > 1 ? [...titles].reverse() : titles;
16
- let best = null, bestScore = -1;
17
- for (const title of orderedTitles) {
18
- const items = await searchCatalog(title);
19
- const targetClean = cleanTitle(title);
20
- for (const item of items) {
21
- const itemTitles = [item.title, item.native].filter(Boolean).map(cleanTitle);
22
- let score = 0;
23
- if (itemTitles.some(t => t === targetClean)) score += 5;
24
- else if (itemTitles.some(t => t.includes(targetClean) || targetClean.includes(t))) score += 3;
25
- else continue;
26
- if (item.type === 'TV') score += 4;
27
- else if (item.type === 'Movie' || item.type === 'Special' || item.type === 'ONA') score -= 2;
28
- if (year && item.year) {
29
- const diff = Math.abs(item.year - year);
30
- if (diff === 0) score += 3;
31
- else if (diff === 1) score += 1;
32
- else if (diff > 2) score -= 3;
33
- }
34
- if (score > bestScore) { bestScore = score; best = item; }
35
- }
36
- if (bestScore >= 9) break;
37
- }
38
- return best;
39
- }
40
-
41
- export async function getStream({ id, s, e, audio }) {
42
- try {
43
- const info = await getTmdbInfo(id, s ? 'tv' : 'movie', s);
44
- if (!info || !info.isAnime) return null;
45
- const entry = await resolveEntry(info.titles, info.year);
46
- if (!entry) return null;
47
- const episodeNum = e || 1;
48
- const params = new URLSearchParams({ title: entry.title || '', ep: String(episodeNum) });
49
- if (entry.year) params.set('year', entry.year);
50
- if (entry.anilistId) params.set('anilistId', entry.anilistId);
51
- if (entry.malId) params.set('malId', entry.malId);
52
- const servers = await fetchJson(`${BASE_URL}/api/anime/src/servers?${params}`, { signal: AbortSignal.timeout(10000) });
53
- if (!servers) return null;
54
- const audiosToTry = audio === "all" ? ["sub", "dub"] : (audio === "dub" ? ["dub", "sub"] : ["sub", "dub"]);
55
- for (const aud of audiosToTry) {
56
- const list = servers[aud];
57
- if (!Array.isArray(list) || !list.length) continue;
58
- const allUrls = list.filter(srv => (srv.kind === "hls" || srv.kind === "file") && srv.url)
59
- .sort((a, b) => (b.priority || 0) - (a.priority || 0))
60
- .map(srv => ({ url: srv.url.startsWith('/') ? `${BASE_URL}${srv.url}` : srv.url, type: srv.kind === "hls" ? "hls" : "mp4", audio: aud, server: srv.provider ? `AniPM-${srv.provider}` : "AniPM", headers: { Referer: `${BASE_URL}/`, Origin: BASE_URL }, skipProxy: false }));
61
- if (allUrls.length) return { allUrls };
62
- }
63
- return null;
64
- } catch { return null; }
65
- }
66
-
67
- export async function getSources(args) {
68
- const stream = await getStream(args);
69
- return stream?.allUrls ? [...new Set(stream.allUrls.map(u => u.server))] : [];
70
- }