aboutsummaryrefslogtreecommitdiff
path: root/util.go
blob: 7da213c336c3ba488c1890699ad47516a4a9bb51 (plain)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package main

import (
	"bufio"
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/html"
)

var privateIPBlocks []*net.IPNet

// isPrivateIP checks to if the provided IP address is a loopback, link-local
// or unique-local address
//
// credit: https://stackoverflow.com/a/50825191
func isPrivateIP(ip net.IP) bool {

	if privateIPBlocks == nil {
		for _, cidr := range []string{
			"127.0.0.0/8",    // IPv4 loopback
			"10.0.0.0/8",     // RFC1918
			"172.16.0.0/12",  // RFC1918
			"192.168.0.0/16", // RFC1918
			"169.254.0.0/16", // RFC3927 link-local
			"::1/128",        // IPv6 loopback
			"fe80::/10",      // IPv6 link-local
			"fc00::/7",       // IPv6 unique local addr
		} {
			_, block, err := net.ParseCIDR(cidr)
			if err != nil {
				panic(fmt.Errorf("parse error on %q: %v", cidr, err))
			}
			privateIPBlocks = append(privateIPBlocks, block)
		}
	}
	if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
		return true
	}
	for _, block := range privateIPBlocks {
		if block.Contains(ip) {
			return true
		}
	}
	return false
}

// getDOIFromBytes returns the DOI parsed from the provided []byte slice
func getDOIFromBytes(b []byte) []byte {

	re := regexp.MustCompile(`(10[.][0-9]{4,}[^\s"/<>]*/[^\s"'<>,\{\};\[\]\?&]+)`)
	return re.Find(b)
}

// makeRequest makes a request to a remote resource using the provided
// *http.Client and returns its *http.Response
func makeRequest(client *http.Client, u string) (*http.Response, error) {

	req, err := http.NewRequest("GET", u, nil)

	// sciencedirect and company block atypical user agents
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%q: status code not OK", u)
	}
	return resp, nil
}

// getMetaFromCitation parses an *http.Response for <meta> tags to populate a
// paper's Meta attributes and returns the paper
func getMetaFromCitation(resp *http.Response) (*Meta, error) {

	doc, err := html.Parse(resp.Body)
	if err != nil {
		return nil, err
	}

	var meta Meta
	var f func(*html.Node)
	f = func(n *html.Node) {
		if n.Type == html.ElementNode && n.Data == "meta" {
			var name string
			var cont string
			for _, a := range n.Attr {
				if a.Key == "name" || a.Key == "property" {
					name = a.Val
				} else if a.Key == "content" {
					cont = a.Val
				}
			}
			switch name {
			case "citation_title":
				meta.Title = cont
			case "citation_author":
				var c Contributor
				// Doe, Jain
				if strings.Contains(cont, ",") {
					v := strings.Split(cont, ", ")
					c.FirstName = strings.Join(v[1:], " ")
					c.LastName = v[0]
					// Jain Doe
				} else {
					v := strings.Split(cont, " ")
					c.FirstName = strings.Join(v[:len(v)-1], " ")
					c.LastName = strings.Join(v[len(v)-1:], " ")
				}
				c.Role = "author"
				if len(meta.Contributors) > 0 {
					c.Sequence = "additional"
				} else {
					c.Sequence = "first"
				}
				meta.Contributors = append(meta.Contributors, c)
			case "citation_date", "citation_publication_date":
				var formats = []string{"2006-01-02", "2006/01/02", "2006"}
				for _, format := range formats {
					t, err := time.Parse(format, cont)
					if err == nil {
						meta.PubMonth = t.Month().String()
						meta.PubYear = strconv.Itoa(t.Year())
						break
					}
				}
			case "citation_journal_title", "og:site_name", "DC.Publisher":
				meta.Journal = cont
			case "citation_firstpage":
				meta.FirstPage = cont
			case "citation_lastpage":
				meta.LastPage = cont
			case "citation_doi":
				meta.DOI = cont
			case "citation_arxiv_id":
				meta.ArxivID = cont
			case "citation_pdf_url":
				meta.Resource = cont
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			f(c)
		}
	}
	f(doc)
	return &meta, nil
}

// renameFile is an alternative to os.Rename which supports moving files
// between devices where os.Rename would return an error (cross-device link)
func renameFile(src string, dst string) (err error) {

	if src == dst {
		return nil
	}
	err = copyFile(src, dst)
	if err != nil {
		return fmt.Errorf("failed to copy source file %s to %s: %s", src, dst, err)
	}
	err = os.RemoveAll(src)
	if err != nil {
		return fmt.Errorf("failed to cleanup source file %s: %s", src, err)
	}
	return nil
}

// copyFile copies a file located at src to dst, used by renameFile()
//
// credit: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04
func copyFile(src, dst string) (err error) {

	in, err := os.Open(src)
	if err != nil {
		return
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return
	}
	defer func() {
		if e := out.Close(); e != nil {
			err = e
		}
	}()

	_, err = io.Copy(out, in)
	if err != nil {
		return
	}

	err = out.Sync()
	if err != nil {
		return
	}
	return
}

// getMetaFromDOI saves doi.org API data to TempFile and returns its path
func getMetaFromDOI(client *http.Client, doi []byte) (*Meta, error) {

	u := "https://doi.org/" + string(doi)
	req, err := http.NewRequest("GET", u, nil)

	req.Header.Add("Accept", "application/vnd.crossref.unixref+xml;q=1,application/rdf+xml;q=0.5")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%q: failed to get metadata", u)
	}
	if resp.Header.Get("Content-Type") != "application/vnd.crossref.unixref+xml" {
		return nil, fmt.Errorf("%q: content-type not application/vnd.crossref.unixref+xml", u)
	}
	if err != nil {
		return nil, err
	}

	r := bufio.NewReader(resp.Body)
	d := xml.NewDecoder(r)

	// populate p struct with values derived from doi.org metadata
	var meta Meta
	if err := d.Decode(&meta); err != nil {
		return nil, err
	}
	return &meta, nil
}

