-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
83 lines (74 loc) · 1.53 KB
/
server.go
File metadata and controls
83 lines (74 loc) · 1.53 KB
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
package plexible
import (
"bufio"
"bytes"
"fmt"
"net"
"strings"
"time"
)
type Server struct {
Addr net.Addr
Params map[string]string
}
func DiscoverServers(duration time.Duration) ([]*Server, error) {
// Create UDP socket with OS-assigned port.
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, err
}
defer conn.Close()
// Broadcast discovery message to Plex server port.
conn.WriteTo(
[]byte("M-SEARCH * HTTP/1.0"),
&net.UDPAddr{IP: net.ParseIP(discoveryIP), Port: serverDiscoveryPort},
)
// Start goroutine to listen for server responses.
ch := make(chan *Server)
go func() {
b := make([]byte, 1024)
n, addr, err := conn.ReadFrom(b)
if err != nil {
return
}
params, err := parseServerResponse(b[:n])
if err != nil {
return
}
ch <- &Server{addr, params}
}()
// Collect servers until the timeout.
servers := []*Server{}
timeout := time.After(duration)
Collection:
for {
select {
case s := <-ch:
servers = append(servers, s)
case <-timeout:
break Collection
}
}
return servers, nil
}
func parseServerResponse(b []byte) (map[string]string, error) {
params := map[string]string{}
s := bufio.NewScanner(bytes.NewReader(b))
first := true
for s.Scan() {
line := s.Text()
if first {
if line != "HTTP/1.0 200 OK" {
return nil, fmt.Errorf("Unrecognised response header: %s", line)
}
first = false
continue
}
if line == "" {
break
}
parts := strings.SplitN(line, ":", 2)
params[parts[0]] = strings.TrimSpace(parts[1])
}
return params, nil
}