-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnex.go
108 lines (98 loc) · 2.39 KB
/
nex.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
// URL Handler for nex protocol: nex.nightfall.city
package main
import (
"bufio"
"fmt"
"net"
"net/url"
"strings"
)
type NexResponse struct {
bodyReader *bufio.Reader
bodyReaderClosed bool
conn *net.Conn
connClosed bool
fileExt string // From request
}
// NexParsedURL fetches u and returns a NexResponse
func NexParsedURL(u *url.URL) (res *NexResponse, err error) {
host := u.Host
if u.Port() == "" {
host += ":1900" // Default port
}
// Connect to server, no TLS
conn, err := net.Dial("tcp", host)
if err != nil {
return
}
path := u.Path
if u.Path == "" {
path = "/"
}
fileExt := "/"
if !strings.HasSuffix(path, "/") {
fileExt = strings.SplitN(path, ".", 2)[1]
}
// Requests are simply file paths
conn.Write([]byte(fmt.Sprintf("%s\n", path)))
// Receive and parse response header
reader := bufio.NewReader(conn)
res = &NexResponse{
bodyReader: reader,
bodyReaderClosed: false, // idk
conn: &conn,
connClosed: false,
fileExt: fileExt,
}
return
}
func (c *Client) ParseNexDirectoryPage(page *Page) string {
var linkStyle = c.style.gmiLink.Sprint
body := string(page.bodyBytes)
rendered := []string{}
maxWidth := 0
for _, line := range strings.Split(body, "\n") {
if strings.HasSuffix(line, "\r") {
line = strings.Trim(line, "\r")
}
if strings.HasPrefix(line, "=>") {
originalLine := line
line = strings.TrimSpace(line[2:])
if line == "" {
// Empty link line
rendered = append(rendered, originalLine)
continue
}
bits := strings.Fields(line)
parsedLink, err := url.Parse(bits[0])
if err != nil {
rendered = append(rendered, originalLine)
continue
}
link := page.u.ResolveReference(parsedLink) // link url
var label string // link text
if len(bits) == 1 {
label = bits[0]
} else {
label = strings.Join(bits[1:], " ")
}
c.links = append(c.links, link.String())
linkLine := fmt.Sprintf("[%d] ", len(c.links))
linkLine += linkStyle(label)
if link.Scheme != "nex" {
linkLine += fmt.Sprintf(" (%s)", link.Scheme)
}
if len(c.links) < 10 {
linkLine = " " + linkLine
}
rendered = append(rendered, linkLine)
} else {
// Normal paragraph
rendered = append(rendered, line)
if len(line) > maxWidth {
maxWidth = len(line)
}
}
}
return c.Centered(rendered, maxWidth, []int{})
}