// getPaper saves makes an outbound request to a remote resource and saves the
// response body to a temporary file, returning its path, provided the response
// has the content-type application/pdf
func getPaper(client *http.Client, scihub *url.URL, resource string) (string, error) {

	ref, err := url.Parse(resource)
	if err != nil {
		return "", err
	}
	refURL := scihub.ResolveReference(ref) // scihub + resource

	resp, err := makeRequest(client, refURL.String())
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	doc, err := html.Parse(resp.Body)
	if err != nil {
		return "", err
	}

	var directLink *url.URL
	var f func(*html.Node)
	f = func(n *html.Node) {
		if n.Type == html.ElementNode {
			for _, a := range n.Attr {
				if a.Key == "src" {
					_v, err := url.Parse(a.Val)
					if err != nil {
						continue
					}
					if strings.HasSuffix(_v.Path, "pdf") {
						directLink = scihub.ResolveReference(_v)
						break
					}
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			f(c)
		}
	}
	f(doc)

	if directLink == nil || directLink.String() == "" {
		return "", fmt.Errorf("%q: could not locate PDF link", refURL.String())
	}

	resp, err = makeRequest(client, directLink.String())
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.Header.Get("content-type") != "application/pdf" {
		return "", fmt.Errorf("%q: content-type not application/pdf", refURL.String())
	}

	tmpPDF, err := ioutil.TempFile("", "tmp-*.pdf")
	if err != nil {
		return "", err
	}
	if err := saveRespBody(resp, tmpPDF.Name()); err != nil {
		return "", err
	}
	if err := tmpPDF.Close(); err != nil {
		return "", err
	}
	return tmpPDF.Name(), nil
}

// saveRespBody writes the provided http.Response to path
func saveRespBody(resp *http.Response, path string) error {

	out, err := os.Create(path)
	if err != nil {
		return err
	}
	defer out.Close()

	r := http.MaxBytesReader(nil, resp.Body, MAX_SIZE)
	_, err = io.Copy(out, r)
	if err != nil {
		return err
	}
	return nil
}