-
Notifications
You must be signed in to change notification settings - Fork 0
/
getUser.go
89 lines (84 loc) · 2.3 KB
/
getUser.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
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"time"
)
func getUser(mtid string) (PaperResponse, error) {
base, err := url.Parse("https://m2.mtmt.hu/api/publication")
if err != nil {
return PaperResponse{}, err
}
// Query params
params := url.Values{}
params.Add("cond", "published;eq;true")
params.Add("cond", "core;eq;true")
params.Add("cond", "authors.mtid;eq;"+mtid)
params.Add("cond", "category.mtid;eq;1")
params.Add("cond", "type.mtid;eq;24")
params.Add("cond", "languages.label;eq;Angol")
params.Add("sort", "publishedYear,desc")
params.Add("sort", "firstAuthor,asc")
params.Add("size", "10000")
params.Add("size", "10000")
params.Add("fields", "template")
params.Add("labelLang", "hun")
params.Add("cite_type", "2")
params.Add("page", "1")
params.Add("format", "json")
base.RawQuery = params.Encode()
resp, err := http.Get(base.String())
if err != nil {
return PaperResponse{}, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return PaperResponse{}, err
}
mtmtResponse := MtmtResponse{}
err = json.Unmarshal([]byte(body), &mtmtResponse)
papers := getPapers(mtmtResponse, mtid)
papers = getJournals(papers)
retval := PaperResponse{Papers: papers, Time: time.Now().Unix()}
return retval, nil
}
func handleGetUser(w http.ResponseWriter, r *http.Request) {
mtid := r.URL.Query().Get("mtid")
log.Printf("/user %s\n", mtid)
regres, _ := regexp.MatchString(`^\d+$`, mtid)
if mtid == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - no MTID given"))
} else if !regres {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - not an mtid"))
} else {
filename := "user_" + mtid + ".json"
info, fileerr := os.Stat(filename)
var jsonresp []byte
if fileerr != nil || time.Now().Unix()-info.ModTime().Unix() >= CACHETIME {
response, err := getUser(mtid)
if err != nil {
if fileerr == nil {
jsonresp, _ = os.ReadFile(filename)
w.Write(jsonresp)
} else {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - MTMT is probably not available and no fallback exists"))
}
} else {
jsonresp, _ = json.Marshal(response)
w.Write(jsonresp)
_ = os.WriteFile(filename, jsonresp, 0644)
}
} else {
jsonresp, _ = os.ReadFile(filename)
w.Write(jsonresp)
}
}
}