feat(torrents): add Galaxy (TorrentGalaxy) provider with IMDb-first search and inline magnets

- new tg parser: /imdb-detail/<tt...> when an IMDb id is available (exact title, local seeder/size sort), keyword search as fallback; rows carry full magnets inline so Play works without a second fetch
- wire tg into /api/torrents and /api/magnet, TG_HOST env (default https://torrentgalaxy.info)
- Galaxy tab in the torrents modal; tabs now share equal space and hidden-scroll on overflow
- fix tab drag&drop: reorder on the sanitized order so tabs added later (like Galaxy) can be dragged
This commit is contained in:
ner committed 2026-10-25 18:24:08 +02:00
1 parent fb645b75a5
commit c41f1f098f
8 files changed
+184 -9

No files matched your search

+5 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import odc from '@/data/parsers/odc';
import tg from '@/data/parsers/tg';
import tlk from '@/data/parsers/tlk';
export async function GET({ nextUrl: { searchParams } }: NextRequest) {
@@ -8,7 +9,10 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const provider = searchParams.get('provider') as string;
try {
return NextResponse.json(provider === 'odc' ? await odc.magnet(url) : await tlk.magnet(url));
const magnet =
provider === 'odc' ? await odc.magnet(url) : provider === 'tg' ? await tg.magnet(url) : await tlk.magnet(url);
return NextResponse.json(magnet);
} catch (error) {
return NextResponse.error();
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { Sort } from '@/data/parsers';
import odc from '@/data/parsers/odc';
import tg from '@/data/parsers/tg';
import tlk from '@/data/parsers/tlk';
import tpb from '@/data/parsers/tpb';
import yts from '@/data/parsers/yts';
@@ -16,7 +17,7 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const sort = searchParams.get('sort') as Sort;
const type = searchParams.get('type') as 'movie' | 'tv' | null;
const providers = { yts, tpb, tlk, odc };
const providers = { yts, tpb, tg, tlk, odc };
try {
const torrents = await providers[key].search({ imdbID, query, sort, type: type ?? undefined });
@@ -20,6 +20,12 @@ export const providers = {
queryFn: (options: Options) => queryFn({ ...options, key: 'tpb' }),
sortable: true
},
tg: {
label: 'Galaxy',
key: 'tg',
queryFn: (options: Options) => queryFn({ ...options, key: 'tg' }),
sortable: true
},
tlk: {
label: 'Toloka',
key: 'tlk',
@@ -34,7 +34,7 @@ const SortableTabsTrigger: FC<{ provider: (typeof providers)[ProviderKey]; isLoa
ref={setNodeRef}
value={provider.key}
style={{ transform: CSS.Transform.toString(transform), transition }}
className={cn('min-h-8 touch-none', isDragging && 'z-10 opacity-50')}
className={cn('min-h-8 min-w-fit flex-1 touch-none', isDragging && 'z-10 opacity-50')}
{...listeners}
>
{isLoading ? <Loader className='animate-spin' size={14} /> : provider.label}
@@ -77,6 +77,15 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
type: show.type,
show: tracked
});
const tg = useTorrents({
query,
queryFn: providers.tg.queryFn,
sort,
key: providers.tg.key,
imdbID: show.imdb_id!,
type: show.type,
show: tracked
});
const tlk = useTorrents({
query: scopedQuery,
queryFn: providers.tlk.queryFn,
@@ -87,7 +96,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
show: tracked
});
const queries = { yts, tpb, tlk };
const queries = { yts, tpb, tg, tlk };
const { order, ...dndProps } = useProvidersOrder();
@@ -117,7 +126,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
<Button
type='submit'
className='h-full !px-3 transition-all duration-200 hover:bg-secondary-foreground hover:shadow-lg hover:shadow-secondary-foreground/60'
disabled={tpb.isPending || tlk.isPending}
disabled={tpb.isPending || tg.isPending || tlk.isPending}
>
<Search size={16} />
</Button>
@@ -126,7 +135,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
<Tabs defaultValue={tabs[0].provider.key} className='w-full rounded-none px-2'>
<DndContext {...dndProps}>
<SortableContext items={visibleOrder} strategy={horizontalListSortingStrategy}>
<TabsList className={cn('grid w-full', isSeries ? 'grid-cols-2' : 'grid-cols-3')}>
<TabsList className='no-scrollbar flex w-full overflow-x-auto'>
{tabs.map(({ provider, query }) => (
<SortableTabsTrigger key={provider.key} provider={provider} isLoading={query.isLoading} />
))}
@@ -32,12 +32,14 @@ const useProvidersOrder = () => {
if (!over || active.id === over.id) return;
void setOrder((current) => {
const activeIndex = current.indexOf(active.id as ProviderKey);
const overIndex = current.indexOf(over.id as ProviderKey);
const order = sanitize(current);
const activeIndex = order.indexOf(active.id as ProviderKey);
const overIndex = order.indexOf(over.id as ProviderKey);
if (activeIndex === -1 || overIndex === -1) return current;
return arrayMove(current, activeIndex, overIndex);
return arrayMove(order, activeIndex, overIndex);
});
};
+151
View File
@@ -0,0 +1,151 @@
import axios, { AxiosInstance } from 'axios';
import { load } from 'cheerio';
import torrentTitle from 'parse-torrent-title';
import { TG_HOST } from '@/env';
import { Sort } from '../index';
const UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
const CATEGORIES = { movie: 'Movies', tv: 'TV' } as const;
type ShowType = 'movie' | 'tv';
export class TorrentGalaxy {
private client: AxiosInstance;
constructor() {
this.client = axios.create({
baseURL: TG_HOST || 'https://torrentgalaxy.info',
headers: {
'User-Agent': UA,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9'
}
});
}
private buildSearchUrl(query: string, type?: ShowType, sort = Sort.seeds) {
const parts = [`keywords:${encodeURIComponent(query)}`];
if (type && type in CATEGORIES) parts.push(`category:${CATEGORIES[type]}`);
parts.push(`order:-${sort === Sort.seeds ? 'se' : 's'}`);
return `/get-posts/${parts.join(':')}/`;
}
private parseRows(data: string) {
const $ = load(data);
return $('div.tgxtablecell[data-href^="/post-detail/"]')
.map((_, cell) => {
const $cell = $(cell);
const row = $cell.parent();
const originalTitle = $cell.find('a[title]').first().attr('title') || $cell.find('a').first().text().trim();
const size = row
.find('.badge.badge-secondary')
.map((__, el) => $(el).text().replace(/\s+/g, ' ').trim())
.get()
.find((text) => /[GMK]B/.test(text));
const seeds = row
.find('span[title="Seeders/Leechers"]')
.first()
.text()
.match(/(\d+)\s*\/\s*(\d+)/);
const magnet = row.find('a[href^="magnet:"]').first().attr('href') || '';
const hash = /urn:btih:([0-9a-fA-F]{40})/.exec(magnet)?.[1] ?? '';
const { title, resolution, source, codec, container, season, episode, year } = torrentTitle.parse(
originalTitle || ''
);
return {
year: year?.toString(),
source,
codec,
container,
originalTitle,
title,
episodes: season && episode ? `S${season}:E${episode}` : undefined,
id: $cell.attr('data-href') || originalTitle || '',
size,
seeders: parseInt(seeds?.[1] || '0', 10),
quality: resolution,
magnet,
download: $cell.attr('data-href') || '',
hash
};
})
.get();
}
private parseSize(size?: string) {
const [value, unit] = (size || '').trim().split(/\s+/);
const units: Record<string, number> = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
return Number.parseFloat(value) * (units[unit] ?? 1) || 0;
}
async search({
query,
sort = Sort.seeds,
type,
imdbID
}: {
query: string;
sort?: Sort;
type?: ShowType;
imdbID?: string;
}): Promise<Torrent[]> {
if (imdbID && /^tt\d+$/.test(imdbID)) {
try {
// The IMDb page has no server-side sort, so sort the fetched rows locally.
const { data } = await this.client.get(`/imdb-detail/${imdbID}/`, { responseType: 'text' });
const byImdb = this.parseRows(data as string);
if (byImdb.length) {
return sort === Sort.size
? byImdb.sort((a, b) => this.parseSize(b.size) - this.parseSize(a.size))
: byImdb.sort((a, b) => b.seeders - a.seeders);
}
} catch (_) {
// fall back to the keyword search below
}
}
const search = (searchQuery: string) =>
this.client.get(this.buildSearchUrl(searchQuery, type, sort)).then(({ data }) => this.parseRows(data as string));
let torrents = await search(query);
if (!torrents.length) {
// The query is scoped by the show's year to disambiguate sequels, but the TMDB
// release year can differ from the year in release names, so fall back to the bare title.
const fallback = query.replace(/\s\d{4}$/, '');
if (fallback !== query) torrents = await search(fallback);
}
return torrents;
}
async magnet(url: string) {
const { data } = await this.client.get(url, { responseType: 'text' });
return (
load(data as string)('a.dl-magnet')
.first()
.attr('href') || ''
);
}
}
const parser = new TorrentGalaxy();
export default parser;
+1
View File
@@ -1,6 +1,7 @@
MOVIE_DB_TOKEN=YOUR_TOKEN
PIRATE_BAY_HOST=https://thepiratebay10.org
YTS_HOST=https://yts.mx/api/v2/list_movies.json
TG_HOST=https://torrentgalaxy.info
TOLOKA_HOST=https://toloka.to
TOLOKA_USERNAME=your_toloka_username
TOLOKA_PASSWORD=your_toloka_password
+1
View File
@@ -18,6 +18,7 @@ export const TOLOKA_PASSWORD = process.env.TOLOKA_PASSWORD;
export const PIRATE_BAY_HOST = process.env.PIRATE_BAY_HOST;
export const YTS_HOST = process.env.YTS_HOST;
export const TG_HOST = process.env.TG_HOST;
export const ODC_HOST = process.env.ODC_HOST;
export const ODC_USERNAME = process.env.ODC_USERNAME;