forked from ErichMoraga/tis-rip
-
Notifications
You must be signed in to change notification settings - Fork 4
/
rip.py
executable file
·303 lines (248 loc) · 9.59 KB
/
rip.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
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
#!/usr/bin/env python3
from selenium import webdriver
import time
import os.path
import xml.etree.ElementTree as ET
import shutil
import subprocess
from bs4 import BeautifulSoup
import os
import sys
# The chrome application path is pretty platform/install specific..
CHROME_PATH = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
def mkfilename(s):
fn = ""
for x in s:
if x.isalnum() or x == " ":
fn += x
else:
fn += "_"
return fn
def fix_links(fn):
modified = False
doc = open(fn, 'r').read()
soup = BeautifulSoup(doc, 'lxml')
for link in soup.find_all("a"):
href = link.get('href')
if href is None:
continue
if '?' in href:
href = href.split('?')[0]
if not href.startswith('/t3Portal/document'):
continue
new_path = os.path.basename(href)
if href != new_path:
link['href'] = new_path
modified = True
if modified:
print("Writing ", fn)
with open(fn, 'w') as fh:
fh.write(soup.prettify())
def download_ewd(driver, ewd):
SYSTEMS = ["system", "routing", "overall"]
for s in SYSTEMS:
fn = os.path.join(ewd, s, "index.xml")
d = os.path.join(ewd, s)
if not os.path.exists(d):
os.makedirs(d)
if os.path.exists(fn):
continue
url = "https://techinfo.toyota.com/t3Portal/external/en/ewdappu/" + ewd + "/ewd/contents/" + s + "/title.xml"
print("Loading", url)
driver.get(url)
print("Saving...")
xml_src = driver.execute_script('return document.getElementById("webkit-xml-viewer-source-xml").innerHTML')
with open(fn, 'w') as fh:
fh.write(xml_src)
for s in SYSTEMS:
idx = os.path.join(ewd, s, "index.xml")
print(idx)
tree = ET.parse(idx)
root = tree.getroot()
for child in root:
name = child.findall('name')[0].text
fig = child.findall('fig')[0].text
fn = os.path.join(ewd, s, mkfilename(fig + " " + name) + ".pdf")
if os.path.exists(fn):
continue
print("Downloading ", name, "...")
url = "https://techinfo.toyota.com/t3Portal/external/en/ewdappu/" + ewd + "/ewd/contents/" + s + "/pdf/" + fig + ".pdf"
driver.get(url)
# this will have downloaded the file, or not
temp_dl_path = os.path.join("download", fig + ".pdf.crdownload")
while os.path.exists(temp_dl_path):
time.sleep(5.0)
dl_path = os.path.join("download", fig + ".pdf")
if not os.path.exists(dl_path):
time.sleep(1)
if not os.path.exists(dl_path):
print("Didn't download ", url, "!")
continue
shutil.move(dl_path, fn)
print("Done ", name)
def toc_parse_items(base, items):
if len(items) == 0:
return ""
wrap = "<ul>"
for i in items:
wrap += "<li>"
name = i.findall("name")[0].text
wrap += name
if "href" in i.attrib and i.attrib["href"] != "":
# it has a link, parse it
bn = os.path.splitext(os.path.basename(i.attrib["href"]))[0]
html_path = os.path.join(base, "html", bn + ".html")
pdf_path = os.path.join(base, "pdf", bn + ".pdf")
if os.path.exists(html_path):
wrap += " [<a href=\"html/" + bn + ".html\">HTML</a>] "
if os.path.exists(pdf_path):
wrap += " [<a href=\"pdf/" + bn + ".pdf\">PDF</a>] "
wrap += toc_parse_items(base, i.findall("item"))
wrap += "</li>"
wrap += "</ul>"
return wrap
def build_toc_index(base):
if not os.path.exists(base):
return False
toc_path = os.path.join(base, "toc.xml")
if not os.path.exists(toc_path):
print("toc.xml missing in ", base)
return False
print("Building TOC index from ", toc_path, "...")
tree = ET.parse(toc_path)
root = tree.getroot()
body = toc_parse_items(base, root.findall("item"))
index_out = os.path.join(base, "index.html")
with open(index_out, "w") as fh:
fh.write("<!doctype html>\n")
fh.write("<html><head><title>" + base + "</title></head><body>")
fh.write(body)
fh.write("</body></html>")
def download_manual(driver, t, id):
if not os.path.exists(os.path.join(id, "html")):
os.makedirs(os.path.join(id, "html"))
if not os.path.exists(os.path.join(id, "pdf")):
os.makedirs(os.path.join(id, "pdf"))
toc_path = os.path.join(id, "toc.xml")
if not os.path.exists(toc_path):
print("Downloading the TOC for", id)
url = "https://techinfo.toyota.com/t3Portal/external/en/" + t + "/" + id + "/toc.xml"
driver.get(url)
xml_src = driver.execute_script('return document.getElementById("webkit-xml-viewer-source-xml").innerHTML')
with open(toc_path, 'w') as fh:
fh.write(xml_src)
tree = ET.parse(toc_path)
root = tree.getroot()
n = 0
c = 0
for i in root.iter("item"):
if not 'href' in i.attrib or i.attrib['href'] == '':
continue
c += 1
for i in root.iter("item"):
if not 'href' in i.attrib or i.attrib['href'] == '':
continue
href = i.attrib['href']
url = "https://techinfo.toyota.com" + href
n += 1
print("Downloading", href, " (", n, "/", c, ")...")
# all are html files, load them all up one at a time and then save them
f_parts = href.split('/')
f_p = os.path.join(id, "html", f_parts[len(f_parts)-1])
pdf_p = os.path.join(id, "pdf", f_parts[len(f_parts)-1][:-5] + ".pdf")
#print("do we make a pdf?")
print(f_p+" "+pdf_p)
if os.path.exists(f_p) and not os.path.exists(pdf_p):
# make the pdf
#print("we have a file but no pdf, let's go!")
make_pdf(f_p, pdf_p)
if os.path.exists(f_p) or os.path.exists(pdf_p):
continue
driver.get(url)
if "location='/t3Portal" in driver.page_source:
print("\tPDF redirect found!")
while True:
time.sleep(5.0)
incomplete = False
for f in os.listdir("download"):
if f.endswith(".crdownload"):
incomplete = True
break
if not incomplete:
break
else:
print("Waiting for incomplete download!")
time.sleep(5.0)
# list out all downloads in folder and try to match them!
dest_file = None
while len(os.listdir("download")) < 1:
time.sleep(5.0)
for f in os.listdir("download"):
print(f)
if f in driver.page_source:
dest_file = f
break
if dest_file is None:
print("\tCould not find matching download!")
input("wait")
continue
shutil.move(os.path.join("download", dest_file), pdf_p)
print("\tDone")
else:
print("\tInjecting scripts...")
# we want to inject jQuery now
driver.execute_script("""var s=window.document.createElement('script');\
s.src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js';\
window.document.head.appendChild(s);""")
# remove the toyota footer
src = None
try :
src = driver.execute_script(open("injected.js", "r").read())
except:
time.sleep(1)
src = driver.execute_script(open("injected.js", "r").read())
with open(f_p, 'w') as fh:
fh.write(src)
fix_links(f_p)
print("\tDone")
build_toc_index(id)
def make_pdf(src, dest):
print("Creating PDF from", src, "to", dest)
subprocess.run([CHROME_PATH, "--print-to-pdf=" + os.path.abspath(dest), "--no-gpu", "--headless", "file://" + os.path.abspath(src)])
if __name__ == "__main__":
if len(sys.argv) < 2:
print("You must pass the documents you wish to download as arguments to this script!")
sys.exit(1)
EWDS = []
REPAIR_MANUALS = []
COLLISION_MANUALS = []
for arg in sys.argv[1:]:
if arg.startswith('EM'):
EWDS.append(arg)
elif arg.startswith('RM'):
REPAIR_MANUALS.append(arg)
elif arg.startswith('BM'):
COLLISION_MANUALS.append(arg)
else:
print("Unknown document type for '" + arg + "'!")
sys.exit(1)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("user-data-dir=./user-data")
shutil.rmtree("download", True)
os.makedirs("download")
driver = webdriver.Chrome("./chromedriver", options=chrome_options)
driver.get("https://techinfo.toyota.com")
input("Please login and press enter to continue...")
# for each in ewd download
print("Downloading electrical wiring diagrams...")
for ewd in EWDS:
download_ewd(driver, ewd)
# download all collision manuals
print("Downloading collision repair manuals...")
for cr in COLLISION_MANUALS:
download_manual(driver, "cr", cr)
# download all repair manuals
print("Downloading repair manuals...")
for rm in REPAIR_MANUALS:
download_manual(driver, "rm", rm)
driver.close()