This repository has been archived by the owner on Apr 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
162 lines (129 loc) · 3.18 KB
/
server.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
package arias
import (
"bytes"
"encoding/json"
"fmt"
"github.com/MyAnimeStream/arias/aria2"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/google/uuid"
"github.com/gorilla/schema"
"log"
"net/http"
"time"
)
const Version = "0.1.1"
var schemaDecoder = schema.NewDecoder()
type Server struct {
Router chi.Router
HttpClient *http.Client
Config Config
AriaClient aria2.Client
Storage Storage
tasks map[uuid.UUID]Task
}
func NewServer(config Config) (s Server, err error) {
ariaClient, err := aria2.Dial(config.Aria2Addr)
if err != nil {
return
}
storage, err := NewStorageFromType(config.StorageType)
if err != nil {
return
}
r := chi.NewRouter()
//r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
s = Server{
Router: r,
HttpClient: &http.Client{Timeout: 30 * time.Second},
Config: config,
AriaClient: ariaClient,
Storage: storage,
tasks: make(map[uuid.UUID]Task),
}
s.addHandlers()
return
}
func (s *Server) ListenAndServe() error {
addr := s.Config.ServerAddr
log.Printf("Starting to serve on %s\n", addr)
return http.ListenAndServe(addr, s.Router)
}
func (s *Server) PerformTask(task Task) {
id := task.GetId()
s.tasks[id] = task
go func() {
_ = task.Perform()
}()
}
func (s *Server) SendCallback(url string, data interface{}) (resp *http.Response, err error) {
p, err := json.Marshal(data)
if err != nil {
return
}
w := bytes.NewBuffer(p)
req, err := http.NewRequest("POST", url, w)
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", fmt.Sprintf("arias/%s", Version))
resp, err = s.HttpClient.Do(req)
return
}
func (s *Server) GoSendCallback(url string, data interface{}) {
go func() {
_, err := s.SendCallback(url, data)
if err != nil {
log.Printf("couldn't perform callback to %s: %s\n", url, err)
}
}()
}
func (s *Server) addHandlers() {
r := s.Router
r.Get("/download", s.download)
r.Get("/status", s.status)
}
func jsonResponse(w http.ResponseWriter, data interface{}, status int) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(data)
}
func (s *Server) download(w http.ResponseWriter, r *http.Request) {
var downloadRequest DownloadRequest
err := schemaDecoder.Decode(&downloadRequest, r.URL.Query())
if err != nil {
http.Error(w, err.Error(), 400)
return
}
if err := downloadRequest.UseConfig(&s.Config); err != nil {
http.Error(w, err.Error(), 400)
return
}
if err := downloadRequest.Check(); err != nil {
http.Error(w, err.Error(), 400)
return
}
task := NewDownloadTask(s, downloadRequest)
s.PerformTask(task)
resp := DownloadResponse{task.GetId().String()}
_ = jsonResponse(w, resp, http.StatusOK)
}
func (s *Server) status(w http.ResponseWriter, r *http.Request) {
rawID := r.URL.Query().Get("id")
id, err := uuid.Parse(rawID)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
task, ok := s.tasks[id]
if !ok {
http.Error(w, "task not found", 404)
return
}
_ = jsonResponse(w, task.GetStatus(), http.StatusOK)
}