From 96585b495d6daca0815141ceaa0d635de9e5e122 Mon Sep 17 00:00:00 2001 From: Pierre Date: Sat, 10 Jan 2026 15:34:02 +0100 Subject: [PATCH] initial commit --- .github/workflows/docker.yml | 56 +++++++++++++ .gitignore | 5 ++ Dockerfile | 16 ++++ README.md | 64 +++++++++++++++ package.json | 10 +++ src/index.ts | 28 +++++++ src/meta-core-client.ts | 73 +++++++++++++++++ src/plugin.ts | 154 +++++++++++++++++++++++++++++++++++ src/types.ts | 70 ++++++++++++++++ tsconfig.json | 18 ++++ 10 files changed, 494 insertions(+) create mode 100644 .github/workflows/docker.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 package.json create mode 100644 src/index.ts create mode 100644 src/meta-core-client.ts create mode 100644 src/plugin.ts create mode 100644 src/types.ts create mode 100644 tsconfig.json diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..8cdc3e7 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,56 @@ +name: Build and Push Docker Image + +on: + push: + branches: [main, master] + tags: ['v*'] + pull_request: + branches: [main, master] + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Container Registry + if: github.event_name != 'pull_request' + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=sha + + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..397b0d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +*.log +.env +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7b4e487 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM node:20-slim AS builder +WORKDIR /app +COPY package.json tsconfig.json ./ +RUN npm install +COPY src/ ./src/ +RUN npm run build + +FROM node:20-slim +WORKDIR /app +COPY package.json ./ +RUN npm install --omit=dev +COPY --from=builder /app/dist ./dist +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD node -e "require('http').get('http://localhost:8080/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))" +CMD ["node", "dist/index.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..fea1ca1 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# MetaMesh Plugin: Anime Detector + +A MetaMesh plugin that detects anime content based on keywords, Japanese text, and audio tracks. + +## Description + +This plugin analyzes video files to determine if they are anime content. Detection is based on: + +- **Fansub group keywords**: `[HorribleSubs]`, `[SubsPlease]`, `[Erai-raws]`, etc. +- **Japanese text detection**: Uses `wanakana` library for kana/kanji detection +- **Audio track language**: Checks for Japanese audio streams +- **File path**: Checks if "anime" is in the path + +## Metadata Fields + +| Field | Description | +|-------|-------------| +| `anime` | Boolean indicating if content is anime | +| `titles/jpn` | Japanese title (if detected) | +| `titles/rom` | Romanized title | +| `genres` | Adds "Anime" to genres set | + +## Dependencies + +- Requires `file-info`, `ffmpeg`, and `filename-parser` plugins to run first + +## Configuration + +No configuration required. + +## API Endpoints + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/health` | GET | Health check | +| `/manifest` | GET | Plugin manifest | +| `/configure` | POST | Update configuration | +| `/process` | POST | Process a file | + +## Running Locally + +```bash +npm install +npm run build +npm start +``` + +## Docker + +```bash +docker build -t metamesh-plugin-anime-detector . +docker run -p 8080:8080 metamesh-plugin-anime-detector +``` + +## Environment Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `PORT` | `8080` | HTTP server port | +| `HOST` | `0.0.0.0` | HTTP server host | + +## License + +MIT diff --git a/package.json b/package.json new file mode 100644 index 0000000..3ad4b4c --- /dev/null +++ b/package.json @@ -0,0 +1,10 @@ +{ + "name": "@metazla/plugin-anime-detector", + "version": "1.0.0", + "description": "MetaMesh plugin: Detects anime content", + "type": "module", + "main": "dist/index.js", + "scripts": { "build": "tsc", "start": "node dist/index.js" }, + "dependencies": { "fastify": "^5.0.0", "wanakana": "^5.3.1" }, + "devDependencies": { "@types/node": "^20.0.0", "typescript": "^5.3.0" } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..a1db0dc --- /dev/null +++ b/src/index.ts @@ -0,0 +1,28 @@ +import Fastify from 'fastify'; +import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js'; +import { manifest, process as processFile } from './plugin.js'; + +const app = Fastify({ logger: true }); +let ready = false; + +app.get('/health', async (): Promise => ({ status: 'healthy', ready, version: manifest.version })); +app.get('/manifest', async () => manifest); +app.post<{ Body: ConfigureRequest }>('/configure', async (request): Promise => { + console.log(`[${manifest.id}] Configuration updated`); + return { status: 'ok' }; +}); +app.post<{ Body: ProcessRequest }>('/process', async (request, reply) => { + const { taskId, cid, filePath, callbackUrl, metaCoreUrl } = request.body; + if (!taskId || !cid || !filePath || !callbackUrl || !metaCoreUrl) { + return reply.send({ status: 'rejected', error: 'Missing required fields' } as ProcessResponse); + } + processFile(request.body, async (payload: CallbackPayload) => { + try { await fetch(callbackUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); } + catch (error) { console.error(`[${manifest.id}] Callback error:`, error); } + }).catch(console.error); + return reply.send({ status: 'accepted' } as ProcessResponse); +}); + +const port = parseInt(process.env.PORT || '8080', 10); +app.listen({ port, host: '0.0.0.0' }).then(() => { ready = true; console.log(`[${manifest.id}] Listening on port ${port}`); }); +process.on('SIGTERM', async () => { ready = false; await app.close(); process.exit(0); }); diff --git a/src/meta-core-client.ts b/src/meta-core-client.ts new file mode 100644 index 0000000..edbe17c --- /dev/null +++ b/src/meta-core-client.ts @@ -0,0 +1,73 @@ +/** + * meta-core API Client for writing metadata + * Fails gracefully if meta-core is unavailable (logs warning, returns without throwing) + */ + +export class MetaCoreClient { + constructor(private baseUrl: string) {} + + private async safeFetch(url: string, options: RequestInit): Promise { + try { + return await fetch(url, { ...options, signal: AbortSignal.timeout(5000) }); + } catch (error) { + console.warn(`[MetaCoreClient] Warning: meta-core unavailable at ${this.baseUrl}`); + return null; + } + } + + async setProperty(hashId: string, key: string, value: string): Promise { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ value }), + }); + if (response && !response.ok) { + console.warn(`[MetaCoreClient] Failed to set property: ${response.status}`); + } + } + + async getProperty(hashId: string, key: string): Promise { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' }); + if (!response || response.status === 404) return null; + if (!response.ok) return null; + const data = await response.json() as { value?: string }; + return data.value ?? null; + } + + async mergeMetadata(hashId: string, metadata: Record): Promise { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(metadata), + }); + if (response && !response.ok) { + console.warn(`[MetaCoreClient] Failed to merge metadata: ${response.status}`); + } + } + + async deleteProperty(hashId: string, key: string): Promise { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'DELETE' }); + if (response && !response.ok && response.status !== 404) { + console.warn(`[MetaCoreClient] Failed to delete property: ${response.status}`); + } + } + + async addToSet(hashId: string, key: string, value: string): Promise { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/_add/${key}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ value }), + }); + if (response && !response.ok) { + console.warn(`[MetaCoreClient] Failed to add to set: ${response.status}`); + } + } + + async getMetadata(hashId: string): Promise> { + const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' }); + if (!response || response.status === 404) return {}; + if (!response.ok) return {}; + const data = await response.json() as { metadata?: Record }; + return data.metadata ?? {}; + } +} diff --git a/src/plugin.ts b/src/plugin.ts new file mode 100644 index 0000000..d4db0a4 --- /dev/null +++ b/src/plugin.ts @@ -0,0 +1,154 @@ +/** + * Anime Detector Plugin + * Detects if content is anime based on keywords and Japanese text + */ + +import { isJapanese, isKana } from 'wanakana'; +import type { PluginManifest, ProcessRequest, CallbackPayload } from './types.js'; +import { MetaCoreClient } from './meta-core-client.js'; + +export const manifest: PluginManifest = { + id: 'anime-detector', + name: 'Anime Detector', + version: '1.0.0', + description: 'Detects anime content based on keywords, Japanese text, and audio tracks', + author: 'MetaMesh', + dependencies: ['file-info', 'ffmpeg', 'filename-parser'], + priority: 35, + color: '#E91E63', + defaultQueue: 'fast', + timeout: 30000, + schema: { + anime: { label: 'Is Anime', type: 'boolean', readonly: true }, + 'titles/jpn': { label: 'Japanese Title', type: 'string' }, + }, + config: {}, +}; + +// Anime keywords from @metazla/filename-tools - fansub group identifiers only +// Note: Codec patterns (HEVC, x265, etc.) are NOT anime indicators +const ANIME_KEYWORDS = [ + '[HorribleSubs]', + '[DB]', // Dragon Ball fansubs, also generic for various sub groups + '[Erai-raws]', + '[SubsPlease]', + '[GG]', // A known fansub group + '[Commie]', // A fansubbing group + '[Underwater]', // A fansubbing group + '[Nyaa]', // A reference to the Nyaa Torrents site, often included in anime torrents + '[FFF]', // A fansubbing group + '[Coalgirls]', // A fansubbing group known for high-quality releases + '[Chihiro]', // A fansubbing group + '[DameDesuYo]', // A fansubbing group + '[GJM]', // A fansubbing group (Good Job! Media) + '[AhorribleSubs]', // A misspelling of HorribleSubs sometimes used + '[AnimeRG]', // A group known for releasing anime torrents + '[Judas]', // A group known for their anime releases + '[Cleo]', // A group known for their anime encodes + '[LostYears]', // A group known for dub and sub releases + '[KaiDubs]', // A group known for dubbed anime releases + '[AnimeKaizoku]', // A website known for anime downloads, sometimes included in filenames + '[AnimeLand]', // A website known for anime downloads, sometimes included in filenames + '[Beatrice-Raws]', // A group known for raw anime blu-ray encodes + '[BakedFish]', // A less common but recognized release group + '[DeadFish]', // A group known for re-encoding fansubs into hardsubbed mp4 format + '[Golumpa]', // A group known for dubbed anime releases + '[EMBER]', // A group known for their anime releases +]; + +export async function process( + request: ProcessRequest, + sendCallback: (payload: CallbackPayload) => Promise +): Promise { + const startTime = Date.now(); + const metaCore = new MetaCoreClient(request.metaCoreUrl); + + try { + const { cid, filePath, existingMeta } = request; + + // Only process video files + if (existingMeta?.fileType !== 'video') { + await sendCallback({ + taskId: request.taskId, + status: 'skipped', + duration: Date.now() - startTime, + reason: 'Not a video file', + }); + return; + } + + const originalTitle = existingMeta?.originalTitle || ''; + const fileName = existingMeta?.fileName || ''; + let isAnime = false; + let isJpn = false; + + // Check if "anime" is in the filepath + if (/anime/i.test(filePath)) { + isAnime = true; + isJpn = true; + } + + // Check for anime keywords + for (const keyword of ANIME_KEYWORDS) { + if (fileName.includes(keyword)) { + isAnime = true; + isJpn = true; + break; + } + } + + // Check if title is Japanese + if (originalTitle && (isKana(originalTitle) || isJapanese(originalTitle))) { + isJpn = true; + } + + // Check audio streams for Japanese language + for (let i = 0; i < 10; i++) { + const lang = existingMeta?.[`fileinfo/streamdetails/audio/${i}/language`]; + if (lang === 'jpn' || lang === 'ja') { + isJpn = true; + break; + } + if (!lang) break; + } + + // Check video streams for Japanese language (matching original) + for (let i = 0; i < 10; i++) { + const lang = existingMeta?.[`fileinfo/streamdetails/video/${i}/language`]; + if (lang === 'jpn' || lang === 'ja') { + isJpn = true; + break; + } + if (!lang) break; + } + + const metadata: Record = {}; + + if (isJpn && originalTitle) { + if (isKana(originalTitle)) { + metadata['titles/jpn'] = originalTitle; + } else { + metadata['titles/rom'] = originalTitle; + } + } + + if (isAnime || isJpn) { + metadata.anime = 'true'; + await metaCore.mergeMetadata(cid, metadata); + await metaCore.addToSet(cid, 'genres', 'Anime'); + } + + await sendCallback({ + taskId: request.taskId, + status: 'completed', + duration: Date.now() - startTime, + }); + } catch (error) { + await sendCallback({ + taskId: request.taskId, + status: 'failed', + duration: Date.now() - startTime, + error: error instanceof Error ? error.message : String(error), + }); + } +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..4dbbfe2 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,70 @@ +/** + * MetaMesh Plugin Types + */ + +export interface PluginManifest { + id: string; + name: string; + version: string; + description?: string; + author?: string; + dependencies?: string[]; + schema?: Record; + config?: Record; + priority?: number; + color?: string; + defaultQueue?: 'fast' | 'background'; + timeout?: number; +} + +export interface SchemaField { + label: string; + type?: 'string' | 'number' | 'boolean' | 'select' | 'text' | 'array' | 'json' | 'cid'; + readonly?: boolean; + hint?: string; +} + +export interface ConfigField { + type: 'string' | 'number' | 'boolean' | 'select'; + label?: string; + required?: boolean; + default?: unknown; + secret?: boolean; +} + +export interface HealthResponse { + status: 'healthy' | 'unhealthy'; + ready: boolean; + version: string; +} + +export interface ProcessRequest { + taskId: string; + cid: string; + filePath: string; + callbackUrl: string; + metaCoreUrl: string; + existingMeta?: Record; +} + +export interface ProcessResponse { + status: 'accepted' | 'rejected'; + error?: string; +} + +export interface CallbackPayload { + taskId: string; + status: 'completed' | 'failed' | 'skipped'; + duration: number; + error?: string; + reason?: string; +} + +export interface ConfigureRequest { + config: Record; +} + +export interface ConfigureResponse { + status: 'ok' | 'error'; + error?: string; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..95ac5c2 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "sourceMap": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +}