fetch.go (5739B)
1 package bib 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "net/url" 9 "os" 10 "os/exec" 11 "regexp" 12 "slices" 13 "strings" 14 "time" 15 "unicode" 16 ) 17 18 // Client resolves DOIs via Crossref and fetches BibTeX via doi.org content 19 // negotiation, the same services scholarref's getdoi and getref use. 20 type Client struct { 21 HTTP *http.Client 22 CrossrefURL string 23 DOIURL string 24 } 25 26 func NewClient() *Client { 27 return &Client{ 28 HTTP: &http.Client{Timeout: 30 * time.Second}, 29 CrossrefURL: "https://api.crossref.org/works", 30 DOIURL: "https://doi.org", 31 } 32 } 33 34 func (c *Client) get(u, accept string) ([]byte, error) { 35 req, err := http.NewRequest("GET", u, nil) 36 if err != nil { 37 return nil, err 38 } 39 req.Header.Set("Accept", accept) 40 req.Header.Set("User-Agent", "manus-tracker/0.1") 41 resp, err := c.HTTP.Do(req) 42 if err != nil { 43 return nil, err 44 } 45 defer resp.Body.Close() 46 b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) 47 if err != nil { 48 return nil, err 49 } 50 if resp.StatusCode != http.StatusOK { 51 return nil, fmt.Errorf("%s: %s", u, resp.Status) 52 } 53 return b, nil 54 } 55 56 var doiInText = regexp.MustCompile(`(?i)\b(10\.\d{4,9}/[^\s"<>,;]+)`) 57 58 // Lookup returns a DOI for a DOI string, a PDF file, or a free-text query. 59 func (c *Client) Lookup(q string) (string, error) { 60 q = strings.TrimSpace(q) 61 if IsDOI(q) { 62 return NormDOI(q), nil 63 } 64 if fi, err := os.Stat(q); err == nil && !fi.IsDir() { 65 return doiFromPDF(q) 66 } 67 if q == "" { 68 return "", fmt.Errorf("empty query") 69 } 70 b, err := c.get(c.CrossrefURL+"?rows=1&select=DOI&query="+url.QueryEscape(q), "application/json") 71 if err != nil { 72 return "", err 73 } 74 var r struct { 75 Message struct { 76 Items []struct{ DOI string } 77 } 78 } 79 if err := json.Unmarshal(b, &r); err != nil { 80 return "", fmt.Errorf("crossref: %v", err) 81 } 82 if len(r.Message.Items) == 0 { 83 return "", fmt.Errorf("no DOI found for %q", q) 84 } 85 return NormDOI(r.Message.Items[0].DOI), nil 86 } 87 88 func doiFromPDF(path string) (string, error) { 89 for _, args := range [][]string{{"pdfinfo", path}, {"pdftotext", "-l", "3", path, "-"}} { 90 out, err := exec.Command(args[0], args[1:]...).Output() 91 if err != nil { 92 continue 93 } 94 if m := doiInText.FindString(string(out)); m != "" { 95 return NormDOI(strings.TrimRight(m, ".)")), nil 96 } 97 } 98 return "", fmt.Errorf("no DOI found in %s", path) 99 } 100 101 // Fetch retrieves and normalises the BibTeX entry for doi. 102 func (c *Client) Fetch(doi string) (*Entry, error) { 103 b, err := c.get(c.DOIURL+"/"+NormDOI(doi), "application/x-bibtex") 104 if err != nil { 105 return nil, err 106 } 107 es, err := Parse(string(b)) 108 if err != nil || len(es) == 0 { 109 return nil, fmt.Errorf("no BibTeX returned for %s", doi) 110 } 111 e := es[0] 112 Normalize(e) 113 e.Raw = Format(e) 114 return e, nil 115 } 116 117 var keyYear = regexp.MustCompile(`_(\d)`) 118 119 // Normalize applies getref's conventions: Name_2010 keys become Name2010, 120 // journal names and author first names are abbreviated, url and month drop. 121 func Normalize(e *Entry) { 122 e.Key = keyYear.ReplaceAllString(e.Key, "$1") 123 e.Order = slices.DeleteFunc(e.Order, func(k string) bool { return k == "url" || k == "month" }) 124 delete(e.Fields, "url") 125 delete(e.Fields, "month") 126 if j, ok := e.Fields["journal"]; ok { 127 e.Fields["journal"] = AbbrevJournal(j) 128 } 129 if a, ok := e.Fields["author"]; ok { 130 e.Fields["author"] = AbbrevAuthors(a) 131 } 132 if d, ok := e.Fields["doi"]; ok { 133 e.Fields["doi"] = NormDOI(d) 134 } 135 } 136 137 var journalAbbrev = []string{ 138 "Journal", "J.", "Geophysical", "Geophys.", "Research", "Res.", "Geophysics", "Geophys.", 139 "Letters", "Lett.", "Mechanics", "Mech.", "Glaciology", "Glaciol.", "Proceedings", "Proc.", 140 "Royal", "R.", "Society", "Soc.", "Annals", "Ann.", "Resources", "Resour.", "Surface", "Surf.", 141 "Processes", "Proc.", "National", "Nat.", "Computers", "Comput.", "Geotechnics", "Geotech.", 142 "Academy", "Acad.", "Sciences", "Sci.", "Review", "Rev.", "Quaternary", "Quat.", 143 "Physical", "Phys.", "Planetary", "Planet.", "Quarterly", "Q.", "Geological", "Geol.", 144 "Statistical", "Stat.", "Applied", "Appl.", "Physics", "Phys.", "Communications", "Commun.", 145 "Geoscience", "Geosci.", "Landforms", "Land.", "Science", "Sci.", "Annual", "Ann.", 146 "International", "Int.", "Numerical", "Numer.", "Methods", "Meth.", "Geomechanics", "Geomech.", 147 "Analytical", "Anal.", "Advances", "Adv.", "Modeling", "Mod.", "Systems", "Sys.", 148 " for ", " ", " of ", " ", " and ", " ", " in ", " ", 149 } 150 151 // AbbrevJournal abbreviates a journal title with getref's word list. A 152 // single-word title (e.g. "Science", "Geomorphology") is left unchanged. 153 func AbbrevJournal(j string) string { 154 if !strings.Contains(strings.TrimSpace(j), " ") { 155 return j 156 } 157 for i := 0; i < len(journalAbbrev); i += 2 { 158 j = strings.ReplaceAll(j, journalAbbrev[i], journalAbbrev[i+1]) 159 } 160 return j 161 } 162 163 // AbbrevAuthors shortens given names to initials: "Geoffrey S. Boulton" 164 // becomes "G. S. Boulton"; "Boulton, Geoffrey S." becomes "Boulton, G. S.". 165 func AbbrevAuthors(a string) string { 166 names := strings.Split(a, " and ") 167 for i, n := range names { 168 n = strings.TrimSpace(n) 169 if last, first, ok := strings.Cut(n, ","); ok { 170 names[i] = strings.TrimSpace(last) + ", " + initials(strings.Fields(first)) 171 continue 172 } 173 w := strings.Fields(n) 174 if len(w) < 2 { 175 names[i] = n 176 continue 177 } 178 names[i] = initials(w[:len(w)-1]) + " " + w[len(w)-1] 179 } 180 return strings.Join(names, " and ") 181 } 182 183 func initials(words []string) string { 184 out := make([]string, 0, len(words)) 185 for _, w := range words { 186 parts := strings.Split(w, "-") 187 for i, p := range parts { 188 r := []rune(p) 189 if len(r) > 0 && unicode.IsUpper(r[0]) && !strings.HasSuffix(p, ".") { 190 parts[i] = string(r[0]) + "." 191 } 192 } 193 out = append(out, strings.Join(parts, "-")) 194 } 195 return strings.Join(out, " ") 196 }