-
Notifications
You must be signed in to change notification settings - Fork 0
/
target.go
351 lines (324 loc) · 9.04 KB
/
target.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2023 Dmitry Dikun
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"errors"
"fmt"
"google.golang.org/api/drive/v3"
"html/template"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
type target interface {
ID() string
Type() string
Name() string
Insert(row map[string]string, fs *drive.FilesService) (string, error)
//Update(row map[string]string, fs *drive.FilesService) (error)
Finish() error
}
func newTarget(cfg *config, tcfg *targetConfig, tdir string) (target, error) {
switch tcfg.Type {
case telegramTargetType:
return newTelegramTarget(tcfg, cfg.TelegramBotToken, tdir)
case htmlCatalogTargetType:
return newHTMLCatalogTarget(tcfg, tdir)
default:
return nil, errors.New("invalid target")
}
}
func targetStatusFieldName(t target) string {
return t.ID() + "_status"
}
func targetRecordIdFieldName(t target) string {
return t.ID() + "_record_id"
}
func copyRow(row map[string]string) map[string]string {
row2 := make(map[string]string, len(row))
for k, v := range row {
row2[k] = v
}
return row2
}
func copyRowAny(row map[string]string) map[string]any {
row2 := make(map[string]any, len(row))
for k, v := range row {
row2[k] = v
}
return row2
}
const telegramTargetType = "telegram"
type telegramTarget struct {
taskDir string
name string
token string
channel string
template *template.Template
}
func newTelegramTarget(cfg *targetConfig, token string, tdir string) (target, error) {
tmpl, err := template.ParseFiles(cfg.Template)
if err != nil {
return nil, fmt.Errorf("failed to parse template: %v", err)
}
return &telegramTarget{
taskDir: tdir,
name: cfg.Name,
token: token,
channel: cfg.TelegramChannel,
template: tmpl,
}, nil
}
func (tt *telegramTarget) ID() string {
return telegramTargetType + "_" + tt.name
}
func (tt *telegramTarget) Type() string {
return telegramTargetType
}
func (tt *telegramTarget) Name() string {
return tt.name
}
func (tt *telegramTarget) Insert(row map[string]string, fs *drive.FilesService) (string, error) {
row = copyRow(row)
var buf bytes.Buffer
if err := tt.template.Execute(&buf, row); err != nil {
return "", fmt.Errorf("failed to render template: %v", err)
}
if aname, ok := row["audio"]; ok && aname != "" {
tadir := filepath.Join(tt.taskDir, "audio")
tafile := filepath.Join(tadir, aname)
if _, err := os.Stat(tafile); err != nil {
if !os.IsNotExist(err) {
return "", err
}
id, err := getDriveFileId(fs, aname, "")
if err != nil {
return "", err
}
rc, err := getDriveFileReadCloser(fs, id, "")
if err != nil {
return "", err
}
defer rc.Close()
if err = os.MkdirAll(tadir, dirPerm); err != nil {
return "", err
}
taf, err := os.OpenFile(tafile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, filePerm)
if err != nil {
return "", err
}
defer taf.Close()
defer taf.Sync()
return telegramSendAudioStream(tt.token, tt.channel, aname, rc, taf, buf.String())
} else {
taf, err := os.OpenFile(tafile, os.O_RDONLY, 0)
if err != nil {
return "", err
}
defer taf.Close()
return telegramSendAudioStream(tt.token, tt.channel, aname, taf, nil, buf.String())
}
//id, err := getDriveFileId(fs, audio, "")
//if err != nil {
// return "", err
//}
//rc, err := getDriveFileReadCloser(fs, id, "")
//if err != nil {
// return "", err
//}
//defer rc.Close()
//return telegramSendAudioStream(tt.token, tt.channel, audio, rc, buf.String())
} else {
return telegramSendMessage(tt.token, tt.channel, buf.String())
}
}
func (tt *telegramTarget) Finish() error {
return nil
}
const htmlCatalogTargetType = "html_catalog"
type htmlCatalogTarget struct {
taskDir string
name string
catalog string
catalogDir string
catalogIndex string
tmpIndex string
indexBuf []byte
lastId int
template *template.Template
staticPrefix string
indexPlaceholder string
}
func newHTMLCatalogTarget(cfg *targetConfig, tdir string) (target, error) {
if cfg.IndexPlaceholder == "" {
return nil, errors.New("invalid config: index placeholder not set")
}
cdir := filepath.Join(cfg.Dir, cfg.Catalog)
if err := os.MkdirAll(cdir, dirPerm); err != nil {
return nil, fmt.Errorf("failed to create catalog directory: %v", err)
}
idxfile := filepath.Join(cdir, "index.html")
idxbuf, err := os.ReadFile(idxfile)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to read catalog index: %v", err)
}
idxbuf = []byte(fmt.Sprintf("<ul>%s</ul>", cfg.IndexPlaceholder))
if err = os.WriteFile(idxfile, idxbuf, filePerm); err != nil {
return nil, fmt.Errorf("failed to create catalog index: %v", err)
}
}
tmpl, err := template.ParseFiles(cfg.Template)
if err != nil {
return nil, fmt.Errorf("failed to parse template: %v", err)
}
maxId := 0
if dirents, err := os.ReadDir(cdir); err != nil {
return nil, fmt.Errorf("failed to read catalog directory: %v", err)
} else {
for _, dirent := range dirents {
if id, err := strconv.Atoi(dirent.Name()); err == nil && maxId < id {
maxId = id
}
}
}
t := &htmlCatalogTarget{
taskDir: tdir,
name: cfg.Name,
catalog: cfg.Catalog,
catalogDir: cdir,
catalogIndex: idxfile,
indexBuf: idxbuf,
lastId: maxId,
template: tmpl,
staticPrefix: strings.Trim(cfg.StaticPrefix, "/"),
indexPlaceholder: cfg.IndexPlaceholder,
}
t.tmpIndex = filepath.Join(tdir, t.ID()+"_index.html")
return t, nil
}
func (ct *htmlCatalogTarget) ID() string {
return htmlCatalogTargetType + "_" + ct.name
}
func (ct *htmlCatalogTarget) Type() string {
return htmlCatalogTargetType
}
func (ct *htmlCatalogTarget) Name() string {
return ct.name
}
func (ct *htmlCatalogTarget) Insert(row1 map[string]string, fs *drive.FilesService) (string, error) {
row := copyRowAny(row1)
title, _ := row["title"].(string)
if title == "" {
return "", errors.New("invalid row: no title")
}
text, _ := row["text"].(string)
if text == "" {
return "", errors.New("invalid row: no text")
}
row["text"] = template.HTML(strings.ReplaceAll(
"<p>"+strings.ReplaceAll(text, "\n", "</p><p>")+"</p>",
"<p></p>",
"",
))
id := strconv.Itoa(ct.lastId + 1)
idir := filepath.Join(ct.catalogDir, id)
if err := os.MkdirAll(idir, dirPerm); err != nil {
return "", err
}
if err := func() error {
if aname, ok := row["audio"].(string); ok && aname != "" {
tadir := filepath.Join(ct.taskDir, "audio")
tafile := filepath.Join(tadir, aname)
iafile := filepath.Join(idir, aname)
if _, err := os.Stat(tafile); err != nil {
if !os.IsNotExist(err) {
return err
}
id, err := getDriveFileId(fs, aname, "")
if err != nil {
return err
}
rc, err := getDriveFileReadCloser(fs, id, "")
if err != nil {
return err
}
defer rc.Close()
if err = os.MkdirAll(tadir, dirPerm); err != nil {
return err
}
taf, err := os.OpenFile(tafile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, filePerm)
if err != nil {
return err
}
defer taf.Close()
defer taf.Sync()
iaf, err := os.OpenFile(iafile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, filePerm)
if err != nil {
return err
}
defer iaf.Close()
defer iaf.Sync()
if _, err := io.Copy(io.MultiWriter(taf, iaf), rc); err != nil {
return err
}
} else {
taf, err := os.OpenFile(tafile, os.O_RDONLY, 0)
if err != nil {
return err
}
defer taf.Close()
iaf, err := os.OpenFile(iafile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, filePerm)
if err != nil {
return err
}
defer iaf.Close()
defer iaf.Sync()
if _, err := io.Copy(iaf, taf); err != nil {
return err
}
}
row["audio"] = filepath.Join("/", ct.staticPrefix, ct.catalog, id, aname)
}
f, err := os.OpenFile(filepath.Join(idir, "index.html"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, filePerm)
if err != nil {
return err
}
defer f.Close()
defer f.Sync()
if err = ct.template.Execute(f, row); err != nil {
return fmt.Errorf("failed to render template: %v", err)
}
ct.indexBuf = bytes.Replace(ct.indexBuf, []byte(ct.indexPlaceholder),
[]byte(fmt.Sprintf(`<li><a href='/%s?item=%s'>%s</a></li>`, ct.catalog, id, title)+ct.indexPlaceholder), 1)
if err = os.WriteFile(ct.tmpIndex, ct.indexBuf, filePerm); err != nil {
return err
}
if err = os.Rename(ct.tmpIndex, ct.catalogIndex); err != nil {
return err
}
ct.lastId++
return nil
}(); err != nil {
_ = os.RemoveAll(idir)
return "", err
}
return id, nil
}
func (ct *htmlCatalogTarget) Finish() error {
return nil
}