-
Notifications
You must be signed in to change notification settings - Fork 0
/
qurl.go
263 lines (228 loc) · 5.47 KB
/
qurl.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
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
package main
import (
"embed"
"flag"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/skip2/go-qrcode"
"golang.org/x/term"
)
//go:embed templates/upload.html
var templates embed.FS
const (
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
suffixLength = 10
defaultPort = ":8081"
ipPrefix = "192.168." // try to guess the local net prefix
uploadedMsg = "File uploaded successfully"
)
type QRCode struct {
size int
modules [][]bool
}
func main() {
helpFlag := flag.Bool("h", false, "Show help message")
shareFile := flag.String("f", "", "File to share")
shareText := flag.String("t", "", "Text to share")
flag.Parse()
if *helpFlag {
flag.Usage()
os.Exit(0)
}
// If sharing text less than 200 chars, use QR code directly
if *shareText != "" && len(*shareText) < 200 {
qr, err := qrcode.New(*shareText, qrcode.Low)
if err != nil {
fmt.Printf("Failed to generate QR code: %v\n", err)
os.Exit(1)
}
clearScreen()
printQRCode(&QRCode{
size: len(qr.Bitmap()),
modules: convertBitmap(qr.Bitmap()),
})
return
}
done := make(chan bool)
// Generate random suffix
src := rand.NewSource(time.Now().UnixNano())
rand.New(src)
b := make([]byte, suffixLength)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
randomSuffix := string(b)
// Set up HTTP server
http.HandleFunc("/"+randomSuffix, func(w http.ResponseWriter, r *http.Request) {
if *shareFile != "" {
file, err := os.Open(*shareFile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(*shareFile))
io.Copy(w, file)
clearScreen()
fmt.Println(uploadedMsg)
done <- true
return
} else if *shareText != "" {
w.Write([]byte(*shareText))
clearScreen()
done <- true
return
}
if r.Method == "GET" {
template, err := templates.ReadFile("templates/upload.html")
if err != nil {
http.Error(w, "Failed to load template", http.StatusInternalServerError)
return
}
w.Write(template)
} else if r.Method == "POST" {
if text := r.FormValue("text"); text != "" {
clearScreen()
fmt.Println(text)
done <- true
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
dst, err := os.Create(filepath.Join(".", header.Filename))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
clearScreen()
fmt.Println(uploadedMsg)
done <- true
}
})
// Get local networks IP address or use environment variable
var localIP string
if envHost := os.Getenv("HOST_ADDR"); envHost != "" {
localIP = envHost
} else {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Printf("Failed to get interface addresses: %v\n", err)
os.Exit(1)
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok {
ipStr := ipnet.IP.String()
if len(ipStr) >= 8 && ipStr[:8] == ipPrefix {
if ipnet.IP.To4() != nil {
localIP = ipStr
break
}
}
}
}
if localIP == "" {
fmt.Println("Could not find local networks IP address")
os.Exit(1)
}
}
// Get port from env var or use default
port := defaultPort
if envPort := os.Getenv("HOST_PORT"); envPort != "" {
port = ":" + envPort
}
// Start server in goroutine
go func() {
if err := http.ListenAndServe(port, nil); err != nil {
fmt.Printf("Failed to start server: %v\n", err)
os.Exit(1)
}
}()
url := fmt.Sprintf("http://%s%s/%s", localIP, port, randomSuffix)
qr, err := qrcode.New(url, qrcode.Low)
if err != nil {
fmt.Printf("Failed to generate QR code: %v\n", err)
os.Exit(1)
}
clearScreen()
printQRCode(&QRCode{
size: len(qr.Bitmap()),
modules: convertBitmap(qr.Bitmap()),
})
<-done
os.Exit(0)
}
func convertBitmap(bitmap [][]bool) [][]bool {
size := len(bitmap)
modules := make([][]bool, size)
for i := range modules {
modules[i] = make([]bool, size)
for j := range modules[i] {
modules[i][j] = bitmap[i][j]
}
}
return modules
}
func printQRCode(qr *QRCode) {
width, height, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println("Could not get the size of the terminal, exiting..")
os.Exit(1)
}
// Check if terminal is large enough
qrWidth := qr.size * 2
qrHeight := qr.size
if width < qrWidth || height < qrHeight {
fmt.Printf("Make sure the terminal size is at least %d rows * %d cols,\nto display the QR Code correctly\n", qrHeight, qrWidth)
os.Exit(0)
}
// Calculate padding for centering
hPadding := (width - qrWidth) / 2
vPadding := (height - qrHeight) / 2
// Print vertical padding
for i := 0; i < vPadding; i++ {
fmt.Println()
}
// Print QR code with horizontal padding
for i := 0; i < qr.size; i++ {
fmt.Print(strings.Repeat(" ", hPadding))
for j := 0; j < qr.size; j++ {
if qr.modules[i][j] {
fmt.Print("██")
} else {
fmt.Print(" ")
}
}
fmt.Println()
}
}
func clearScreen() {
switch runtime.GOOS {
case "linux", "darwin":
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
case "windows":
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
cmd.Run()
}
}