forked from sibbr/tableconverter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tableconverter.go
224 lines (187 loc) · 5.06 KB
/
tableconverter.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
package main
import (
"crypto/rand"
"encoding/csv"
"encoding/hex"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// Labels placeholder for labels
type Labels struct {
Value string
ID int
}
var templates = template.Must(template.ParseFiles("labels.html"))
var cookieDuration = 60 * 60 // cookie active time in seconds
// Publicador hold information about the publisher converting tables at moment
type Publicador struct {
fp multipart.File
form *multipart.Form
sep string
cookie http.Cookie
created time.Time
}
// Publicadores list of publishers
var Publicadores = map[string]Publicador{}
var mutex = &sync.RWMutex{}
func upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
publicador := Publicador{}
var err error
publicador.fp, _, err = r.FormFile("uploadFile")
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
publicador.sep = r.FormValue("separator")
labels := getLabels(publicador.fp, r.FormValue("separator"))
nlabels := make([]Labels, len(labels))
for k, v := range labels {
nlabels[k].Value = v
nlabels[k].ID = k
}
// cookie creation
rawCookie := make([]byte, 12)
rand.Read(rawCookie)
cookieName := hex.EncodeToString(rawCookie)
publicador.cookie = http.Cookie{Name: "sibbr-tableconverter", Value: cookieName, MaxAge: cookieDuration, HttpOnly: true}
http.SetCookie(w, &publicador.cookie)
publicador.created = time.Now()
publicador.form = r.MultipartForm
mutex.Lock()
Publicadores[cookieName] = publicador
mutex.Unlock()
renderTemplate(w, "labels", &nlabels)
} else if r.Method == "GET" {
cookie, err := r.Cookie("sibbr-tableconverter")
if err != nil {
http.Redirect(w, r, "http://"+r.Host, 302)
return
}
var publicador Publicador
// check if cookie is alive on server side
mutex.RLock()
if _, ok := Publicadores[cookie.Value]; ok {
publicador = Publicadores[cookie.Value]
} else {
http.Redirect(w, r, "http://"+r.Host, 302)
return
}
mutex.RUnlock()
// Parse form values
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
// Inverting form values (maps golang)
fixed := []int{}
reverseForm := map[int]string{}
for k, v := range r.Form {
numero, _ := strconv.Atoi(v[0])
fixed = append(fixed, numero)
reverseForm[numero] = k
}
sort.Ints(fixed)
ordenados := []string{}
for i := 0; i < len(fixed); i++ {
ordenados = append(ordenados, reverseForm[fixed[i]])
}
// Seeking fp cause of getLabels used early
_, err = publicador.fp.Seek(0, 0)
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
// First run of Melt looking for errors
// FIXME: buffer output to escape second Melt call
err = Melt(publicador.fp, ioutil.Discard, ordenados, publicador.sep)
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
// Rewind because of the first Melt call
_, err = publicador.fp.Seek(0, 0)
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
// set cookie to delete, processing done
publicador.cookie.MaxAge = -1
http.SetCookie(w, &publicador.cookie)
w.Header().Set("Content-Disposition", "attachment; filename=converted.csv")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
Melt(publicador.fp, w, ordenados, publicador.sep)
// delete publisher
mutex.Lock()
Publicadores[cookie.Value].fp.Close()
Publicadores[cookie.Value].form.RemoveAll()
delete(Publicadores, cookie.Value)
mutex.Unlock()
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *[]Labels) {
err := templates.ExecuteTemplate(w, tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getLabels(input io.Reader, sep string) []string {
dados := csv.NewReader(input)
if sep == "tab" {
dados.Comma = '\t'
} else {
dados.Comma = rune(sep[0])
}
dados.FieldsPerRecord = -1
labels, err := dados.Read()
if err != nil {
return nil
}
return labels
}
func home(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadFile("index.html")
if err != nil {
w.WriteHeader(404)
fmt.Fprint(w, "Page not found")
}
io.Copy(w, strings.NewReader(string(content)))
}
func main() {
// goroutine to remove expired info (invalid cookie, files) from server
go func() {
for {
time.Sleep(30 * time.Second)
mutex.Lock()
for k, v := range Publicadores {
if v.created.Add(time.Duration(cookieDuration) * time.Second).After(time.Now()) {
Publicadores[k].fp.Close()
Publicadores[k].form.RemoveAll()
delete(Publicadores, k)
}
}
mutex.Unlock()
}
}()
fsCSS := http.FileServer(http.Dir("css"))
http.Handle("/css/", http.StripPrefix("/css/", fsCSS))
fsIMG := http.FileServer(http.Dir("img"))
http.Handle("/img/", http.StripPrefix("/img/", fsIMG))
fsJS := http.FileServer(http.Dir("js"))
http.Handle("/js/", http.StripPrefix("/js/", fsJS))
http.HandleFunc("/upload", upload)
http.HandleFunc("/", home)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}