-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.py
161 lines (141 loc) · 5.72 KB
/
sync.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
#!/usr/bin/python3
# @author: aghontpi
# File is run by github-action everyday and -
# - syncs content with api
from pathlib import Path
import json
import requests
import datetime
class Utils(object):
def __init__(self):
self.offline_directory = Path(__file__).parent
self.download_directory = "api"
self.log_directory = "logs"
self.state_filename = "syncState.json"
self._log(
f"\n{'*'*20} {datetime.datetime.now().strftime('%Y-%m-%d')} {'*'*20}")
def _saveState(self, json_content):
self._log("updating syncState", json_content)
filepath = self.offline_directory.joinpath(self.state_filename)
with open(filepath, 'w') as writefile:
json.dump(json_content, writefile)
writefile.close()
def _log(self, log, _arg=''):
filepath = self.offline_directory.joinpath(self.log_directory)
log_string = f"{log} {str(_arg)}"
if not Path.is_dir(filepath):
Path(filepath).mkdir()
log_string = f"creating logs path\n" + log_string
filepath = filepath.joinpath('log.txt')
with open(filepath, 'a+') as logFile:
logFile.write(
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {log_string} \n")
logFile.close()
print(log_string)
def _saveContent(self, json_content):
id = json_content['num']
img_url = json_content['img']
img_name = img_url.split('/')[-1]
# handle no image for a specific json
if img_name == "":
self._log("no image for :", id)
return True
download_directory = self.offline_directory.joinpath(
self.download_directory)
if not Path.is_dir(download_directory):
try:
Path(download_directory).mkdir()
except:
self._log("can not create api directory")
return False
self._log("saving in new directory :",
download_directory.as_posix())
download_directory = download_directory.joinpath(str(id))
if not Path.is_dir(download_directory):
try:
Path(download_directory).mkdir()
except:
self._log("can not create offline directory")
return False
self._log("saving in new directory : ",
download_directory.as_posix())
# save assests
img = requests.get(img_url)
if img.status_code != 200:
self._log("error downloading image :", img_url)
return False
file_path = download_directory.joinpath(img_name)
with open(file_path, 'wb') as save_file:
save_file.write(img.content)
save_file.close()
# saving the info.json
file_path = download_directory.joinpath('info.0.json')
json_content[
'mirror_img'] = f'https://raw.githubusercontent.com/aghontpi/mirror-xkcd-api/main/api/{id}/{img_name}'
with open(file_path, 'w') as save_file:
json.dump(json_content, save_file)
save_file.close()
return True
class Sync(Utils):
def __init__(self):
self.urllink = 'https://xkcd.com/info.0.json'
self.local_content = None
self.remote_content = None
super(Sync, self).__init__()
def sync(self):
if self._parseLocalstate()._parseRemoteState()._compareLocalAndRemote():
self._log('no new content to sync')
exit()
self.downloadNewContent()
def _parseLocalstate(self):
filepath = self.offline_directory.joinpath(self.state_filename)
if not Path.is_file(filepath):
# not present, creating file
self._log('creating local state file ')
with open(filepath, 'w') as create_file:
create_file.write('{"last_update_content": {"id": "1"}}')
create_file.close()
with open(filepath, encoding='utf-8') as json_file:
data = json.loads(json_file.read())
json_file.close()
self.local_content = data
return self
def _parseRemoteState(self):
try:
remoteContent = requests.get(self.urllink).content
remoteContent = (json.loads(remoteContent))
except:
pass
self.remote_content = remoteContent
return self
def _compareLocalAndRemote(self):
l_content_id = int(self.local_content['last_update_content']['id'])
r_content_id = int(self.remote_content['num'])
return not l_content_id < r_content_id
def downloadNewContent(self):
l_content = self.local_content
r_content = self.remote_content
# check local content id vs remote content id
self._log("processing", l_content['last_update_content']['id'])
l_content_id = int(l_content['last_update_content']['id'])
r_content_id = int(r_content['num'])
while l_content_id < r_content_id:
try:
json_content = json.loads(requests.get(
"https://xkcd.com/"+str(l_content_id)+"/info.0.json").content)
except:
self._log('can not contact remote for :', l_content_id)
self._log('skipping ', l_content_id)
l_content_id += 1
continue
if self._saveContent(json_content):
l_content_id += 1
l_content['last_update_content']['id'] = str(l_content_id)
self._log('downloaded content :', l_content_id)
self._saveState(self.local_content)
else:
self._log('error saving content... skipping')
break
if __name__ == "__main__":
sync = Sync()
sync.sync()