vendor/github.com/hugolgst/rich-go/ipc/ipc.go
81 lines · 1521 bytes
1package ipc
2
3import (
4 "bytes"
5 "encoding/binary"
6 "fmt"
7 "net"
8 "os"
9)
10
11var socket net.Conn
12
13// Choose the right directory to the ipc socket and return it
14func GetIpcPath() string {
15 variablesnames := []string{"XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"}
16
17 if _, err := os.Stat("/run/user/1000/snap.discord"); err == nil {
18 return "/run/user/1000/snap.discord"
19 }
20
21 if _, err := os.Stat("/run/user/1000/.flatpak/com.discordapp.Discord/xdg-run"); err == nil {
22 return "/run/user/1000/.flatpak/com.discordapp.Discord/xdg-run"
23 }
24
25 for _, variablename := range variablesnames {
26 path, exists := os.LookupEnv(variablename)
27
28 if exists {
29 return path
30 }
31 }
32
33 return "/tmp"
34}
35
36func CloseSocket() error {
37 if socket != nil {
38 socket.Close()
39 socket = nil
40 }
41 return nil
42}
43
44// Read the socket response
45func Read() string {
46 buf := make([]byte, 512)
47 payloadlength, err := socket.Read(buf)
48 if err != nil {
49 //fmt.Println("Nothing to read")
50 }
51
52 buffer := new(bytes.Buffer)
53 for i := 8; i < payloadlength; i++ {
54 buffer.WriteByte(buf[i])
55 }
56
57 return buffer.String()
58}
59
60// Send opcode and payload to the unix socket
61func Send(opcode int, payload string) string {
62 buf := new(bytes.Buffer)
63
64 err := binary.Write(buf, binary.LittleEndian, int32(opcode))
65 if err != nil {
66 fmt.Println(err)
67 }
68
69 err = binary.Write(buf, binary.LittleEndian, int32(len(payload)))
70 if err != nil {
71 fmt.Println(err)
72 }
73
74 buf.Write([]byte(payload))
75 _, err = socket.Write(buf.Bytes())
76 if err != nil {
77 fmt.Println(err)
78 }
79
80 return Read()
81}