-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
handlers.go
169 lines (152 loc) · 4.5 KB
/
handlers.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
// Copyright 2020-2021 Changkun Ou. All rights reserved.
// Use of this source code is governed by a GPL-3.0
// license that can be found in the LICENSE file.
package daemon
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"changkun.de/x/midgard/internal/clipboard"
"changkun.de/x/midgard/internal/config"
"changkun.de/x/midgard/internal/types"
"changkun.de/x/midgard/internal/types/proto"
"changkun.de/x/midgard/internal/utils"
"changkun.de/x/midgard/internal/version"
)
// Ping response a pong
func (m *Daemon) Ping(ctx context.Context, in *proto.PingInput) (*proto.PingOutput, error) {
return &proto.PingOutput{
Version: version.GitVersion,
GoVersion: version.GoVersion,
BuildTime: version.BuildTime,
}, nil
}
// AllocateURL request the midgard server to allocate a given URL for
// a given resource, or the content from the midgard universal clipboard.
func (m *Daemon) AllocateURL(ctx context.Context, in *proto.AllocateURLInput) (*proto.AllocateURLOutput, error) {
var (
source = types.SourceUniversalClipboard
data string
uri string
)
if in.SourcePath != "" {
source = types.SourceAttachment
b, err := os.ReadFile(in.SourcePath)
if err != nil {
return nil, fmt.Errorf("failed to read %v, err: %w", in.SourcePath, err)
}
data = base64.StdEncoding.EncodeToString(b)
}
if in.DesiredPath != "" {
// we want to make sure the extension of the file is correct
dext := filepath.Ext(in.DesiredPath)
sext := filepath.Ext(in.SourcePath)
uri = strings.TrimSuffix(in.DesiredPath, dext) + sext
}
res, err := utils.Request(
http.MethodPut,
types.EndpointAllocateURL,
&types.AllocateURLInput{
Source: source,
URI: uri,
Data: data,
})
if err != nil {
return nil, fmt.Errorf("cannot perform allocate request, err %w", err)
}
var out types.AllocateURLOutput
err = json.Unmarshal(res, &out)
if err != nil {
return nil, fmt.Errorf("cannot parse requested URL, err: %w", err)
}
if out.URL == "" {
return nil, fmt.Errorf("%s", out.Message)
}
url := config.Get().Domain + out.URL
clipboard.Local.Write(types.MIMEPlainText, utils.StringToBytes(url))
return &proto.AllocateURLOutput{URL: url, Message: "Done."}, nil
}
// CodeToImage tries to create an image for the given code.
func (m *Daemon) CodeToImage(ctx context.Context, in *proto.CodeToImageInput) (out *proto.CodeToImageOutput, err error) {
log.Println("received a code2img request:", in.CodePath)
var code string
// the user presented a file, so we read it.
// if it does not exist, then we don't bother the server.
if len(in.CodePath) > 0 {
if in.Start == in.End && in.Start == 0 {
b, err := os.ReadFile(in.CodePath)
if err != nil {
return nil, fmt.Errorf("cannot read the given file: %w", err)
}
code = utils.BytesToString(b)
} else {
f, err := os.Open(in.CodePath)
if err != nil {
return nil, fmt.Errorf("cannot read the given file: %w", err)
}
s := bufio.NewScanner(f)
line := int64(1)
for s.Scan() {
if line < in.Start {
line++
continue
} else if line > in.End {
break
}
code += s.Text() + "\n"
line++
}
code = code[:len(code)-1] // remove the last \n
f.Close()
}
}
res, err := utils.Request(http.MethodPost, types.EndpointCode2Image, &types.Code2ImgInput{Code: code})
if err != nil {
return nil, fmt.Errorf("failed to convert: %w", err)
}
var o types.Code2ImgOutput
err = json.Unmarshal(res, &o)
if err != nil {
return nil, fmt.Errorf("failed to parse server response: %w", err)
}
// write to local clipboard.
clipboard.Local.Write(types.MIMEPlainText,
utils.StringToBytes(config.Get().Domain+o.Image))
return &proto.CodeToImageOutput{
CodeURL: o.Code,
ImageURL: o.Image,
}, nil
}
// ListDaemons lists all active daemons.
func (m *Daemon) ListDaemons(ctx context.Context, in *proto.ListDaemonsInput) (out *proto.ListDaemonsOutput, err error) {
readerCh := make(chan *types.WebsocketMessage)
m.readChs.Store(m.ID, readerCh)
m.writeCh <- &types.WebsocketMessage{
Action: types.ActionListDaemonsRequest,
UserID: m.ID,
Message: "list active daemons",
}
for {
select {
case <-ctx.Done():
log.Println("list daemons timeout!")
return nil, errors.New("list daemons timeout")
case resp := <-readerCh:
switch resp.Action {
case types.ActionListDaemonsResponse:
m.readChs.Delete(m.ID)
return &proto.ListDaemonsOutput{Daemons: utils.BytesToString(resp.Data)}, nil
default:
log.Println(resp.Message)
}
}
}
}