-
Notifications
You must be signed in to change notification settings - Fork 0
/
saveLinkedImagesRecursively.groovy
277 lines (241 loc) · 9.87 KB
/
saveLinkedImagesRecursively.groovy
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
import java.nio.file.*
import java.text.SimpleDateFormat
import org.freeplane.features.map.mindmapmode.clipboard.MMapClipboardController
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
//TODO: Add ability to save SVG as PNG, and also the original SVG file?
//TODO: Add ability to process Base64 image
//Get selected nodes:
selectedNodes = c.selecteds
//Get list of node containing image links
c.statusInfo = "Processing"
listNodeWithImg = []
listNodeWithNotesWithImg = []
listNodeWithDetailsWithImg = []
selectedNodes.each{ eachNode ->
listNodeWithImg += eachNode.find{htmlUtils.isHtmlNode(it.text) && it.text.contains("<img")}
listNodeWithNotesWithImg += eachNode.find{(it.noteText != null) && it.noteText.contains("<img")}
listNodeWithDetailsWithImg += eachNode.find{(it.detailsText != null) && it.detailsText.contains("<img")}
}
//Get list of node with notes containing image links
//Check if img links in listNodeWithImg is downloadable
/**
* Http HEAD Method to get URL content type
*
* @param urlString
* @return content type
* @throws IOException
*/
public String getContentType(String urlString) throws IOException{
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36")
if (isRedirect(connection.getResponseCode())) {
String newUrl = connection.getHeaderField("Location"); // get redirect url from "location" header field
logger.warn("Original request URL: '{}' redirected to: '{}'", urlString, newUrl);
return getContentType(newUrl);
}
String contentType = connection.getContentType();
return contentType;
}
/**
* Check status code for redirects
*
* @param statusCode
* @return true if matched redirect group
*/
protected Boolean isRedirect(int statusCode) {
if (statusCode != HttpURLConnection.HTTP_OK) {
if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM
|| statusCode == HttpURLConnection.HTTP_SEE_OTHER) {
return true;
}
}
return false;
}
//A function to check if an image link is downloadable
def isDownloadable (String link) {
//list the content type to receive from header
def imgType = ['image/png','image/jpg','image/jpeg','image/png','image/tiff','image/bmp', 'image/tiff-fx', 'image/gif']
//additional list of extension to force download when the response return text/html contentype, but the link contains the extension
imgExt = ['.png', '.jpg','.jpeg','.tiff', '.bmp', '.gif']
containExt = ""
imgExt.each{ ext ->
if(link.contains(ext)){
containExt = ext - "."
}
}
try {
def contentType = getContentType(link)
if (imgType.contains(contentType)){
return (contentType - 'image/')
} else if (containExt != "") {
return containExt
}
else {
return "nope"
}
} catch (Exception e) {
c.statusInfo = e
return "nope"
}
}
//A function to check if the image link redirects to another link, and download the file following the redirected link
def redirectFollowingDownload( String url, String filename ) {
while( url ) {
new URL( url ).openConnection().with { conn ->
conn.instanceFollowRedirects = false
//Set the User-Agent is required to prevent Status 403 on some sites
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36")
url = conn.getHeaderField( "Location" )
if( !url ) {
new File( filename ).withOutputStream { out ->
conn.inputStream.with { inp ->
out << inp
inp.close()
}
}
}
}
}
}
def downloadFile (String link, String fileSave) {
def fileExt = isDownloadable(link)
if (fileExt != "nope"){
redirectFollowingDownload(link, fileSave)
}
}
//Check if the image link contain file URI, then remove it to get the right path to image
def convertFileUri (String fileUri) {
def file2Copy = ""
if (fileUri.contains("file:////")){
file2Copy = fileUri - "file:///"
return file2Copy
} else {
file2Copy = fileUri - "file://"
return file2Copy
}
}
def getDateTimeNow () {
def date = new Date()
sdf = new SimpleDateFormat("yyyyMMdd-HHmmss")
def dateNow = sdf.format(date).toString()
return dateNow
}
//TODO: Show popup listing images failed to fetch
/* Parse the text of nodes containing imgs to extract src */
def checkNote(nodeTest, int cases) {
switch(cases){
case 0:
return nodeTest.text
break
case 1:
return nodeTest.noteText
break
case 2:
return nodeTest.detailsText
break
}
}
def downloadImages (nodes, int cases) {
if (nodes.isEmpty()) {
c.statusInfo = "Nothing to download"
} else {
//Get mm file path
def fileTitle = map.getName().toString();
def fileName = map.getFile().toString();
def imgRelPath = Paths.get(fileTitle + "_files",'img').toString()
def fileAbsPath = Paths.get(Paths.get(fileName).getParent().toString(),imgRelPath);
//Create mm_files/img folder
if (Files.notExists(fileAbsPath)){
Files.createDirectories(fileAbsPath)
}
nodes.each{eachNode ->
Document parseString = Jsoup.parse(checkNote(eachNode, cases));
Elements imgTags = parseString.getElementsByTag('img');
def index = 0;
println imgTags
imgTags.each {item ->
def imgSrc = item.attr("src")
//Copy image from tmp to mm folder if it is on local machine
if (imgSrc.contains("file:////") || imgSrc.contains("file:///")) {
def file2Copy = convertFileUri(imgSrc)
def srcPath = Paths.get(file2Copy)
baseName = ""
switch(cases){
case 0:
baseName = "${eachNode.id}_${index}_${getDateTimeNow()}" + srcPath.getFileName()
break
case 1:
baseName = "Note_${eachNode.id}_${index}_${getDateTimeNow()}" + srcPath.getFileName()
break
case 2:
baseName = "Details_${eachNode.id}_${index}_${getDateTimeNow()}" + srcPath.getFileName()
break
}
def desPath = Paths.get(fileAbsPath.toString(), baseName)
if (Files.exists(srcPath)){
Files.copy(srcPath, desPath)
switch(cases){
case 0:
eachNode.text = eachNode.text.replace(imgSrc, Paths.get(imgRelPath, baseName).toString())
eachNode.link.text = Paths.get(imgRelPath, baseName).toString()
break
case 1:
eachNode.noteText = eachNode.noteText.replace(imgSrc, Paths.get(imgRelPath, baseName).toString())
break
case 2:
eachNode.detailsText = eachNode.detailsText.replace(imgSrc, Paths.get(imgRelPath, baseName).toString())
break
}
index += 1
}
}
//Download image if it is on the internet
def fileExt = isDownloadable(imgSrc)
if (fileExt != "nope") {
def dateNow = getDateTimeNow()
String fileSaveName = ""
switch(cases){
case 0:
fileSaveName = "${eachNode.id}_${index}_${dateNow}.${fileExt}"
break
case 1:
fileSaveName = "Note_${eachNode.id}_${index}_${dateNow}.${fileExt}"
break
case 2:
fileSaveName = "Details_${eachNode.id}_${index}_${dateNow}.${fileExt}"
break
}
def replaceNodePath = Paths.get(imgRelPath, fileSaveName).toString()
def fileDownloadPath = Paths.get(fileAbsPath.toString(), fileSaveName).toString()
//Download file
downloadFile(imgSrc, fileDownloadPath)
//Set the node src
switch(cases){
case 0:
eachNode.text = eachNode.text.replace(imgSrc, replaceNodePath)
break
case 1:
eachNode.noteText = eachNode.noteText.replace(imgSrc, replaceNodePath)
break
case 2:
eachNode.detailsText = eachNode.detailsText.replace(imgSrc, replaceNodePath)
break
}
index += 1
}
}
}
}
}
downloadImages(listNodeWithImg, 0)
downloadImages(listNodeWithNotesWithImg, 1)
downloadImages(listNodeWithDetailsWithImg, 2)
c.statusInfo = "DONE!"