summaryrefslogtreecommitdiff
path: root/iris/backend.go
blob: fae53228e0c6cb29b84f3438f4e2a229879a9033 (plain)
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package iris

import (
	"bytes"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/mail"
	"net/textproto"
	"os"
	"os/exec"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/dustin/go-nntp"
	nntpserver "github.com/dustin/go-nntp/server"
	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
)

var group = &nntp.Group{
	Name:        "ctrl-c.iris",
	Description: "The iris message board",
	Posting:     nntp.PostingPermitted,
	Low:         1,
}

const DefaultWaitTime = 30 * time.Second
const msgfile = ".iris.messages"

// NewBackend builds an iris nntp backend.
//
// The provided waitTime may be <= 0, in which case DefaultWaitTime will be used.
func NewBackend(logger log.Logger, waitTime time.Duration) (nntpserver.Backend, error) {
	if waitTime <= 0 {
		waitTime = DefaultWaitTime
	}

	b := &backend{logger: logger, waitTime: waitTime}
	if err := b.refresh(); err != nil {
		return nil, err
	}

	return b, nil
}

type backend struct {
	logger   log.Logger
	waitTime time.Duration
	lastRead time.Time
	messages []*nntp.Article
}

func (b backend) debug(keyvals ...any) error { return level.Debug(b.logger).Log(keyvals...) }
func (b backend) info(keyvals ...any) error  { return level.Info(b.logger).Log(keyvals...) }
func (b backend) warn(keyvals ...any) error  { return level.Warn(b.logger).Log(keyvals...) }
func (b backend) err(keyvals ...any) error   { return level.Error(b.logger).Log(keyvals...) }

func (b backend) ListGroups(max int) ([]*nntp.Group, error) {
	return []*nntp.Group{group}, nil
}

func (b *backend) GetGroup(name string) (*nntp.Group, error) {
	if name != group.Name {
		return nil, nntpserver.ErrNoSuchGroup
	}
	if err := b.refresh(); err != nil {
		return nil, err
	}

	return group, nil
}

func (b *backend) GetArticles(_ *nntp.Group, from, to int64) ([]nntpserver.NumberedArticle, error) {
	if err := b.refresh(); err != nil {
		return nil, err
	}

	numbered := make([]nntpserver.NumberedArticle, 0, len(b.messages))
	for i, msg := range b.messages {
		num := int64(i + 1)
		if num >= from && num <= to {
			numbered = append(numbered, nntpserver.NumberedArticle{
				Num:     num,
				Article: copyArticle(msg),
			})
		}
	}

	return numbered, nil
}

func (b *backend) GetArticle(_ *nntp.Group, messageID string) (*nntp.Article, error) {
	if err := b.refresh(); err != nil {
		return nil, err
	}

	for _, msg := range b.messages {
		if msg.Header.Get("Message-Id") == messageID {
			return msg, nil
		}
	}

	num, err := strconv.Atoi(messageID)
	if err == nil && num <= len(b.messages) {
		return copyArticle(b.messages[num-1]), nil
	}

	return nil, nntpserver.ErrInvalidMessageID
}

func (b backend) Post(article *nntp.Article) error {
	// iris replies are all made to a top-level post, there is no grandchild nesting.
	//
	// but NNTP supports this, so collapse the provided "References" header up to the OP.
	parent := b.findOP(article.Header.Get("References"))
	if parent != nil {
		article.Header.Set("References", parent.MessageID())
	}

	msg, err := msgToIris(article)
	if err != nil {
		return err
	}
	return appendMessage(msg)
}

func (b backend) Authorized() bool                                     { return true }
func (b backend) AllowPost() bool                                      { return true }
func (b backend) Authenticate(_, _ string) (nntpserver.Backend, error) { return nil, nil }

func (b backend) findOP(ref string) *nntp.Article {
	if ref == "" {
		return nil
	}
	// all references should have the same OP so just take the first
	msgID := strings.SplitN(ref, " ", 2)[0]

	// traverse backwards expecting most reply activity concentrated late in the total history
	for i := len(b.messages) - 1; i >= 0; i-- {
		article := b.messages[i]
		if article.MessageID() != msgID {
			continue
		}

		gpID := article.Header.Get("References")
		if gpID != "" {
			return b.findOP(gpID)
		}
		return article
	}

	return nil
}

