Spaces:
Runtime error

File size: 9,668 Bytes
d0df973
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
CraftMovies Hugging Face Space API
==================================

FastAPI backend for CraftMovies, ready for Hugging Face Spaces Docker hosting.

Default port:
    7860

Local run:
    python -m uvicorn main:app --host 0.0.0.0 --port 7860

Endpoints:
    GET /
    GET /health
    GET /api/home
    GET /api/search?q=lucifer
    GET /api/search-all?q=lucifer&limit_tv=1&limit_episodes=5
    GET /api/fetch-movies
    GET /api/fetch-tv
    GET /api/browse/movie
    GET /api/browse/tv
    GET /api/movie?url=/movie/5nspt-the-avengers-2012
    GET /api/tv-show?url=/tv/56tj4-lucifer&limit_episodes=5
    GET /api/episode?url=/tv/56tj4-lucifer/season/1/episode/3
"""

from __future__ import annotations

import hashlib
import json
import os
import time
from typing import Any, Callable, Optional

from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse

from craftmovies import CraftMovies, CraftMoviesConfig


class Settings:
    """Environment settings for Hugging Face Space deployment."""

    BASE_URL: str = os.getenv("CRAFTMOVIES_BASE_URL", "https://streamimdb.ru")
    REQUEST_TIMEOUT: int = int(os.getenv("CRAFTMOVIES_TIMEOUT", "15"))
    DEBUG: bool = os.getenv("CRAFTMOVIES_DEBUG", "false").lower() == "true"
    CACHE_TTL_SECONDS: int = int(os.getenv("CRAFTMOVIES_CACHE_TTL_SECONDS", "300"))
    CORS_ORIGINS: list[str] = [
        origin.strip()
        for origin in os.getenv("CRAFTMOVIES_CORS_ORIGINS", "*").split(",")
        if origin.strip()
    ]


settings = Settings()

app = FastAPI(
    title="CraftMovies API",
    description=(
        "Hugging Face Spaces-ready API for CraftMovies. "
        "Returns metadata, seasons, episodes, posters, recommendations, and visible iframe embed URLs."
    ),
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "DELETE"],
    allow_headers=["*"],
)

cm = CraftMovies(
    CraftMoviesConfig(
        base_url=settings.BASE_URL,
        timeout=settings.REQUEST_TIMEOUT,
        debug=settings.DEBUG,
    )
)

_CACHE: dict[str, dict[str, Any]] = {}


def make_cache_key(name: str, params: dict[str, Any]) -> str:
    payload = json.dumps({"name": name, "params": params}, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def get_cached(key: str) -> Optional[Any]:
    item = _CACHE.get(key)
    if not item:
        return None

    age = time.time() - item["created_at"]
    if age > settings.CACHE_TTL_SECONDS:
        _CACHE.pop(key, None)
        return None

    return item["value"]


def set_cached(key: str, value: Any) -> None:
    _CACHE[key] = {"created_at": time.time(), "value": value}


def cached_call(name: str, params: dict[str, Any], fn: Callable[[], Any], refresh: bool = False) -> Any:
    key = make_cache_key(name, params)

    if not refresh:
        cached = get_cached(key)
        if cached is not None:
            if isinstance(cached, dict):
                cached = dict(cached)
                cached["_cache"] = "hit"
            return cached

    value = fn()
    if isinstance(value, dict):
        value["_cache"] = "miss"
    set_cached(key, value)
    return value


def require_url(value: Optional[str]) -> str:
    if not value or not value.strip():
        raise HTTPException(status_code=400, detail="Missing required query parameter: url")
    return value.strip()


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal server error",
            "details": str(exc),
            "path": str(request.url.path),
        },
    )


@app.get("/", include_in_schema=False)
def root():
    """Redirect root to docs for easy Hugging Face Space testing."""
    return RedirectResponse(url="/docs")


@app.get("/health")
def health():
    return {
        "status": "ok",
        "service": "CraftMovies API",
        "environment": "huggingface-space",
        "base_url": settings.BASE_URL,
        "cache_ttl_seconds": settings.CACHE_TTL_SECONDS,
        "docs": "/docs",
    }


@app.get("/api/cache/stats")
def cache_stats():
    return {"items": len(_CACHE), "ttl_seconds": settings.CACHE_TTL_SECONDS}


@app.delete("/api/cache")
def clear_cache():
    _CACHE.clear()
    return {"status": "cleared"}


@app.get("/api/home")
def api_home(refresh: bool = Query(False)):
    return cached_call(
        "home",
        {"base_url": settings.BASE_URL},
        lambda: cm.home(),
        refresh=refresh,
    )


@app.get("/api/search")
def api_search(
    q: str = Query(..., min_length=1, description="Search query"),
    refresh: bool = Query(False),
):
    return cached_call(
        "search",
        {"q": q, "base_url": settings.BASE_URL},
        lambda: cm.search(q),
        refresh=refresh,
    )


@app.get("/api/search-all")
def api_search_all(
    q: str = Query(..., min_length=1, description="Search query"),
    include_episode_details: bool = Query(True, description="Fetch episode pages for TV results"),
    limit_tv: int = Query(0, ge=0, description="Max TV shows to expand. 0 means all."),
    limit_episodes: int = Query(0, ge=0, description="Max episode pages per show. 0 means all."),
    refresh: bool = Query(False),
):
    return cached_call(
        "search_all",
        {
            "q": q,
            "include_episode_details": include_episode_details,
            "limit_tv": limit_tv,
            "limit_episodes": limit_episodes,
            "base_url": settings.BASE_URL,
        },
        lambda: cm.searchAll(
            q,
            include_episode_details=include_episode_details,
            limit_tv=limit_tv,
            limit_episodes=limit_episodes,
        ),
        refresh=refresh,
    )


@app.get("/api/fetch-movies")
def api_fetch_movies(
    include_details: bool = Query(False),
    limit_items: int = Query(0, ge=0),
    refresh: bool = Query(False),
):
    return cached_call(
        "fetch_movies",
        {
            "include_details": include_details,
            "limit_items": limit_items,
            "base_url": settings.BASE_URL,
        },
        lambda: cm.fetchMovies(include_details=include_details, limit_items=limit_items),
        refresh=refresh,
    )


@app.get("/api/fetch-tv")
def api_fetch_tv(
    include_details: bool = Query(False),
    include_episode_details: bool = Query(False),
    limit_items: int = Query(0, ge=0),
    limit_episodes: int = Query(0, ge=0),
    refresh: bool = Query(False),
):
    return cached_call(
        "fetch_tv",
        {
            "include_details": include_details,
            "include_episode_details": include_episode_details,
            "limit_items": limit_items,
            "limit_episodes": limit_episodes,
            "base_url": settings.BASE_URL,
        },
        lambda: cm.fetchTV(
            include_details=include_details,
            include_episode_details=include_episode_details,
            limit_items=limit_items,
            limit_episodes=limit_episodes,
        ),
        refresh=refresh,
    )


@app.get("/api/browse/{media_type}")
def api_browse(
    media_type: str,
    include_details: bool = Query(False),
    include_episode_details: bool = Query(False),
    limit_items: int = Query(0, ge=0),
    limit_episodes: int = Query(0, ge=0),
    refresh: bool = Query(False),
):
    if media_type not in {"movie", "tv"}:
        raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'tv'")

    return cached_call(
        "browse",
        {
            "media_type": media_type,
            "include_details": include_details,
            "include_episode_details": include_episode_details,
            "limit_items": limit_items,
            "limit_episodes": limit_episodes,
            "base_url": settings.BASE_URL,
        },
        lambda: cm.browse(
            media_type,
            include_details=include_details,
            include_episode_details=include_episode_details,
            limit_items=limit_items,
            limit_episodes=limit_episodes,
        ),
        refresh=refresh,
    )


@app.get("/api/movie")
def api_movie(
    url: str = Query(..., description="Movie URL/path"),
    refresh: bool = Query(False),
):
    target_url = require_url(url)

    return cached_call(
        "movie",
        {"url": target_url, "base_url": settings.BASE_URL},
        lambda: cm.movie(target_url),
        refresh=refresh,
    )


@app.get("/api/tv-show")
def api_tv_show(
    url: str = Query(..., description="TV show URL/path"),
    full: bool = Query(True, description="Fetch episode pages too"),
    limit_episodes: int = Query(0, ge=0),
    refresh: bool = Query(False),
):
    target_url = require_url(url)

    return cached_call(
        "tv_show",
        {
            "url": target_url,
            "full": full,
            "limit_episodes": limit_episodes,
            "base_url": settings.BASE_URL,
        },
        lambda: cm.tvShow(target_url, full=full, limit_episodes=limit_episodes),
        refresh=refresh,
    )


@app.get("/api/episode")
def api_episode(
    url: str = Query(..., description="Episode URL/path"),
    refresh: bool = Query(False),
):
    target_url = require_url(url)

    return cached_call(
        "episode",
        {"url": target_url, "base_url": settings.BASE_URL},
        lambda: cm.episode(target_url),
        refresh=refresh,
    )