-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher.py
234 lines (222 loc) · 9.3 KB
/
fetcher.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
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
import requests
import os
import smtplib
import configparser
import json
import requests
import logging
import img2pdf
from email.message import EmailMessage
from PIL import Image
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
logging.basicConfig(filename='errors.log', format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p', level=logging.INFO)
config = configparser.ConfigParser()
config.read('config/config.cfg')
id_items = config.items("manga")
base_url = config["mangadex_api_url"]["base_url"]
languages = config["manga_config"]["languages"]
def fetcher(key, id):
try:
with open("records.json", "r") as jsonFile:
data = json.load(jsonFile)
except Exception as e:
logging.error(e)
os.exit()
#print(base_url)
#print(data["mangas"][key]["id"])
try:
payload = {"translatedLanguage[]": languages, "order[chapter]" : "desc", "limit": 1}
r = requests.get(
f"{base_url}/manga/{id}/feed",
params=payload,
)
#print([chapter["attributes"]["chapter"] for chapter in r.json()["data"]][0])
if ([chapter["attributes"]["chapter"] for chapter in r.json()["data"]][0]) != data["mangas"][key]["latest"]:
#print([chapter["attributes"]["chapter"] for chapter in r.json()["data"]])
latestchapterdata = [chapter for chapter in r.json()["data"]]
emailstatus = emailnotif(r.json()["data"])
if emailstatus != True:
data["mangas"][key]["email"] = "false"
logging.error("something with email failed")
#os.exit() commented out for now,enable if you want whole to fail
else:
try:
with open("records.json", "r") as jsonFile:
data = json.load(jsonFile)
data["mangas"][key]["email"] = "true"
with open("records.json", "w") as jsonFile:
json.dump(data, jsonFile)
except Exception as e:
logging.error(e)
os.exit()
"""
chapteremailstatus = chapteremail(latestchapterdata)
if chapteremailstatus != True:
data["mangas"][key]["chapteremailed"] = "false"
logging.error("something with email failed")
# os.exit() commented out for now enale if you dont want new chapter to show up in json aswell
else:
try:
with open("records.json", "r") as jsonFile:
data = json.load(jsonFile)
data["mangas"][key]["chapteremailed"] = "true"
with open("records.json", "w") as jsonFile:
json.dump(data, jsonFile)
except Exception as e:
logging.error(e)
os.exit()
"""
try:
with open("records.json", "r") as jsonFile:
data = json.load(jsonFile)
data["mangas"][key]["latest"] = ([chapter["attributes"]["chapter"] for chapter in r.json()["data"]][0])
with open("records.json", "w") as jsonFile:
json.dump(data, jsonFile)
except Exception as e:
logging.error(e)
os.exit()
else:
print("already updated not running")
logging.info("already updated not running")
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
logging.error(errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
logging.error(errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
logging.error(errt)
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
logging.error(err)
def emailnotif(latestchapterdata):
# get email and password from environment variables
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_RECIPIENT = os.environ.get('EMAIL_RECIPIENT')
#print(EMAIL_PASSWORD)
# set up email content
#([chapter["attributes"]["chapter"] for chapter in r.json()["data"]][0])
#chap = ([chapter["attributes"]["chapter"] for chapter in latestchapterdata][0])
#print(str(chap))
msg = EmailMessage()
msg['Subject'] = ([chapter["attributes"]["chapter"] for chapter in latestchapterdata][0]) + " has been released"
#print(msg['Subject'])
msg['From'] = EMAIL_ADDRESS
msg['To'] = EMAIL_RECIPIENT
msg.set_content(([chapter["attributes"]["chapter"] for chapter in latestchapterdata][0]) + " has been released")
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
return True
except Exception as e:
logging.error(e)
print(e)
return False
for key, id in enumerate(id_items):
fetcher(key ,id[1])
"""
def chapteremail(latestchapterdata):
try:
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_RECIPIENT = os.environ.get('EMAIL_RECIPIENT')
id = ([chapter["id"] for chapter in latestchapterdata][0])
latestchapter = ([chapter["attributes"]["chapter"] for chapter in latestchapterdata][0])
#print(id)
r = requests.get(
f"{base_url}/at-home/server/{id}"
)
r_json = r.json()
#print(r.status_code)
host = r_json["baseUrl"]
chapter_hash = r_json["chapter"]["hash"]
data = r_json["chapter"]["data"]
folder_path = f"Chapters/{latestchapter}"
os.makedirs(folder_path, exist_ok=True)
# fetch pages from mangadex
for page in data:
r = requests.get(f"{host}/data/{chapter_hash}/{page}")
with open(f"{folder_path}/{page}", mode="wb") as f:
f.write(r.content)
imgs = []
for fname in os.listdir(folder_path):
if not fname.endswith(".png"):
continue
path = os.path.join(folder_path, fname)
if os.path.isdir(path):
continue
imgs.append(path)
publish = sorted(imgs, key=os.path.getmtime)
with open(latestchapter+".html","a") as file:
file.write('''<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img {
border: 1px solid #555;
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 5px;
margin-bottom: 5px;
}
</style>
</head>
<body>''')
for image in publish:
file.write('''<div class="card"><img src="'''+image+'''" align="center" style="width:50%; alt=" "/>''')
file.write('\n')
file.write('''</body>''')
file.write('\n')
file.write('''</html>''')
msg = MIMEMultipart()
msg['Subject'] = ([chapter["attributes"]["chapter"] for chapter in latestchapterdata][0]) + " has been released find attached chapter"
#print(msg['Subject'])
msg['From'] = EMAIL_ADDRESS
msg['To'] = EMAIL_RECIPIENT
#email content
message = """ """<html> here the upper commas for comment out stay for html tags,only other go
<body>
Attached is the chapter
<br><br>
</body>
</html>
msg.attach(MIMEText(message, 'html'))
publish.append(latestchapter+".html")
for a_file in publish:
attachment = open(a_file, 'rb')
file_name = os.path.basename(a_file)
part = MIMEBase('application','octet-stream')
part.set_payload(attachment.read())
part.add_header('Content-Disposition',
'attachment',
filename=file_name)
encoders.encode_base64(part)
msg.attach(part)
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.sendmail(EMAIL_ADDRESS, EMAIL_RECIPIENT, msg.as_string())
return True
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
logging.error(errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
logging.error(errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
logging.error(errt)
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
logging.error(err)
except Exception as e:
logging.error(e)
return False
"""