/
screenshot.go
292 lines (258 loc) · 8.5 KB
/
screenshot.go
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
/*
Copyright © 2022, 2023 M.Watermann, 10247 Berlin, Germany
All rights reserved
EMail : <support@mwat.de>
*/
package nele
//lint:file-ignore ST1017 - I prefer Yoda conditions
import (
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"github.com/mwat56/apachelogger"
"github.com/mwat56/screenshot"
)
type (
// `tImgURL` represents a pair of image name and page URL.
tImgURL struct {
imgURL string
pageURL string
}
tImgURLlist []tImgURL
// `tLink` represents a group of link, link text and link URL.
tLink struct {
link string // the whole markdown link
linkText string
linkURL string
}
)
// `checkScreenshots()` checks whether the image file referenced
// in the text of `aPosting` actually exists locally.
//
// `aPosting` The posting the text of which is searched for
//
// a local image link.
func checkScreenshots(aPosting *TPosting) {
if nil == aPosting {
return
}
var pair tImgURL // re-use variable
list := checkScreenshotURLs(aPosting.Markdown())
for _, pair = range list {
goCreateScreenshot(pair.pageURL)
}
} // checkScreenshots()
var (
// R/O RegEx to find an URL for the screenshot image's.
ssImageRE = regexp.MustCompile(
`(?s)\[\s*\!\[[^\]]*?\]\s*\(\s*([^\)]+?)\s*\)\s*\]\s*\(\s*([^\)]+?)\s*\)`)
// 111111111 222222222
// `[![alt-text](image-URL)](link-url)`
// 1 : local image URL
// 2 : remote page URL
)
// `checkScreenshotURLs()` tests whether `aTxt` contains an external
// link with an embedded page screenshot image,
// returning a list of the two link URLs.
//
// `aTxt` is the text to search.
func checkScreenshotURLs(aTxt []byte) (rList tImgURLlist) {
matches := ssImageRE.FindAllSubmatch(aTxt, -1)
for idx, l := 0, len(matches); idx < l; idx++ {
rList = append(rList, tImgURL{
filepath.Base(string(matches[idx][1])),
string(matches[idx][2]),
})
}
return
} // checkScreenshotURLs()
// `goCreateScreenshot()` generates a screenshot of `aURL` in background.
//
// `aURL` The URL for which to create a screenshot image.
func goCreateScreenshot(aURL string) {
// `screenshot.CreateImage()` checks whether the file exists
// and whether it's too old.
imgName, err := screenshot.CreateImage(aURL)
if (nil != err) || (0 == len(imgName)) {
apachelogger.Err("goCreateScreenshot()",
fmt.Sprintf("screenshot.CreateImage(%s): '%v'", aURL, err))
}
} // goCreateScreenshot()
// `goSetLinkScreenshots()` changes the external links in the text
// of `aPosting` to include a page screenshot image (if available).
//
// `aPosting` The posting the text of which is going to be processed.
func goSetLinkScreenshots(aPosting *TPosting) {
if (nil == aPosting) || (0 == aPosting.Len()) {
return
}
url := `` // re-use in loop below
linkMatches := ssLinkRE.FindAllSubmatch(aPosting.Markdown(), -1)
if (nil != linkMatches) && (0 < len(linkMatches)) {
imgDir := screenshot.ImageDir()
for l, cnt := len(linkMatches), 0; cnt < l; cnt++ {
url = string(linkMatches[cnt][3])
if !ssSchemeRE.MatchString(url) {
continue // skip local links
}
preparePost(aPosting,
&tLink{
link: string(linkMatches[cnt][1]),
linkText: string(linkMatches[cnt][2]),
linkURL: url,
},
imgDir)
}
}
// In case we didn't find any normal links we check
// the links with an embedded page screenshot image:
checkScreenshots(aPosting)
} // goSetLinkScreenshots()
// `goUpdateAllLinkScreenshots()` prepares the external links in
// all postings to use a page screenshot image (if available).
//
// `aPostingBaseDir` is the base directory used for storing
//
// articles/postings.
func goUpdateAllLinkScreenshots(aPostingBaseDir string) {
var ( // re-use variables in loops below
err error
dName, fName, pName string
dNames, fNames []string
p *TPosting
)
if dNames, err = filepath.Glob(aPostingBaseDir + "/*"); nil != err {
return // we can't recover from this :-(
}
for _, dName = range dNames {
if fNames, err = filepath.Glob(dName + "/*.md"); (nil != err) || (0 == len(fNames)) {
continue // no files found
}
for _, pName = range fNames {
fName = filepath.Base(pName)
p = NewPosting(fName[:len(fName)-3]) // strip name extension
if err = p.Load(); nil == err {
goSetLinkScreenshots(p)
} // ELSE ignore the error here …
}
}
} // goUpdateAllLinkScreenshots()
// `preparePost()` creates a screenshot image and updates `aLink`
// in the text of `aPosting` to embed a link into the image.
//
// `aPosting` The posting the text of which is going to be updated.
// `aLink` The link parts to use.
// `aImageURLdir` The URL directory for page screenshot images.
func preparePost(aPosting *TPosting, aLink *tLink, aImageURLdir string) {
imgName, err := screenshot.CreateImage(aLink.linkURL)
if (nil != err) || (0 == len(imgName)) {
apachelogger.Err("preparePost()",
fmt.Sprintf("screenshot.CreateImage(%s): '%v'", aLink.linkURL, err))
return
}
if 0 == len(aImageURLdir) {
return
}
if '/' != aImageURLdir[0] {
aImageURLdir = `/` + aImageURLdir
}
if txt := prepPostText(aPosting.Markdown(), aLink, imgName, aImageURLdir); 0 < len(txt) {
_, _ = aPosting.Set(txt).Store()
}
} // preparePost()
// `prepPostText()` gets called by `preparePost()` to replace
// `[link-text](link-url)` by `[![alt-text](image-URL)](link-URL)`
//
// `aPosting` The posting the text of which is going to be updated.
// `aLink` The link parts to use.
// `aImageURLdir` The URL directory for page screenshot images.
func prepPostText(aPosting []byte, aLink *tLink, aImageName, aImageURLdir string) (rText []byte) {
search := regexp.QuoteMeta(aLink.link)
if re, err := regexp.Compile(search); nil == err {
replace := "[![" + aLink.linkText +
"](" + filepath.Join(aImageURLdir, aImageName) +
")](" + aLink.linkURL + ")"
rText = re.ReplaceAllLiteral(aPosting, []byte(replace))
}
return
} // prepPostText()
// // `validateScreenshot()` implements two purposes:
// // (a) it checks whether a certain article contains screenshots;
// // (b) it checks whether the screenshot image is formally correct
// // (e.g. `png` vs. `jpeg`).
// func validateScreenshot(aImgDir string) {
// /*
// + walk through all posting dirs
// + + check each posting for links
// + +
// */
// } // validateScreenshot()
var (
// R/O RegEx to extract link-text and link-URL from markup.
// Checking for the not-existence of the leading `!` should exclude
// embedded image links.
ssLinkRE = regexp.MustCompile(
`(?m)(?:^\s*\>[\t ]*)((?:[^\!\n\>][\t ]*)?\[([^\[]+?)\]\s*\(([^\]]+?)\))`)
// 11222222222111111133333333311
// `[link-text](link-url)`
// 0 : complete RegEx match
// 1 : markdown link markup
// 2 : link text
// 3 : remote page URL
// R/O simple RegEx to check whether an URL starts with a scheme.
ssSchemeRE = regexp.MustCompile(`^\w+://`)
)
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// CreateScreenshot generates a screenshot of `aURL` in background.
//
// `aURL` The URL for which to create a screenshot image.
func CreateScreenshot(aURL string) {
go goCreateScreenshot(aURL)
runtime.Gosched() // get the background operation started
} // CreateScreenshot
// PrepareLinkScreenshots updates the external link(s) in `aPosting`
// to include page screenshot image(s) (if available).
//
// `aPosting` The posting the text of which is going to be processed.
func PrepareLinkScreenshots(aPosting *TPosting) {
go goSetLinkScreenshots(aPosting)
runtime.Gosched() // get the background operation started
} // PrepareLinkScreenshots()
// RemovePageScreenshots deletes the images used in `aPosting`.
//
// `aPosting` The posting the image(s) of which are going to be deleted.
func RemovePageScreenshots(aPosting *TPosting) {
if (nil == aPosting) || (0 == aPosting.Len()) {
return
}
var ( // re-use variables
err error
fi os.FileInfo
fName string
list tImgURLlist
pair tImgURL
)
if list = checkScreenshotURLs(aPosting.Markdown()); 0 == len(list) {
return
}
for _, pair = range list {
fName = screenshot.PathFile(pair.pageURL)
if fi, err = os.Stat(fName); (nil != err) || fi.IsDir() {
continue
}
_ = os.Remove(fName)
}
} // RemovePageScreenshots()
// UpdateScreenshots starts the process to update the screenshot images
// in all postings.
//
// `aPostingBaseDir` The base directory used for storing
//
// articles/postings.
func UpdateScreenshots(aPostingBaseDir string) {
go goUpdateAllLinkScreenshots(aPostingBaseDir)
runtime.Gosched() // get the background operation started
} // UpdateScreenshots()
/* _EoF_ */