-
Notifications
You must be signed in to change notification settings - Fork 3
/
mainRunner.py
167 lines (149 loc) · 6.94 KB
/
mainRunner.py
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
import datetime
import glob
import html
import tempfile
import traceback
from typing import List, Optional, Set, BinaryIO
from pathlib import Path
from cross.decorators import Logger
from manga.updateAnilistIds import UpdateTrackerIds
from manga.mangagetchapter import CalculateChapterName
from manga.deleteReadAnilist import DeleteReadChapters
from manga.missingChapters import CheckGapsInChapters
from manga.createMetadata import CreateMetadataInterface
from manga.gateways.pushover import PushServiceInterface
from manga.gateways.database import DatabaseGateway
from manga.gateways.filesystem import FilesystemInterface
from models.manga import Chapter, MissingChapter
# for each folder in sources
# databas -> select anilist id where series=x
# getChapter -> title
@Logger
class MainRunner:
def __init__(
self,
sourceFolder: str,
archiveFolder: str,
database: DatabaseGateway,
filesystem: FilesystemInterface,
push: PushServiceInterface,
missingChapters: CheckGapsInChapters,
deleteReadChapters: DeleteReadChapters,
calcChapterName: CalculateChapterName,
updateTrackerIds: UpdateTrackerIds,
createMetadata: CreateMetadataInterface,
) -> None:
self.database = database
self.pushNotification = push
self.filesystem = filesystem
self.sourceFolder = sourceFolder
self.archiveFolder = archiveFolder
self.missingChapters = missingChapters
self.deleteReadChapters = deleteReadChapters
self.calcChapterName = calcChapterName
self.updateTrackerIds = updateTrackerIds
self.createMetadata = createMetadata
def execute(self, interactive=False):
try:
new_chapters: Set[Chapter] = set()
dateScriptStart = datetime.datetime.now()
# Globs chapters
for chapterPathStr in glob.iglob(f"{self.sourceFolder}/*/*/*"):
self.logger.info(f"Parsing: {chapterPathStr}")
# Inferring information from files
chapterPath = Path(chapterPathStr)
chapterName = html.unescape(chapterPath.stem)
seriesName = html.unescape(chapterPath.parent.name)
anilistId = self.database.getAnilistIDForSeries(seriesName)
chapterNumber = self.calcChapterName.execute(chapterName, anilistId)
estimatedArchivePath = self.generateArchivePath(
anilistId, chapterNumber
)
chapterData = Chapter(
anilistId,
seriesName,
chapterNumber,
chapterName,
chapterPath,
estimatedArchivePath,
)
isChapterOnDB = self.database.doesExistChapterAndAnilist(
anilistId, chapterNumber
)
if not anilistId or anilistId is None:
foundAnilistId = self.findAnilistIdForSeries(
seriesName, interactive=interactive
)
estimatedArchivePath = self.generateArchivePath(
foundAnilistId, chapterNumber
)
chapterData.archivePath = estimatedArchivePath
if not foundAnilistId or foundAnilistId is None:
self.logger.error(f"No anilistId for {chapterData.seriesName}")
return
chapterData.anilistId = foundAnilistId
else:
self.logger.debug(f"Already had tracker ID: {anilistId}")
if not isChapterOnDB:
# Creates temporary place to store metadata before putting in CBZ
with tempfile.NamedTemporaryFile() as metadata_file:
self.setupMetadata(chapterData, output=metadata_file)
self.prepareChapterCBZ(chapterData, Path(metadata_file.name))
self.insertInDatabase(chapterData)
new_chapters.add(chapterData)
self.filesystem.deleteSourceChapter(location=chapterPathStr)
else:
self.logger.info("Source exists but chapter's already in db")
self.filesystem.deleteSourceChapter(location=chapterPathStr)
deleted_chapters = self.deleteReadChapters.execute()
for deleted_chapter in deleted_chapters:
if deleted_chapter in new_chapters:
new_chapters.remove(deleted_chapter)
if len(new_chapters) > 0:
gaps = self.missingChapters.getGapsFromChaptersSince(dateScriptStart)
self.send_push(new_chapters, gaps)
except Exception as thrown_exception:
self.logger.error("Exception thrown")
trace = traceback.format_exc()
self.logger.error(trace)
self.send_error(trace)
def generateArchivePath(self, anilistId, chapterNumber):
return Path(self.archiveFolder).joinpath(f"{anilistId}/{chapterNumber}.cbz")
def findAnilistIdForSeries(self, series: str, interactive=False) -> Optional[str]:
return self.updateTrackerIds.updateFor(series, interactive=interactive)
def setupMetadata(self, chapter: Chapter, output: BinaryIO):
self.createMetadata.execute(chapter, output)
def prepareChapterCBZ(self, chapter: Chapter, metadata: Path):
# Source file is CBZ or a folder?
if chapter.sourcePath.is_file():
self.filesystem.move_source_cbz_to_archive(
chapter.archivePath, chapter.sourcePath
)
else:
self.filesystem.compress_chapter(
archive_path=chapter.archivePath, source_path=chapter.sourcePath
)
self.filesystem.put_comicinfo_in_cbz(
cbz=chapter.archivePath, comicinfo=metadata
)
def insertInDatabase(self, chapter: Chapter):
self.database.insertChapter(
chapter.seriesName,
chapter.chapterNumber,
str(chapter.archivePath.resolve()),
str(chapter.sourcePath.resolve()),
)
def send_push(self, chapters: Set[Chapter], gaps: List[MissingChapter]):
chapters_plural = "chapters" if len(chapters) > 1 else "chapter"
base = f"{len(chapters)} new {chapters_plural} downloaded\n\n"
titles = map(lambda x: f"{x.seriesName} {x.chapterNumber}", chapters)
sorted_titles = sorted(titles)
chapters_body = "\n".join(sorted_titles)
if len(gaps) > 0:
missing_title = "Updated in quarantine:"
missing_chapters = map(lambda x: x.reasonToPrint(), gaps)
missing_body = "\n".join(missing_chapters)
chapters_body += "\n\n" + missing_title + "\n" + missing_body
self.pushNotification.sendPush(base + chapters_body)
def send_error(self, value: Exception):
self.pushNotification.sendPush(str(value))