func (b *backend) refresh() error {
	now := time.Now()
	if b.lastRead.IsZero() || now.Sub(b.lastRead) > b.waitTime {
		b.lastRead = now
	} else {
		return nil
	}

	binpath, err := exec.LookPath("iris")
	if err != nil {
		return err
	}
	cmd := exec.Command(binpath, "-d")
	buf := &bytes.Buffer{}
	cmd.Stdout = buf

	if err := cmd.Run(); err != nil {
		return err
	}

	msgs := irisDump{}
	if err := json.NewDecoder(buf).Decode(&msgs); err != nil {
		return err
	}

	b.messages, err = msgs.Articles()
	if err != nil {
		return err
	}
	group.High = int64(len(b.messages))
	group.Count = int64(len(b.messages))
	return nil
}

func copyArticle(article *nntp.Article) *nntp.Article {
	out := *article
	out.Body = bytes.NewBuffer(article.Body.(*bytes.Buffer).Bytes())
	return &out
}

type irisMsg struct {
	Hash      string  `json:"hash"`
	EditHash  *string `json:"edit_hash"`
	IsDeleted *bool   `json:"is_deleted"`
	Data      struct {
		Author    string  `json:"author"`
		Parent    *string `json:"parent"`
		Timestamp string  `json:"timestamp"`
		Message   string  `json:"message"`
	} `json:"data"`
}

func (m irisMsg) calcHash() (string, error) {
	/*
		Careful coding here to match ruby's hash calculation:
		```
		Base64.encode64(Digest::SHA1.digest(m["data"].to_json))
		```

		* have to use an encoder rather than json.Marshal so we can
			turn off the default HTML escaping (ruby doesn't do this)
		* strip trailing newline from JSON encoding output
		* add a trailing newline to base64 encoded form
	*/

	b := &bytes.Buffer{}
	enc := json.NewEncoder(b)
	enc.SetEscapeHTML(false)
	if err := enc.Encode(m.Data); err != nil {
		return "", err
	}

	arr := sha1.Sum(bytes.TrimSuffix(b.Bytes(), []byte("\n")))
	s := base64.StdEncoding.EncodeToString(arr[:])
	if !strings.HasSuffix(s, "\n") {
		s += "\n"
	}
	return s, nil
}

func msgToIris(article *nntp.Article) (*irisMsg, error) {
	postTime := time.Now().UTC().Format(time.RFC3339)

	body, err := io.ReadAll(article.Body)
	if err != nil {
		return nil, err
	}

	var msg irisMsg
	msg.Data.Author = irisAuthor(article.Header.Get("From"))
	msg.Data.Timestamp = postTime
	refs := article.Header.Get("References")
	if refs != "" {
		spl := strings.SplitN(refs, " ", 2)
		ref := fromMsgID(spl[0])
		msg.Data.Parent = &ref
		msg.Data.Message = string(body)
	} else {
		msg.Data.Message = irisBody(article.Header.Get("Subject"), string(body))
	}

	hash, err := msg.calcHash()
	if err != nil {
		return nil, err
	}
	msg.Hash = hash

	return &msg, nil
}

func irisBody(subject, body string) string {
	firstline, _, _ := strings.Cut(body, "\n")
	if subject != "" && subject != firstline {
		body = subject + "\n\n" + body
	}
	return body
}

func irisAuthor(nntpAuthor string) string {
	addr, err := mail.ParseAddress(nntpAuthor)
	if err != nil {
		return nntpAuthor
	}

	return addr.Address
}

type irisDump []irisMsg

