hayate-player 0.1.0__py3-none-any.whl
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.
- hayate/__init__.py +0 -0
- hayate/core/__init__.py +0 -0
- hayate/core/anilist.py +545 -0
- hayate/core/history.py +95 -0
- hayate/core/image_cache.py +230 -0
- hayate/core/lan_server.py +137 -0
- hayate/core/player.py +146 -0
- hayate/core/settings.py +52 -0
- hayate/core/week_cache.py +109 -0
- hayate/core/workers.py +29 -0
- hayate/main.py +24 -0
- hayate/providers/__init__.py +103 -0
- hayate/providers/base.py +48 -0
- hayate/providers/builtins/__init__.py +1 -0
- hayate/providers/builtins/pseudo_provider.py +14 -0
- hayate/providers/builtins/ytdlp_provider.py +139 -0
- hayate/ui/__init__.py +0 -0
- hayate/ui/details_view.py +667 -0
- hayate/ui/lan_hub.py +248 -0
- hayate/ui/lan_player.py +750 -0
- hayate/ui/main_window.py +1411 -0
- hayate/ui/player_view.py +804 -0
- hayate/ui/schedule_view.py +496 -0
- hayate/ui/search_view.py +277 -0
- hayate/ui/settings_view.py +646 -0
- hayate/ui/upcoming_details_view.py +217 -0
- hayate_player-0.1.0.dist-info/METADATA +38 -0
- hayate_player-0.1.0.dist-info/RECORD +32 -0
- hayate_player-0.1.0.dist-info/WHEEL +5 -0
- hayate_player-0.1.0.dist-info/entry_points.txt +2 -0
- hayate_player-0.1.0.dist-info/licenses/LICENSE +674 -0
- hayate_player-0.1.0.dist-info/top_level.txt +1 -0
hayate/__init__.py
ADDED
|
File without changes
|
hayate/core/__init__.py
ADDED
|
File without changes
|
hayate/core/anilist.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
import urllib.request
|
|
2
|
+
import urllib.error
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from datetime import datetime, timedelta, date
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Optional, List, Tuple, Dict, Any
|
|
8
|
+
|
|
9
|
+
from hayate.core.settings import config_dir, load_settings, cache_dir
|
|
10
|
+
|
|
11
|
+
ANILIST_API_URL = "https://graphql.anilist.co"
|
|
12
|
+
|
|
13
|
+
DAYS_OF_WEEK = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
|
|
14
|
+
|
|
15
|
+
SCHEDULE_CACHE_TTL = 30 * 60 # seconds
|
|
16
|
+
SCHEDULE_FORMATS = {"TV", "TV_SHORT", "ONA"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class AnimeMedia:
|
|
21
|
+
id: int
|
|
22
|
+
title: str
|
|
23
|
+
cover_url: str = ""
|
|
24
|
+
banner_url: str = ""
|
|
25
|
+
description: str = ""
|
|
26
|
+
format: Optional[str] = None
|
|
27
|
+
episodes: int = 1
|
|
28
|
+
average_score: Optional[int] = None
|
|
29
|
+
season: Optional[str] = None
|
|
30
|
+
season_year: Optional[int] = None
|
|
31
|
+
genres: List[str] = field(default_factory=list)
|
|
32
|
+
is_adult: bool = False
|
|
33
|
+
relations: List[Dict[str, Any]] = field(default_factory=list)
|
|
34
|
+
airing_episode: Optional[int] = None
|
|
35
|
+
airing_time: Optional[int] = None
|
|
36
|
+
start_date: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None
|
|
37
|
+
end_date: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None
|
|
38
|
+
status: Optional[str] = None
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def display_title(self) -> str:
|
|
42
|
+
return self.title or "Unknown Title"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def year(self) -> Optional[int]:
|
|
46
|
+
return self.season_year
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def has_prequel(self) -> bool:
|
|
50
|
+
return any(r.get("relation_type") == "PREQUEL" for r in self.relations)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def is_date_confirmed(self) -> bool:
|
|
54
|
+
"""True when AniList has at least a year and month for the premiere."""
|
|
55
|
+
return bool(self.start_date and self.start_date[0] and self.start_date[1])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# --------------------------------------------------------------------------
|
|
59
|
+
# Transport
|
|
60
|
+
# --------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
def _send_query(query: str, variables: Optional[dict] = None, _retried: bool = False) -> dict:
|
|
63
|
+
payload = {"query": query, "variables": variables or {}}
|
|
64
|
+
data_bytes = json.dumps(payload).encode("utf-8")
|
|
65
|
+
req = urllib.request.Request(
|
|
66
|
+
ANILIST_API_URL,
|
|
67
|
+
data=data_bytes,
|
|
68
|
+
headers={
|
|
69
|
+
"Content-Type": "application/json",
|
|
70
|
+
"Accept": "application/json",
|
|
71
|
+
"User-Agent": "Hayate/0.1",
|
|
72
|
+
},
|
|
73
|
+
)
|
|
74
|
+
try:
|
|
75
|
+
with urllib.request.urlopen(req, timeout=12) as response:
|
|
76
|
+
result = json.loads(response.read().decode("utf-8"))
|
|
77
|
+
except urllib.error.HTTPError as e:
|
|
78
|
+
# AniList rate limit: wait the advertised time once, then retry.
|
|
79
|
+
if e.code == 429 and not _retried:
|
|
80
|
+
try:
|
|
81
|
+
wait = min(int(e.headers.get("Retry-After", "5")), 30)
|
|
82
|
+
except ValueError:
|
|
83
|
+
wait = 5
|
|
84
|
+
time.sleep(wait)
|
|
85
|
+
return _send_query(query, variables, _retried=True)
|
|
86
|
+
raise
|
|
87
|
+
|
|
88
|
+
if result.get("errors") and not result.get("data"):
|
|
89
|
+
msg = "; ".join(str(err.get("message", err)) for err in result["errors"])
|
|
90
|
+
raise RuntimeError(f"AniList error: {msg}")
|
|
91
|
+
return result
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _resolve_adult(allow_adult: Optional[bool]) -> bool:
|
|
95
|
+
"""None means "use the saved setting"."""
|
|
96
|
+
if allow_adult is None:
|
|
97
|
+
return bool(load_settings().get("allow_adult", False))
|
|
98
|
+
return bool(allow_adult)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _adult_arg(allow_adult: bool) -> str:
|
|
102
|
+
return "" if allow_adult else "isAdult: false, genre_not_in: [\"Ecchi\", \"Hentai\"],"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# --------------------------------------------------------------------------
|
|
106
|
+
# Parsing
|
|
107
|
+
# --------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
def _fuzzy_date(d: Optional[dict]):
|
|
110
|
+
if not d:
|
|
111
|
+
return None
|
|
112
|
+
y, m, day = d.get("year"), d.get("month"), d.get("day")
|
|
113
|
+
if not (y or m or day):
|
|
114
|
+
return None
|
|
115
|
+
return (y, m, day)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _parse_media_node(item: dict) -> AnimeMedia:
|
|
119
|
+
t = item.get("title", {}) or {}
|
|
120
|
+
resolved_title = t.get("english") or t.get("romaji") or "Unknown Title"
|
|
121
|
+
|
|
122
|
+
cover = (item.get("coverImage") or {}).get("large") or ""
|
|
123
|
+
banner = item.get("bannerImage") or cover
|
|
124
|
+
raw_eps = item.get("episodes")
|
|
125
|
+
next_air = item.get("nextAiringEpisode")
|
|
126
|
+
if not raw_eps and next_air and isinstance(next_air, dict):
|
|
127
|
+
current_airing_ep = next_air.get("episode")
|
|
128
|
+
if current_airing_ep and current_airing_ep > 1:
|
|
129
|
+
raw_eps = current_airing_ep - 1
|
|
130
|
+
|
|
131
|
+
parsed_relations = []
|
|
132
|
+
edges = (item.get("relations") or {}).get("edges", [])
|
|
133
|
+
for edge in edges:
|
|
134
|
+
rel_type = edge.get("relationType", "")
|
|
135
|
+
node = edge.get("node")
|
|
136
|
+
if node:
|
|
137
|
+
rel_t = node.get("title", {}) or {}
|
|
138
|
+
node_title = rel_t.get("english") or rel_t.get("romaji") or "Unknown"
|
|
139
|
+
parsed_relations.append({
|
|
140
|
+
"relation_type": rel_type,
|
|
141
|
+
"id": node.get("id"),
|
|
142
|
+
"title": node_title,
|
|
143
|
+
"format": node.get("format"),
|
|
144
|
+
"cover_url": (node.get("coverImage") or {}).get("large", ""),
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
nxt = item.get("nextAiringEpisode") or {}
|
|
148
|
+
|
|
149
|
+
return AnimeMedia(
|
|
150
|
+
id=item.get("id"),
|
|
151
|
+
title=resolved_title,
|
|
152
|
+
cover_url=cover,
|
|
153
|
+
banner_url=banner,
|
|
154
|
+
description=item.get("description") or "",
|
|
155
|
+
format=item.get("format"),
|
|
156
|
+
episodes=raw_eps if raw_eps is not None else 1,
|
|
157
|
+
average_score=item.get("averageScore"),
|
|
158
|
+
season=item.get("season"),
|
|
159
|
+
season_year=item.get("seasonYear"),
|
|
160
|
+
genres=item.get("genres") or [],
|
|
161
|
+
is_adult=bool(item.get("isAdult", False)),
|
|
162
|
+
relations=parsed_relations,
|
|
163
|
+
airing_episode=nxt.get("episode"),
|
|
164
|
+
airing_time=nxt.get("airingAt"),
|
|
165
|
+
start_date=_fuzzy_date(item.get("startDate")),
|
|
166
|
+
end_date=_fuzzy_date(item.get("endDate")),
|
|
167
|
+
status=item.get("status"),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
MEDIA_FIELDS = """
|
|
172
|
+
id
|
|
173
|
+
title {
|
|
174
|
+
romaji
|
|
175
|
+
english
|
|
176
|
+
}
|
|
177
|
+
coverImage {
|
|
178
|
+
large
|
|
179
|
+
}
|
|
180
|
+
bannerImage
|
|
181
|
+
description
|
|
182
|
+
format
|
|
183
|
+
episodes
|
|
184
|
+
averageScore
|
|
185
|
+
season
|
|
186
|
+
seasonYear
|
|
187
|
+
genres
|
|
188
|
+
isAdult
|
|
189
|
+
status
|
|
190
|
+
startDate { year month day }
|
|
191
|
+
endDate { year month day }
|
|
192
|
+
nextAiringEpisode {
|
|
193
|
+
episode
|
|
194
|
+
airingAt
|
|
195
|
+
}
|
|
196
|
+
relations {
|
|
197
|
+
edges {
|
|
198
|
+
relationType
|
|
199
|
+
node {
|
|
200
|
+
id
|
|
201
|
+
title {
|
|
202
|
+
romaji
|
|
203
|
+
english
|
|
204
|
+
}
|
|
205
|
+
format
|
|
206
|
+
coverImage {
|
|
207
|
+
large
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _parse_list(raw: Optional[list], allow_adult: bool) -> List[AnimeMedia]:
|
|
216
|
+
out = [_parse_media_node(i) for i in (raw or [])]
|
|
217
|
+
if not allow_adult:
|
|
218
|
+
out = [m for m in out if not m.is_adult]
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _dedupe(items: List[AnimeMedia], exclude_ids: set) -> List[AnimeMedia]:
|
|
223
|
+
seen = set(exclude_ids)
|
|
224
|
+
out = []
|
|
225
|
+
for m in items:
|
|
226
|
+
if m.id in seen:
|
|
227
|
+
continue
|
|
228
|
+
seen.add(m.id)
|
|
229
|
+
out.append(m)
|
|
230
|
+
return out
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# --------------------------------------------------------------------------
|
|
234
|
+
# Search / details
|
|
235
|
+
# --------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
SEARCH_QUERY = f"""
|
|
238
|
+
query ($query: String, $page: Int, $perPage: Int) {{
|
|
239
|
+
Page(page: $page, perPage: $perPage) {{
|
|
240
|
+
pageInfo {{
|
|
241
|
+
total
|
|
242
|
+
perPage
|
|
243
|
+
currentPage
|
|
244
|
+
hasNextPage
|
|
245
|
+
}}
|
|
246
|
+
media(search: $query, type: ANIME, sort: [SEARCH_MATCH, POPULARITY_DESC]) {{
|
|
247
|
+
{MEDIA_FIELDS}
|
|
248
|
+
}}
|
|
249
|
+
}}
|
|
250
|
+
}}
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
ANIME_BY_ID_QUERY = f"""
|
|
254
|
+
query ($id: Int) {{
|
|
255
|
+
Media(id: $id, type: ANIME) {{
|
|
256
|
+
{MEDIA_FIELDS}
|
|
257
|
+
}}
|
|
258
|
+
}}
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def search_anime_sync(query: str, page: int = 1, per_page: int = 35,
|
|
263
|
+
allow_adult: Optional[bool] = None) -> Tuple[List[AnimeMedia], bool]:
|
|
264
|
+
"""Returns (results, had_adult_hits). had_adult_hits is True when adult
|
|
265
|
+
entries matched but were hidden by the user's setting."""
|
|
266
|
+
allow = _resolve_adult(allow_adult)
|
|
267
|
+
res_json = _send_query(SEARCH_QUERY, {"query": query, "page": page, "perPage": per_page})
|
|
268
|
+
media_list = (res_json.get("data") or {}).get("Page", {}).get("media", []) or []
|
|
269
|
+
everything = [_parse_media_node(item) for item in media_list]
|
|
270
|
+
if allow:
|
|
271
|
+
return everything, False
|
|
272
|
+
kept = [m for m in everything if not m.is_adult]
|
|
273
|
+
return kept, len(kept) != len(everything)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def get_anime_by_id_sync(anime_id: int) -> Optional[AnimeMedia]:
|
|
277
|
+
res_json = _send_query(ANIME_BY_ID_QUERY, {"id": anime_id})
|
|
278
|
+
media = (res_json.get("data") or {}).get("Media")
|
|
279
|
+
if not media:
|
|
280
|
+
return None
|
|
281
|
+
return _parse_media_node(media)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# --------------------------------------------------------------------------
|
|
285
|
+
# Home shelves
|
|
286
|
+
# --------------------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
UPCOMING_SHELF_LIMIT = 20
|
|
289
|
+
SHELF_LIMIT = 12
|
|
290
|
+
SPOTLIGHT_LIMIT = 10
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _home_query(allow_adult: bool) -> str:
|
|
294
|
+
adult = _adult_arg(allow_adult)
|
|
295
|
+
return f"""
|
|
296
|
+
query ($monthAgo: FuzzyDateInt) {{
|
|
297
|
+
spotlight: Page(page: 1, perPage: 15) {{
|
|
298
|
+
media(type: ANIME, status: RELEASING, sort: TRENDING_DESC, format_in: [TV, ONA], {adult}) {{
|
|
299
|
+
{MEDIA_FIELDS}
|
|
300
|
+
}}
|
|
301
|
+
}}
|
|
302
|
+
trending: Page(page: 1, perPage: 20) {{
|
|
303
|
+
media(type: ANIME, sort: TRENDING_DESC, {adult}) {{
|
|
304
|
+
{MEDIA_FIELDS}
|
|
305
|
+
}}
|
|
306
|
+
}}
|
|
307
|
+
new_releases: Page(page: 1, perPage: 24) {{
|
|
308
|
+
media(type: ANIME, status: RELEASING, sort: START_DATE_DESC, format_in: [TV, ONA], {adult}) {{
|
|
309
|
+
{MEDIA_FIELDS}
|
|
310
|
+
}}
|
|
311
|
+
}}
|
|
312
|
+
just_finished: Page(page: 1, perPage: 12) {{
|
|
313
|
+
media(type: ANIME, status: FINISHED, sort: END_DATE_DESC, endDate_greater: $monthAgo, format_in: [TV, ONA], {adult}) {{
|
|
314
|
+
{MEDIA_FIELDS}
|
|
315
|
+
}}
|
|
316
|
+
}}
|
|
317
|
+
upcoming: Page(page: 1, perPage: 30) {{
|
|
318
|
+
media(type: ANIME, status: NOT_YET_RELEASED, sort: POPULARITY_DESC, {adult}) {{
|
|
319
|
+
{MEDIA_FIELDS}
|
|
320
|
+
}}
|
|
321
|
+
}}
|
|
322
|
+
}}
|
|
323
|
+
"""
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _fuzzy_int(d: date) -> int:
|
|
327
|
+
return d.year * 10000 + d.month * 100 + d.day
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def build_shelves(data: dict, allow_adult: bool) -> Dict[str, List[AnimeMedia]]:
|
|
331
|
+
"""Turns the raw GraphQL payload into the shelves shown on the home screen."""
|
|
332
|
+
def raw(key):
|
|
333
|
+
return (data.get(key) or {}).get("media", [])
|
|
334
|
+
|
|
335
|
+
# Spotlight: currently airing, trending, and has a real banner image.
|
|
336
|
+
spotlight_all = _parse_list(raw("spotlight"), allow_adult)
|
|
337
|
+
spotlight = [m for m in spotlight_all if m.banner_url and m.banner_url != m.cover_url]
|
|
338
|
+
if len(spotlight) < 5: # not enough banners, fall back to whatever we have
|
|
339
|
+
spotlight = spotlight_all
|
|
340
|
+
spotlight = spotlight[:SPOTLIGHT_LIMIT]
|
|
341
|
+
spot_ids = {m.id for m in spotlight}
|
|
342
|
+
|
|
343
|
+
# Trending skips whatever is already in the spotlight so the two never match.
|
|
344
|
+
trending = _dedupe(_parse_list(raw("trending"), allow_adult), spot_ids)[:SHELF_LIMIT]
|
|
345
|
+
|
|
346
|
+
popular = _dedupe(_parse_list(raw("popular"), allow_adult), set())[:SHELF_LIMIT]
|
|
347
|
+
|
|
348
|
+
# New releases: first seasons only (no PREQUEL relation).
|
|
349
|
+
new_releases = [m for m in _parse_list(raw("new_releases"), allow_adult) if not m.has_prequel][:SHELF_LIMIT]
|
|
350
|
+
|
|
351
|
+
# Just finished: query already limits to the last 30 days, newest first.
|
|
352
|
+
just_finished = _parse_list(raw("just_finished"), allow_adult)[:SHELF_LIMIT]
|
|
353
|
+
|
|
354
|
+
# Upcoming: only entries with a confirmed premiere month.
|
|
355
|
+
upcoming = [m for m in _parse_list(raw("upcoming"), allow_adult) if m.is_date_confirmed][:UPCOMING_SHELF_LIMIT]
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
"spotlight": spotlight,
|
|
359
|
+
"trending": trending,
|
|
360
|
+
"popular": popular,
|
|
361
|
+
"new_releases": new_releases,
|
|
362
|
+
"just_finished": just_finished,
|
|
363
|
+
"upcoming": upcoming,
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
HOME_CACHE_TTL = 20 * 60 # seconds
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _home_cache_path():
|
|
371
|
+
return cache_dir() / "home_cache.json"
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def get_home_shelves_sync(allow_adult: Optional[bool] = None, use_cache: bool = True) -> Dict[str, List[AnimeMedia]]:
|
|
375
|
+
allow = _resolve_adult(allow_adult)
|
|
376
|
+
path = _home_cache_path()
|
|
377
|
+
|
|
378
|
+
if use_cache:
|
|
379
|
+
try:
|
|
380
|
+
blob = json.loads(path.read_text(encoding="utf-8"))
|
|
381
|
+
fresh = time.time() - blob.get("fetched_at", 0) < HOME_CACHE_TTL
|
|
382
|
+
if fresh and blob.get("allow_adult") == allow and blob.get("date") == date.today().isoformat():
|
|
383
|
+
return build_shelves(blob["data"], allow)
|
|
384
|
+
except Exception:
|
|
385
|
+
pass
|
|
386
|
+
|
|
387
|
+
month_ago = _fuzzy_int(date.today() - timedelta(days=30))
|
|
388
|
+
res_json = _send_query(_home_query(allow), {"monthAgo": month_ago})
|
|
389
|
+
data = res_json.get("data") or {}
|
|
390
|
+
try:
|
|
391
|
+
path.write_text(json.dumps({
|
|
392
|
+
"fetched_at": time.time(),
|
|
393
|
+
"allow_adult": allow,
|
|
394
|
+
"date": date.today().isoformat(),
|
|
395
|
+
"data": data,
|
|
396
|
+
}), encoding="utf-8")
|
|
397
|
+
except Exception:
|
|
398
|
+
pass
|
|
399
|
+
return build_shelves(data, allow)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def get_upcoming_sync(page: int = 1, per_page: int = 50,
|
|
403
|
+
allow_adult: Optional[bool] = None) -> Tuple[List[AnimeMedia], bool]:
|
|
404
|
+
"""Full upcoming list for a "see all" screen. Returns (items, has_next_page)."""
|
|
405
|
+
allow = _resolve_adult(allow_adult)
|
|
406
|
+
q = f"""
|
|
407
|
+
query ($page: Int, $perPage: Int) {{
|
|
408
|
+
Page(page: $page, perPage: $perPage) {{
|
|
409
|
+
pageInfo {{ hasNextPage }}
|
|
410
|
+
media(type: ANIME, status: NOT_YET_RELEASED, sort: POPULARITY_DESC, {_adult_arg(allow)}) {{
|
|
411
|
+
{MEDIA_FIELDS}
|
|
412
|
+
}}
|
|
413
|
+
}}
|
|
414
|
+
}}
|
|
415
|
+
"""
|
|
416
|
+
res = _send_query(q, {"page": page, "perPage": per_page})
|
|
417
|
+
page_data = (res.get("data") or {}).get("Page") or {}
|
|
418
|
+
items = [m for m in _parse_list(page_data.get("media"), allow) if m.is_date_confirmed]
|
|
419
|
+
return items, bool((page_data.get("pageInfo") or {}).get("hasNextPage"))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# --------------------------------------------------------------------------
|
|
423
|
+
# Weekly schedule
|
|
424
|
+
# --------------------------------------------------------------------------
|
|
425
|
+
|
|
426
|
+
SCHEDULE_QUERY = """
|
|
427
|
+
query ($start: Int, $end: Int, $page: Int) {
|
|
428
|
+
Page(page: $page, perPage: 50) {
|
|
429
|
+
pageInfo { hasNextPage }
|
|
430
|
+
airingSchedules(airingAt_greater: $start, airingAt_lesser: $end, sort: TIME) {
|
|
431
|
+
airingAt
|
|
432
|
+
episode
|
|
433
|
+
media {
|
|
434
|
+
id
|
|
435
|
+
title { romaji english }
|
|
436
|
+
coverImage { large }
|
|
437
|
+
format
|
|
438
|
+
isAdult
|
|
439
|
+
episodes
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
"""
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def week_bounds(now: Optional[datetime] = None) -> Tuple[int, int]:
|
|
448
|
+
"""Unix timestamps for Monday 00:00 (local time) to the following Monday."""
|
|
449
|
+
now = now or datetime.now()
|
|
450
|
+
monday = datetime.combine(now.date() - timedelta(days=now.weekday()), datetime.min.time())
|
|
451
|
+
next_monday = monday + timedelta(days=7)
|
|
452
|
+
return int(monday.timestamp()), int(next_monday.timestamp())
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _schedule_cache_path():
|
|
456
|
+
return config_dir() / "schedule_cache.json"
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _read_schedule_cache(week_start: int, allow_adult: bool):
|
|
460
|
+
try:
|
|
461
|
+
blob = json.loads(_schedule_cache_path().read_text(encoding="utf-8"))
|
|
462
|
+
if (blob.get("week_start") == week_start
|
|
463
|
+
and blob.get("allow_adult") == allow_adult
|
|
464
|
+
and time.time() - blob.get("fetched_at", 0) < SCHEDULE_CACHE_TTL):
|
|
465
|
+
return blob.get("data")
|
|
466
|
+
except Exception:
|
|
467
|
+
pass
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _write_schedule_cache(week_start: int, allow_adult: bool, data: dict):
|
|
472
|
+
try:
|
|
473
|
+
_schedule_cache_path().write_text(json.dumps({
|
|
474
|
+
"week_start": week_start,
|
|
475
|
+
"allow_adult": allow_adult,
|
|
476
|
+
"fetched_at": time.time(),
|
|
477
|
+
"data": data,
|
|
478
|
+
}), encoding="utf-8")
|
|
479
|
+
except Exception:
|
|
480
|
+
pass
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def build_schedule(entries: List[dict], week_start: int, allow_adult: bool) -> Dict[str, List[Dict[str, Any]]]:
|
|
484
|
+
"""Groups raw airingSchedules entries into local-time weekdays."""
|
|
485
|
+
schedule: Dict[str, List[Dict[str, Any]]] = {day: [] for day in DAYS_OF_WEEK}
|
|
486
|
+
seen = set()
|
|
487
|
+
for e in entries:
|
|
488
|
+
media = e.get("media") or {}
|
|
489
|
+
if media.get("format") not in SCHEDULE_FORMATS:
|
|
490
|
+
continue
|
|
491
|
+
genres_lower = [g.lower() for g in (media.get("genres") or [])]
|
|
492
|
+
if not allow_adult and (media.get("isAdult") or "ecchi" in genres_lower or "hentai" in genres_lower):
|
|
493
|
+
continue
|
|
494
|
+
key = (media.get("id"), e.get("episode"))
|
|
495
|
+
if key in seen:
|
|
496
|
+
continue
|
|
497
|
+
seen.add(key)
|
|
498
|
+
|
|
499
|
+
airing_at = e.get("airingAt")
|
|
500
|
+
if airing_at is None:
|
|
501
|
+
continue
|
|
502
|
+
local = datetime.fromtimestamp(airing_at)
|
|
503
|
+
t = media.get("title") or {}
|
|
504
|
+
schedule[DAYS_OF_WEEK[local.weekday()]].append({
|
|
505
|
+
"id": media.get("id"),
|
|
506
|
+
"title": t.get("english") or t.get("romaji") or "Unknown",
|
|
507
|
+
"episode": e.get("episode"),
|
|
508
|
+
"airing_at": airing_at,
|
|
509
|
+
"time": local.strftime("%H:%M"),
|
|
510
|
+
"cover_url": (media.get("coverImage") or {}).get("large", ""),
|
|
511
|
+
"format": media.get("format"),
|
|
512
|
+
"is_adult": bool(media.get("isAdult")),
|
|
513
|
+
})
|
|
514
|
+
for items in schedule.values():
|
|
515
|
+
items.sort(key=lambda x: x["airing_at"])
|
|
516
|
+
return schedule
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def get_weekly_schedule_sync(start_timestamp: Optional[int] = None,
|
|
520
|
+
allow_adult: Optional[bool] = None,
|
|
521
|
+
use_cache: bool = True) -> Dict[str, List[Dict[str, Any]]]:
|
|
522
|
+
allow = _resolve_adult(allow_adult)
|
|
523
|
+
if start_timestamp is None:
|
|
524
|
+
week_start, week_end = week_bounds()
|
|
525
|
+
else:
|
|
526
|
+
week_start, week_end = start_timestamp, start_timestamp + 7 * 86400
|
|
527
|
+
|
|
528
|
+
if use_cache:
|
|
529
|
+
cached = _read_schedule_cache(week_start, allow)
|
|
530
|
+
if cached:
|
|
531
|
+
return cached
|
|
532
|
+
|
|
533
|
+
entries: List[dict] = []
|
|
534
|
+
# AniList caps pages at 50 items; a full week is typically 10-15 pages.
|
|
535
|
+
for page in range(1, 21):
|
|
536
|
+
res = _send_query(SCHEDULE_QUERY, {"start": week_start - 1, "end": week_end, "page": page})
|
|
537
|
+
page_data = (res.get("data") or {}).get("Page") or {}
|
|
538
|
+
entries.extend(page_data.get("airingSchedules") or [])
|
|
539
|
+
if not (page_data.get("pageInfo") or {}).get("hasNextPage"):
|
|
540
|
+
break
|
|
541
|
+
time.sleep(0.3)
|
|
542
|
+
|
|
543
|
+
data = build_schedule(entries, week_start, allow)
|
|
544
|
+
_write_schedule_cache(week_start, allow, data)
|
|
545
|
+
return data
|
hayate/core/history.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from hayate.core.settings import config_dir
|
|
6
|
+
|
|
7
|
+
def history_file() -> Path:
|
|
8
|
+
return config_dir() / "history.json"
|
|
9
|
+
|
|
10
|
+
class HistoryManager:
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self.file_path = history_file()
|
|
13
|
+
self.data = self._load()
|
|
14
|
+
|
|
15
|
+
def _load(self) -> dict:
|
|
16
|
+
if not self.file_path.exists():
|
|
17
|
+
return {}
|
|
18
|
+
try:
|
|
19
|
+
return json.loads(self.file_path.read_text(encoding="utf-8"))
|
|
20
|
+
except Exception:
|
|
21
|
+
# Unreadable/corrupt file: keep a copy so the history isn't silently lost.
|
|
22
|
+
try:
|
|
23
|
+
self.file_path.replace(self.file_path.with_suffix(".json.corrupt"))
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
return {}
|
|
27
|
+
|
|
28
|
+
def _save(self):
|
|
29
|
+
# Write to a temp file then swap it in, so a crash mid-write can't corrupt history.
|
|
30
|
+
tmp = self.file_path.with_suffix(".json.tmp")
|
|
31
|
+
try:
|
|
32
|
+
tmp.write_text(json.dumps(self.data, indent=2), encoding="utf-8")
|
|
33
|
+
os.replace(tmp, self.file_path)
|
|
34
|
+
except Exception as e:
|
|
35
|
+
print(f"[history] Failed to save history: {e}")
|
|
36
|
+
|
|
37
|
+
def record_watch(self, anime_id: int, title: str, episode: int, cover_url: str = "",
|
|
38
|
+
banner_url: str = "", total_episodes: int = 0, **kwargs):
|
|
39
|
+
return self.mark_watched(anime_id=anime_id, title=title, episode=episode, cover_url=cover_url)
|
|
40
|
+
|
|
41
|
+
def mark_watched(self, anime_id: int, title: str, episode: int, cover_url: str = ""):
|
|
42
|
+
key = str(anime_id)
|
|
43
|
+
entry = self.data.get(key, {
|
|
44
|
+
"id": anime_id,
|
|
45
|
+
"title": title,
|
|
46
|
+
"cover_url": cover_url,
|
|
47
|
+
"watched_episodes": [],
|
|
48
|
+
"last_episode": episode,
|
|
49
|
+
"updated_at": 0
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
if episode not in entry["watched_episodes"]:
|
|
53
|
+
entry["watched_episodes"].append(episode)
|
|
54
|
+
entry["watched_episodes"].sort()
|
|
55
|
+
|
|
56
|
+
entry["last_episode"] = episode
|
|
57
|
+
entry["title"] = title
|
|
58
|
+
if cover_url:
|
|
59
|
+
entry["cover_url"] = cover_url
|
|
60
|
+
entry["updated_at"] = int(time.time())
|
|
61
|
+
|
|
62
|
+
self.data[key] = entry
|
|
63
|
+
self._save()
|
|
64
|
+
|
|
65
|
+
def get_watched_episodes(self, anime_id: int) -> set[int]:
|
|
66
|
+
entry = self.data.get(str(anime_id))
|
|
67
|
+
if entry:
|
|
68
|
+
return set(entry.get("watched_episodes", []))
|
|
69
|
+
return set()
|
|
70
|
+
|
|
71
|
+
def get_next_episode(self, anime_id: int, total_episodes: int) -> int:
|
|
72
|
+
entry = self.data.get(str(anime_id))
|
|
73
|
+
if not entry:
|
|
74
|
+
return 1
|
|
75
|
+
last = entry.get("last_episode", 0)
|
|
76
|
+
watched = set(entry.get("watched_episodes", []))
|
|
77
|
+
|
|
78
|
+
# Suggest the next unwatched episode
|
|
79
|
+
candidate = last + 1
|
|
80
|
+
if candidate <= total_episodes and candidate not in watched:
|
|
81
|
+
return candidate
|
|
82
|
+
|
|
83
|
+
for ep in range(1, total_episodes + 1):
|
|
84
|
+
if ep not in watched:
|
|
85
|
+
return ep
|
|
86
|
+
|
|
87
|
+
return min(last or 1, total_episodes)
|
|
88
|
+
|
|
89
|
+
def get_recent_history(self, limit: int = 10) -> list[dict]:
|
|
90
|
+
items = list(self.data.values())
|
|
91
|
+
items.sort(key=lambda x: x.get("updated_at", 0), reverse=True)
|
|
92
|
+
return items[:limit]
|
|
93
|
+
|
|
94
|
+
# Singleton instance
|
|
95
|
+
history_mgr = HistoryManager()
|