From c41f1f098fced6f43d7ae02493ae359bcfbc0789 Mon Sep 17 00:00:00 2001 From: ner Date: Sun, 25 Oct 2026 18:24:08 +0200 Subject: [PATCH] feat(torrents): add Galaxy (TorrentGalaxy) provider with IMDb-first search and inline magnets - new tg parser: /imdb-detail/ 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 --- app/api/magnet/route.ts | 6 +- app/api/torrents/route.ts | 3 +- .../Preview/components/Torrents/constants.ts | 6 + .../Preview/components/Torrents/index.tsx | 17 +- .../components/Torrents/useProvidersOrder.ts | 8 +- data/parsers/tg/index.ts | 151 ++++++++++++++++++ env.example | 1 + env.ts | 1 + 8 files changed, 184 insertions(+), 9 deletions(-) create mode 100644 data/parsers/tg/index.ts diff --git a/app/api/magnet/route.ts b/app/api/magnet/route.ts index c491ad8..470d45c 100644 --- a/app/api/magnet/route.ts +++ b/app/api/magnet/route.ts @@ -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(); } diff --git a/app/api/torrents/route.ts b/app/api/torrents/route.ts index a7e7ca6..138da0e 100644 --- a/app/api/torrents/route.ts +++ b/app/api/torrents/route.ts @@ -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 }); diff --git a/components/Preview/components/Torrents/constants.ts b/components/Preview/components/Torrents/constants.ts index f91472a..ffe1905 100644 --- a/components/Preview/components/Torrents/constants.ts +++ b/components/Preview/components/Torrents/constants.ts @@ -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', diff --git a/components/Preview/components/Torrents/index.tsx b/components/Preview/components/Torrents/index.tsx index b2dc5b4..c17c03d 100644 --- a/components/Preview/components/Torrents/index.tsx +++ b/components/Preview/components/Torrents/index.tsx @@ -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 ? : 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) => { @@ -126,7 +135,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => { - + {tabs.map(({ provider, query }) => ( ))} diff --git a/components/Preview/components/Torrents/useProvidersOrder.ts b/components/Preview/components/Torrents/useProvidersOrder.ts index 3e3d541..b1ffafb 100644 --- a/components/Preview/components/Torrents/useProvidersOrder.ts +++ b/components/Preview/components/Torrents/useProvidersOrder.ts @@ -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); }); }; diff --git a/data/parsers/tg/index.ts b/data/parsers/tg/index.ts new file mode 100644 index 0000000..af1620e --- /dev/null +++ b/data/parsers/tg/index.ts @@ -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 = { 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 { + 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; diff --git a/env.example b/env.example index d80550d..1659c04 100644 --- a/env.example +++ b/env.example @@ -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 diff --git a/env.ts b/env.ts index c98974b..6e969c9 100644 --- a/env.ts +++ b/env.ts @@ -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;