func (dump irisDump) Articles() ([]*nntp.Article, error) {
	// calculate the article replacements due to edits
	//
	// note: this is only a single "hop", and because there can be edits-of-edits
	// and edits-of-edits-of-edits, we must actually resolve replacements with a loop.
	//
	// we need to keep all the hops though because there could have been replies to
	// the original or to any intermediate edits.
	replacements := make(map[string]string)
	for _, msg := range dump {
		if msg.EditHash != nil {
			replacements[*msg.EditHash] = msg.Hash
		}
	}

	articles := make([]*nntp.Article, 0, len(dump)-len(replacements))

	// index iris hashes -> nntp Articles for reference lookups
	idx := make(map[string]*nntp.Article)

	sort.SliceStable(dump, func(i, j int) bool {
		return dump[i].Data.Timestamp < dump[j].Data.Timestamp
	})

outer:
	for _, msg := range dump {
		if _, ok := replacements[msg.Hash]; ok {
			continue
		}
		if msg.EditHash != nil && *msg.EditHash == msg.Hash {
			continue
		}

		msgID := msgIDFor(&msg)
		ts, err := time.Parse(time.RFC3339, msg.Data.Timestamp)
		if err != nil {
			return nil, err
		}

		article := &nntp.Article{
			Header: textproto.MIMEHeader{
				"Message-Id": []string{msgID},
				"From":       []string{msg.Data.Author},
				"Newsgroups": []string{group.Name},
				"Date":       []string{ts.Format(time.RFC1123Z)},
			},
		}

		if msg.IsDeleted != nil && *msg.IsDeleted {
			article.Header.Set("Subject", "**TOPIC DELETED BY AUTHOR**")
			article.Body = &bytes.Buffer{}
			article.Bytes = 0
			article.Lines = 0
		} else {
			article.Body = bytes.NewBufferString(msg.Data.Message)
			article.Bytes = len(msg.Data.Message)
			article.Lines = strings.Count(msg.Data.Message, "\n")

			if msg.Data.Parent == nil {
				article.Header.Set("Subject", strings.SplitN(msg.Data.Message, "\n", 2)[0])
			} else {
				parentHash := *msg.Data.Parent
				for {
					if p, ok := replacements[parentHash]; ok {
						if parentHash == p {
							continue outer
						}
						parentHash = p
					} else {
						break
					}
				}
				msg.Data.Parent = &parentHash
				parent, ok := idx[parentHash]
				if !ok {
					continue
				}
				parentSubj := strings.TrimPrefix(parent.Header.Get("Subject"), "Re: ")
				article.Header.Set("Subject", "Re: "+parentSubj)
			}
		}

		if msg.Data.Parent != nil {
			parent := idx[*msg.Data.Parent]
			if parent == nil {
				continue
			}
			parentRefs := parent.Header.Get("References")
			if parentRefs != "" {
				article.Header.Set("References", parentRefs)
			} else {
				article.Header.Set("References", parent.MessageID())
			}
		}

		articles = append(articles, article)
		idx[msg.Hash] = article
	}

	return articles, nil
}

func (id irisDump) MarshalJSON() ([]byte, error) {
	buf := &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	enc.SetEscapeHTML(false)

	out := bytes.NewBufferString("[\n  ")

	for i, msg := range id {
		if err := enc.Encode(msg); err != nil {
			return nil, err
		}

		if i > 0 {
			_, _ = out.WriteString(",\n  ")
		}
		_, _ = out.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
		buf.Reset()
	}
	_, _ = out.WriteString("\n]")

	return out.Bytes(), nil
}

func msgIDFor(msg *irisMsg) string {
	return fmt.Sprintf("<%s.%s>",
		strings.TrimSuffix(msg.Hash, "=\n"),
		msg.Data.Author,
	)
}

func fromMsgID(nntpID string) string {
	hash, _, _ := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(nntpID, "<"), ">"), ".")
	return hash + "=\n"
}

func appendMessage(msg *irisMsg) error {
	home, err := os.UserHomeDir()
	if err != nil {
		return err
	}

	msgFile, err := os.Open(path.Join(home, msgfile))
	if err != nil {
		return err
	}

	var msgs irisDump
	if err := json.NewDecoder(msgFile).Decode(&msgs); err != nil {
		_ = msgFile.Close()
		return err
	}
	_ = msgFile.Close()
	msgs = append(msgs, *msg)

	msgFile, err = os.Create(path.Join(home, msgfile))
	if err != nil {
		return err
	}
	defer func() { _ = msgFile.Close() }()

	out, err := msgs.MarshalJSON()
	if err != nil {
		return err
	}
	_, err = msgFile.Write(out)
	return err
}