-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1125 lines (949 loc) · 39.2 KB
/
server.py
File metadata and controls
executable file
·1125 lines (949 loc) · 39.2 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: ignore-errors
import argparse
import logging
import os
import re
from typing import Any
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
from dlsite_classification.common.regex import REGEX_RG
from dlsite_classification.common.security import (
PathSecurityError,
validate_path_within_root,
)
from dlsite_classification.crawler.company import DLsiteCompanyCrawler
from dlsite_classification.extract.extract import ExtractFolder
from dlsite_classification.manager.manager_company_archive import (
create_company_archives,
)
from dlsite_classification.tools.url import build_image_url, decode_url_path
app = FastAPI(title="DLsite Collection Manager", version="1.0.0")
# Enable CORS for frontend
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:3001",
"http://127.0.0.1:3001",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_data_path():
"""獲取數據路徑,優先級:命令行參數 > 環境變數 > 預設值"""
# 1. 檢查命令行參數
parser = argparse.ArgumentParser(description="DLsite Collection Manager API Server")
parser.add_argument(
"--data-path", "-d", help="Path to DLsite collection data directory"
)
parser.add_argument(
"--port",
"-p",
type=int,
default=8001,
help="Port to run the server on (default: 8001)",
)
parser.add_argument(
"--host",
default="0.0.0.0",
help="Host to bind the server to (default: 0.0.0.0)",
)
# 只解析已知的參數,避免與 uvicorn 的參數衝突
args, unknown = parser.parse_known_args()
if args.data_path:
return args.data_path, args.port, args.host
# 2. 檢查環境變數
env_path = os.getenv("DLSITE_DATA_PATH")
if env_path:
return env_path, args.port, args.host
# 3. 使用預設值
default_paths = [
"./test_game_info", # 測試數據
"/mnt/d/R18/DLsite", # 原始預設路徑
"./data", # 通用數據路徑
]
for path in default_paths:
if os.path.exists(path):
return path, args.port, args.host
# 如果都不存在,使用第一個作為預設值
return default_paths[0], args.port, args.host
# 獲取數據路徑和伺服器配置
DATA_PATH, SERVER_PORT, SERVER_HOST = get_data_path()
extract_data = ExtractFolder(DATA_PATH)
print(f"🗂️ Data path: {DATA_PATH}")
print(f"🌐 Server will run on: http://{SERVER_HOST}:{SERVER_PORT}")
# 標準化和去重函數
def normalize_and_deduplicate_list(items):
"""標準化和去重列表項目"""
if not items:
return []
normalized_items = set()
for item in items:
if item and isinstance(item, str):
# 移除前後空格和特殊字符
cleaned = item.strip().strip("/")
if cleaned:
# 移除多餘的空格和末尾空格
cleaned = re.sub(r"\s+", " ", cleaned).strip()
# 移除重複的空格標記(如 "ロリ " -> "ロリ")
if cleaned not in [existing.strip() for existing in normalized_items]:
normalized_items.add(cleaned)
return sorted(list(normalized_items))
def smart_merge_similar_items(items):
"""智能合併相似項目"""
if not items:
return []
merged = {}
for item in items:
# 標準化項目
base_item = item.strip().rstrip(" ")
# 檢查是否有相似項目已存在
found_similar = False
for existing_key in list(merged.keys()):
# 如果完全匹配或只差空格,合併
if (
base_item == existing_key
or base_item.replace(" ", "") == existing_key.replace(" ", "")
or base_item == existing_key.rstrip(" ")
or base_item.rstrip(" ") == existing_key
):
merged[existing_key] += 1
found_similar = True
break
if not found_similar:
merged[base_item] = 1
return [
{"name": k, "count": v}
for k, v in sorted(merged.items(), key=lambda x: x[1], reverse=True)
]
def split_and_normalize_formats(format_string):
"""分割並標準化作品形式字串"""
if not format_string or not isinstance(format_string, str):
return []
# 移除開頭的 "/"
cleaned = format_string.strip().lstrip("/")
if not cleaned:
return []
# 分割多個格式 (以 / 或 , 分隔)
parts = re.split(r"[/,]", cleaned)
normalized_parts = []
for part in parts:
part = part.strip()
if part and part not in ["", "/"]:
# 標準化常見格式
if "音声あり" in part and "音楽あり" in part and "動画あり" in part:
base = (
part.replace("音声あり", "")
.replace("音楽あり", "")
.replace("動画あり", "")
.strip()
)
if base:
normalized_parts.append(base)
normalized_parts.append("音声あり")
normalized_parts.append("音楽あり")
normalized_parts.append("動画あり")
elif "音声あり" in part and "音楽あり" in part:
base = part.replace("音声あり", "").replace("音楽あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("音声あり")
normalized_parts.append("音楽あり")
elif "音声あり" in part and "動画あり" in part:
base = part.replace("音声あり", "").replace("動画あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("音声あり")
normalized_parts.append("動画あり")
elif "音楽あり" in part and "動画あり" in part:
base = part.replace("音楽あり", "").replace("動画あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("音楽あり")
normalized_parts.append("動画あり")
elif "音声あり" in part:
base = part.replace("音声あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("音声あり")
elif "音楽あり" in part:
base = part.replace("音楽あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("音楽あり")
elif "動画あり" in part:
base = part.replace("動画あり", "").strip()
if base:
normalized_parts.append(base)
normalized_parts.append("動画あり")
else:
normalized_parts.append(part)
return normalize_and_deduplicate_list(normalized_parts)
class WorkResponse(BaseModel):
code: str
title: str
company: str
genre: list[str]
image_url: str
sample_images: list[str]
introduction: str
sale_date: str | None
work_format: list[str]
age_rating: list[str]
file_size: list[str]
my_rating: str | None = None
my_collection: str | None = None
my_collections: list[str] | None = None
class CompanyResponse(BaseModel):
name: str
work_count: int
works: list[WorkResponse]
class SearchResponse(BaseModel):
total: int
works: list[WorkResponse]
companies: list[str]
genres: list[str]
# Helper function to convert work data
def convert_work_to_response(work: Any, work_folder: str) -> WorkResponse | None:
try:
if not work.info or not work.info.tag:
return None
tag = work.info.tag
# Extract title
title = work.name
if tag.title and isinstance(tag.title, dict):
title = list(tag.title.keys())[0] if tag.title else work.name
# Extract company
company = "Unknown"
if tag.company and isinstance(tag.company, dict):
company = list(tag.company.keys())[0]
# Extract genres and deduplicate
genre = []
if tag.genre and isinstance(tag.genre, dict):
# Remove duplicates while preserving order and filtering empty values
seen = set()
for g in tag.genre:
if g and g.strip(): # Filter out empty or whitespace-only strings
g_cleaned = g.strip()
g_lower = g_cleaned.lower()
if g_lower not in seen:
seen.add(g_lower)
genre.append(g_cleaned)
# Extract work format with smart splitting and normalization
work_format = []
if tag.work_format and isinstance(tag.work_format, dict):
for format_str in tag.work_format:
work_format.extend(split_and_normalize_formats(format_str))
work_format = normalize_and_deduplicate_list(work_format)
# Extract age rating
age_rating = []
if tag.age and isinstance(tag.age, dict):
age_rating = list(tag.age.keys())
# Extract file size (keeping original for size info)
file_size = []
if tag.file_capacity and isinstance(tag.file_capacity, dict):
file_size = normalize_and_deduplicate_list(list(tag.file_capacity.keys()))
# Extract sale date
sale_date = None
if tag.sale_date and isinstance(tag.sale_date, dict):
sale_date = list(tag.sale_date.keys())[0] if tag.sale_date else None
# Extract user rating
my_rating = None
if hasattr(tag, "my_rating") and tag.my_rating:
my_rating = tag.my_rating
# Extract user collection
my_collection = None
if hasattr(tag, "my_collection") and tag.my_collection:
my_collection = tag.my_collection
# Extract user collections (multiple)
my_collections = None
if hasattr(tag, "my_collections") and tag.my_collections:
my_collections = tag.my_collections
# Get main image
main_image = None
sample_images = []
if work.info.images:
for img in work.info.images:
if "img_main" in img:
main_image = build_image_url(os.path.join(work.info.path, img))
elif "img_smp" in img:
sample_images.append(
build_image_url(os.path.join(work.info.path, img))
)
if not main_image and work.info.images:
main_image = build_image_url(
os.path.join(work.info.path, work.info.images[0])
)
return WorkResponse(
code=work.code,
title=title,
company=company,
genre=genre,
image_url=main_image or "",
sample_images=sample_images,
introduction=tag.introduction or "",
sale_date=sale_date,
work_format=work_format,
age_rating=age_rating,
file_size=file_size,
my_rating=my_rating,
my_collection=my_collection,
my_collections=my_collections,
)
except Exception as e:
logging.exception(
"Error converting work to response for folder %s: %s", work_folder, e
)
return None
@app.get("/")
async def root():
return {"message": "DLsite Collection Manager API"}
@app.get("/status")
async def status():
"""Check API status and data loading"""
if not extract_data.classification_table:
try:
await extract_data.scan_file()
except Exception as e:
return {"status": "error", "message": f"Failed to scan files: {e}"}
total_companies = len(extract_data.classification_table)
total_works = sum(
len(company.work_item) for company in extract_data.classification_table.values()
)
return {
"status": "ok",
"total_companies": total_companies,
"total_works": total_works,
"data_path": DATA_PATH,
}
@app.get("/works", response_model=SearchResponse)
async def get_works(
search: str | None = Query(None, description="Search in title, company, genre"),
company: str | None = Query(None, description="Filter by company"),
collection: str | None = Query(None, description="Filter by collection"),
rating: str | None = Query(None, description="Filter by rating"),
tags: str | None = Query(None, description="Filter by tags (comma-separated)"),
tag_mode: str = Query("OR", description="Tag filter mode: OR or AND"),
work_format: str | None = Query(None, description="Filter by work format"),
file_format: str | None = Query(None, description="Filter by file format"),
sort: str = Query(
"title", description="Sort by: title, sale_date, company, rating, collection"
),
limit: int = Query(24, ge=1, le=100),
offset: int = Query(0, ge=0),
):
# Ensure data is scanned
if not extract_data.classification_table:
await extract_data.scan_file()
all_works = []
all_companies = set()
all_genres = set()
# Process all companies and works
for company_folder, company_data in extract_data.classification_table.items():
# Extract company name from the first work's company.tag instead of folder name
company_display_name = company_folder
if company_data.work_item:
first_work = next(iter(company_data.work_item.values()))
if first_work.info and first_work.info.tag and first_work.info.tag.company:
company_name_from_tag = list(first_work.info.tag.company.keys())[0]
company_display_name = company_name_from_tag
all_companies.add(company_display_name)
for work_folder, work in company_data.work_item.items():
work_response = convert_work_to_response(work, work_folder)
if work_response:
# Fix company name display
work_response.company = company_display_name
all_works.append(work_response)
# Add genres to global collection for statistics
for genre in work_response.genre:
if genre and genre.strip():
all_genres.add(genre.strip())
# Apply filters
filtered_works = all_works
# Text search
if search:
search_lower = search.lower()
filtered_works = [
work
for work in filtered_works
if (
search_lower in work.title.lower()
or search_lower in work.company.lower()
or search_lower in work.code.lower()
or search_lower in work.introduction.lower()
or any(search_lower in genre.lower() for genre in work.genre)
)
]
# Company filter
if company:
filtered_works = [
work for work in filtered_works if company.lower() in work.company.lower()
]
# Collection filter
if collection:
filtered_works = [
work
for work in filtered_works
if (work.my_collection and collection.lower() in work.my_collection.lower())
or (
hasattr(work, "my_collections")
and work.my_collections
and any(collection.lower() in c.lower() for c in work.my_collections)
)
]
# Rating filter
if rating:
min_rating = int(rating)
filtered_works = [
work
for work in filtered_works
if work.my_rating and int(work.my_rating) >= min_rating
]
# Tag filter with OR/AND logic
if tags:
tag_list = [tag.strip().lower() for tag in tags.split(",")]
if tag_mode.upper() == "AND":
# AND mode: work must have ALL selected tags
filtered_works = [
work
for work in filtered_works
if all(
any(tag in genre.lower() for genre in work.genre)
for tag in tag_list
)
]
else:
# OR mode: work must have ANY of the selected tags
filtered_works = [
work
for work in filtered_works
if any(
any(tag in genre.lower() for genre in work.genre)
for tag in tag_list
)
]
# Work format filter
if work_format:
filtered_works = [
work
for work in filtered_works
if any(work_format.lower() in wf.lower() for wf in work.work_format)
]
# File format filter
if file_format:
filtered_works = [
work
for work in filtered_works
if any(file_format.lower() in ff.lower() for ff in work.file_size)
]
# Sorting with safe rating conversion
def safe_rating(w: WorkResponse) -> int:
try:
return int(w.my_rating) if w.my_rating is not None else 0
except (ValueError, TypeError):
return 0
if sort == "sale_date":
filtered_works.sort(key=lambda x: x.sale_date or "", reverse=True)
elif sort == "company":
filtered_works.sort(key=lambda x: x.company.lower())
elif sort == "rating":
filtered_works.sort(key=safe_rating, reverse=True)
elif sort == "collection":
filtered_works.sort(key=lambda x: x.my_collection or "")
else: # title
filtered_works.sort(key=lambda x: x.title.lower())
# Pagination
total = len(filtered_works)
paginated_works = filtered_works[offset : offset + limit]
return SearchResponse(
total=total,
works=paginated_works,
companies=sorted(list(all_companies)),
genres=sorted(list(all_genres)),
)
@app.get("/companies", response_model=list[CompanyResponse])
async def get_companies():
if not extract_data.classification_table:
await extract_data.scan_file()
companies = []
for company_name, company_data in extract_data.classification_table.items():
works = []
for work_folder, work in company_data.work_item.items():
work_response = convert_work_to_response(work, work_folder)
if work_response:
works.append(work_response)
if works:
# Get company display name from first work's tag
company_display_name = company_name
if works:
company_display_name = works[0].company
companies.append(
CompanyResponse(
name=company_display_name, work_count=len(works), works=works
)
)
return sorted(companies, key=lambda x: x.work_count, reverse=True)
@app.get("/work/{code}")
async def get_work_detail(code: str):
if not extract_data.classification_table:
await extract_data.scan_file()
for _company_name, company_data in extract_data.classification_table.items():
for work_folder, work in company_data.work_item.items():
if work.code == code:
work_response = convert_work_to_response(work, work_folder)
if work_response:
# Add additional detail information
tag = work.info.tag
additional_info = {
"series": list(tag.series.keys()) if tag.series else [],
"voice_actor": list(tag.voice_actor.keys())
if tag.voice_actor
else [],
"author": list(tag.author.keys()) if tag.author else [],
"illustration": list(tag.illustration.keys())
if tag.illustration
else [],
"scenario": list(tag.scenario.keys()) if tag.scenario else [],
"music": list(tag.music.keys()) if tag.music else [],
"file_format": list(tag.file_format.keys())
if tag.file_format
else [],
"operating_environment": list(tag.operating_environment.keys())
if tag.operating_environment
else [],
"update_date": list(tag.update_date.keys())
if tag.update_date
else [],
"star": tag.star if tag.star else None,
"pages": list(tag.pages.keys()) if tag.pages else [],
"event": list(tag.event.keys()) if tag.event else [],
"other": list(tag.other.keys()) if tag.other else [],
"languages": list(tag.languages.keys())
if tag.languages
else [],
}
return {**work_response.dict(), **additional_info}
raise HTTPException(status_code=404, detail="Work not found")
@app.get("/genres")
async def get_all_genres():
if not extract_data.classification_table:
await extract_data.scan_file()
genre_counts = {}
for _company_name, company_data in extract_data.classification_table.items():
for _work_folder, work in company_data.work_item.items():
if work.info and work.info.tag and work.info.tag.genre:
for genre in work.info.tag.genre:
if genre and genre.strip():
normalized_genre = genre.strip()
if normalized_genre in genre_counts:
genre_counts[normalized_genre] += 1
else:
genre_counts[normalized_genre] = 1
# 創建包含計數的標籤列表,按使用頻率排序
genres_with_counts = [
{"name": genre, "count": count}
for genre, count in genre_counts.items()
if count > 0 # 只包含有計數的標籤
]
# 按使用頻率排序(從高到低)
genres_with_counts.sort(key=lambda x: x["count"], reverse=True)
return {"genres": genres_with_counts}
@app.get("/work-formats")
async def get_all_work_formats():
if not extract_data.classification_table:
await extract_data.scan_file()
all_work_formats = set()
for _, company_data in extract_data.classification_table.items():
for _, work in company_data.work_item.items():
if work.info and work.info.tag and work.info.tag.work_format:
for format_str in work.info.tag.work_format:
normalized_formats = split_and_normalize_formats(format_str)
all_work_formats.update(normalized_formats)
return {"work_formats": sorted(list(all_work_formats))}
@app.get("/file-formats")
async def get_all_file_formats():
if not extract_data.classification_table:
await extract_data.scan_file()
all_file_formats = set()
for _, company_data in extract_data.classification_table.items():
for _, work in company_data.work_item.items():
if work.info and work.info.tag and work.info.tag.file_format:
for format_str in work.info.tag.file_format:
normalized_formats = split_and_normalize_formats(format_str)
all_file_formats.update(normalized_formats)
return {"file_formats": sorted(list(all_file_formats))}
class UserDataRequest(BaseModel):
rating: str | None = None
collection: str | None = None
collections: list[str] | None = None
class CompanyWorksStatusResponse(BaseModel):
"""Response for company works status comparison."""
company_id: str
company_name: str
total_on_dlsite: int
owned_works: list[dict[str, Any]]
missing_works: list[dict[str, Any]]
archive_status: dict[str, Any]
class CompanyListItem(BaseModel):
"""Company list item for dropdown."""
id: str
name: str
folder_name: str
work_count: int
class ArchiveCreationRequest(BaseModel):
"""Request body for archive creation."""
force_update: bool = False
@app.get("/companies/list")
async def get_companies_list():
"""Get list of all companies with their IDs for dropdown selection."""
if not extract_data.classification_table:
await extract_data.scan_file()
companies = []
for folder_name, company_data in extract_data.classification_table.items():
# Extract company ID from folder name
matches = REGEX_RG.findall(folder_name)
company_id = matches[0] if matches else ""
if company_id:
companies.append(
CompanyListItem(
id=company_id,
name=company_data.name,
folder_name=folder_name,
work_count=len(company_data.work_item),
)
)
# Sort by company name
companies.sort(key=lambda x: x.name)
return {"companies": [c.model_dump() for c in companies]}
@app.get("/company/{company_id}/works-status")
async def get_company_works_status(company_id: str):
"""Compare owned works vs all works on DLsite for a company.
Returns which works the user owns and which are missing.
"""
if not extract_data.classification_table:
await extract_data.scan_file()
# Find company folder
company_data = None
company_folder_path = None
for folder_name, data in extract_data.classification_table.items():
matches = REGEX_RG.findall(folder_name)
if matches and matches[0] == company_id:
company_data = data
company_folder_path = os.path.join(DATA_PATH, folder_name)
break
if not company_data:
raise HTTPException(status_code=404, detail=f"Company {company_id} not found")
# Get owned work codes
owned_codes = set()
owned_works_info = []
for work_folder, work in company_data.work_item.items():
if work.code:
owned_codes.add(work.code)
# Get basic work info
title = ""
if work.info and work.info.tag and work.info.tag.title:
if isinstance(work.info.tag.title, dict):
title = list(work.info.tag.title.keys())[0]
else:
title = str(work.info.tag.title)
owned_works_info.append(
{
"code": work.code,
"title": title,
"folder": work_folder,
}
)
# Try to get all work IDs from DLsite
try:
crawler = DLsiteCompanyCrawler(code=company_id)
all_dlsite_codes = await crawler.get_all_work_ids(rate_limit_delay=1.5)
except Exception as e:
logging.error(f"Failed to crawl company {company_id}: {e}")
# Return partial data if crawling fails
return CompanyWorksStatusResponse(
company_id=company_id,
company_name=company_data.name,
total_on_dlsite=-1, # Indicates crawl failure
owned_works=owned_works_info,
missing_works=[],
archive_status={
"error": str(e),
"has_archive": os.path.isdir(
os.path.join(company_folder_path or "", "ARCHIVE")
),
},
).model_dump()
# Calculate missing works
all_dlsite_set = set(all_dlsite_codes)
missing_codes = all_dlsite_set - owned_codes
missing_works = [
{"code": code, "title": "", "folder": ""} for code in missing_codes
]
# Check ARCHIVE status
archive_path = os.path.join(company_folder_path or "", "ARCHIVE")
archive_exists = os.path.isdir(archive_path)
archived_count = 0
if archive_exists:
for item in os.listdir(archive_path):
if item.endswith("_info") and os.path.isdir(
os.path.join(archive_path, item)
):
archived_count += 1
return CompanyWorksStatusResponse(
company_id=company_id,
company_name=company_data.name,
total_on_dlsite=len(all_dlsite_codes),
owned_works=owned_works_info,
missing_works=missing_works,
archive_status={
"has_archive": archive_exists,
"archived_count": archived_count,
"archive_path": archive_path if archive_exists else None,
},
).model_dump()
@app.post("/company/{company_id}/archive")
async def create_company_archive(company_id: str, request: ArchiveCreationRequest):
"""Create or update ARCHIVE folder for a specific company.
Downloads metadata for all works by this company from DLsite.
"""
if not extract_data.classification_table:
await extract_data.scan_file()
# Find company folder
company_folder_path = None
for folder_name in extract_data.classification_table:
matches = REGEX_RG.findall(folder_name)
if matches and matches[0] == company_id:
company_folder_path = os.path.join(DATA_PATH, folder_name)
break
if not company_folder_path:
raise HTTPException(status_code=404, detail=f"Company {company_id} not found")
try:
results = await create_company_archives(
data_path=DATA_PATH,
specific_company_id=company_id,
force_update=request.force_update,
max_concurrent_works=3,
rate_limit_delay=2.5,
)
return {
"status": "success",
"company_id": company_id,
"works_archived": results.get(company_id, 0),
}
except Exception as e:
logging.error(f"Failed to create archive for {company_id}: {e}")
raise HTTPException(
status_code=500, detail=f"Archive creation failed: {e}"
) from e
@app.get("/company/{company_id}/archive-info")
async def get_company_archive_info(company_id: str):
"""Get detailed ARCHIVE information for a company.
Returns list of all archived works with their info status.
"""
if not extract_data.classification_table:
await extract_data.scan_file()
# Find company folder
company_folder_path = None
company_name = ""
for folder_name, data in extract_data.classification_table.items():
matches = REGEX_RG.findall(folder_name)
if matches and matches[0] == company_id:
company_folder_path = os.path.join(DATA_PATH, folder_name)
company_name = data.name
break
if not company_folder_path:
raise HTTPException(status_code=404, detail=f"Company {company_id} not found")
archive_path = os.path.join(company_folder_path, "ARCHIVE")
if not os.path.isdir(archive_path):
return {
"company_id": company_id,
"company_name": company_name,
"has_archive": False,
"archived_works": [],
}
# List all archived works
archived_works = []
for item in os.listdir(archive_path):
if item.endswith("_info") and os.path.isdir(os.path.join(archive_path, item)):
work_code = item.replace("_info", "")
info_path = os.path.join(archive_path, item)
# Get basic info from tags if available
title = ""
title_tag = os.path.join(info_path, "title.tag")
if os.path.isfile(title_tag):
try:
with open(title_tag, encoding="utf-8") as f:
title = f.read().strip().split("\n")[0]
except Exception:
pass
# Check if main image exists
has_image = any(
f.endswith(("_img_main.jpg", "_img_main.png", "_img_main.webp"))
for f in os.listdir(info_path)
)
archived_works.append(
{
"code": work_code,
"title": title,
"has_image": has_image,
"info_path": info_path,
}
)
# Sort by code
archived_works.sort(key=lambda x: x["code"])
return {
"company_id": company_id,
"company_name": company_name,
"has_archive": True,
"archived_count": len(archived_works),
"archived_works": archived_works,
}
@app.post("/work/{code}/user-data")
async def update_user_data(code: str, user_data: UserDataRequest):
"""Update user's rating and collection for a work"""
if not extract_data.classification_table:
await extract_data.scan_file()
# Find the work
for _, company_data in extract_data.classification_table.items():
for _, work in company_data.work_item.items():
if work.code == code:
if not work.info or not work.info.path:
raise HTTPException(status_code=404, detail="Work info not found")
info_path = work.info.path
# Save rating
if user_data.rating is not None:
rating_file = os.path.join(info_path, "my_rating.tag")
try:
with open(rating_file, "w", encoding="utf-8") as f:
f.write(user_data.rating)
# Update in-memory data immediately without full rescan
if work.info.tag:
work.info.tag.my_rating = user_data.rating
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Failed to save rating: {e}"
) from e
# Save single collection (backward compatibility)
if user_data.collection is not None:
collection_file = os.path.join(info_path, "my_collection.tag")
try:
with open(collection_file, "w", encoding="utf-8") as f:
f.write(user_data.collection)
# Update in-memory data immediately
if work.info.tag:
work.info.tag.my_collection = user_data.collection
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Failed to save collection: {e}"
) from e
# Save multiple collections
if user_data.collections is not None: