all repos — paprika @ master

go rewrite of taigabot

plugins/quotes.go (view raw)

 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
package plugins

import (
	"bytes"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strconv"
	"strings"

	"git.icyphox.sh/paprika/database"
	"github.com/dgraph-io/badger/v3"
	"gopkg.in/irc.v3"
)

type Quotes struct{}

func init() {
	Register(Quotes{})
}

func (Quotes) Triggers() []string {
	return []string{".q", ".quote"}
}

func result(quoteNum int, total int, nick string, quote string) string {
	return fmt.Sprintf("[%d/%d] <%s> %s", quoteNum, total, nick, quote)
}

var found = errors.New("Found")
var KeyEncodingError = errors.New("Unexpected key encoding")
var TooManyQuotes = errors.New("Too many quotes")

func getQuoteTotal(txn *badger.Txn, keyPrefix []byte) (int, error) {
	item, err := txn.Get([]byte(keyPrefix))
	if err != nil {
		return 0, err
	}
	it, err := item.ValueCopy(nil)
	if err != nil {
		return 0, err
	}
	res, err := strconv.Atoi(string(it))
	if _, ok := err.(*strconv.NumError); ok {
		log.Printf("quotes.go: Warning: Something is wrong with the value in key: %s", keyPrefix)
		return 0, nil // return 0 in hopes of it being overwritten
	} else if err != nil {
		return 0, err
	}
	return res, nil
}

func getAndIncrementQuoteTotal(txn *badger.Txn, keyPrefix []byte) (int, error) {
	total, err := getQuoteTotal(txn, keyPrefix)
	if err == badger.ErrKeyNotFound {
		total = 0
	} else if err != nil {
		return 0, err
	}
	total++
	return total, txn.Set(keyPrefix, []byte(strconv.Itoa(total)))
}

func findQuotes(nick string, keyPrefix, search []byte) (string, error) {
	var (
		num   int
		total int
		quote string
	)

	err := database.DB.DB.View(func(txn *badger.Txn) error {
		iter := txn.NewIterator(badger.DefaultIteratorOptions)
		defer iter.Close()

		var err error
		prefix := append(keyPrefix, ' ')
		for iter.Seek(prefix); iter.ValidForPrefix(prefix); iter.Next() {
			item := iter.Item()
			key := item.Key()
			err = item.Value(func(val []byte) error {
				if bytes.Contains(val, search) {
					quote = string(val)
					keys := bytes.SplitN(key, []byte{' '}, 3)
					if len(keys) != 3 {
						log.Printf("quotes.go: Key Error: %s is not in expected format", key)
						return KeyEncodingError
					}
					num, err = database.DecodeNumber(keys[2])
					if err != nil {
						return err
					} else {
						return found
					}
				} else {
					return nil
				}
			})

			if err != nil {
				break
			}
		}

		if err == found {
			total, err = getQuoteTotal(txn, []byte(keyPrefix))
			if err != nil {
				return err
			} else {
				return found
			}
		} else {
			return err
		}
	})

	if err == nil {
		return "No quote found.", nil
	} else if err == found {
		return result(num, total, nick, quote), nil
	} else {
		return "", err
	}
}

func addQuote(keyPrefix, quote []byte) (string, error) {
	var id int
	err := database.DB.DB.Update(func(txn *badger.Txn) error {
		var err error
		id, err = getAndIncrementQuoteTotal(txn, keyPrefix)
		if err != nil {
			return err
		} else if id > 5_000 {
			return TooManyQuotes
		}

		encodedId, err := database.EncodeNumber(id)
		if err != nil {
			return err
		}

		key := append(keyPrefix, ' ')
		key = append(key, encodedId...)

		err = txn.Set(key, quote)
		if err != nil {
			return err
		}
		return nil
	})
	if err == nil {
		return fmt.Sprintf("Quote %d added.", id), err
	} else {
		return "", err
	}
}

func getQuote(nick string, qnum int, keyPrefix []byte) (string, error) {
	var (
		num      int
		total    int
		quote    string
		negative bool
	)

	if qnum < 0 {
		qnum += 1
		negative = true
	} else {
		negative = false
	}

	err := database.DB.DB.View(func(txn *badger.Txn) error {
		var err error
		total, err = getQuoteTotal(txn, keyPrefix)
		if err != nil {
			return err
		}

		num = qnum
		if negative {
			num = total + qnum
			if num < 1 {
				return badger.ErrKeyNotFound
			}
		} else if num > total {
			return badger.ErrKeyNotFound
		} else if num == randomQuote {
			// [1, total+1)
			num = rand.Intn(total) + 1
		}

		encodeQnum, err := database.EncodeNumber(num)
		if err != nil {
			return err
		}
		encodedKey := append(keyPrefix, ' ')
		encodedKey = append(encodedKey, encodeQnum...)

		qItem, err := txn.Get(encodedKey)
		if err != nil {
			return err
		}
		quoteT, err := qItem.ValueCopy(nil)
		if err != nil {
			return err
		}
		quote = string(quoteT)
		return nil
	})

	if err == badger.ErrKeyNotFound {
		return "No such quote for " + nick, nil
	} else if err != nil {
		return "", err
	} else {
		return result(num, total, nick, quote), nil
	}
}

const randomQuote = 0
const (
	addQ int = iota
	getQ
	start
	parseNick
	parseGetParam
)

func (Quotes) Execute(m *irc.Message) (string, error) {
	params := strings.Split(m.Trailing(), " ")
	if len(params) == 1 {
		return ".q [ add ] nickname [ quote | search | number ]", nil
	}

	pState := start
	cState := getQ

	var nick string
	keyPrefix := []byte(m.Params[0] + " ")
	for i := 1; i < len(params); i++ {
		word := params[i]
	back:
		if len(word) == 0 {
			continue
		}
		switch pState {
		case start:
			pState = parseNick
			if word == "add" {
				cState = addQ
			} else {
				goto back
			}
		case parseNick:
			if word == "<" || len(word) == 0 {
				break
			}

			// <xyz> -> xyz
			word = strings.TrimPrefix(word, "<")
			word = strings.TrimSuffix(word, ">")
			if len(word) == 0 {
				return "Invalid nickname given", nil
			}
			// This is used elsewhere to check the prefix of a "target"
			// if it's true, then this word still has a prefix we can
			// remove.
			if likelyInvalidNickChr(word[0]) {
				word = word[1:]
			}
			if len(word) == 0 {
				return "Invalid nickname given", nil
			}
			// we only allow "< " prefix, not "<" + 2*sym
			for j := 0; j < len(word); j++ {
				if likelyInvalidNickChr(word[j]) {
					return fmt.Sprintf("Invalid nickname: %s", word), nil
				}
			}
			nick = word
			keyPrefix = append(keyPrefix, nick...)
			if cState == addQ {
				quote := strings.Join(params[i+1:], " ")
				if len(quote) == 0 {
					return "Empty quote not allowed.", nil
				}
				return addQuote(keyPrefix, []byte(quote))
			} else {
				pState = parseGetParam
			}
		case parseGetParam:
			if i+1 == len(params) {
				qnum, err := strconv.Atoi(word)
				if err != nil {
					return findQuotes(nick, keyPrefix, []byte(word))
				} else {
					return getQuote(nick, qnum, keyPrefix)
				}
			} else {
				quote := strings.Join(params[i+1:], " ")
				return findQuotes(nick, keyPrefix, []byte(quote))
			}
		}
	}
	// If no number given, use 0 to indicate random quote.
	if pState == parseGetParam {
		return getQuote(nick, randomQuote, keyPrefix)
	} else {
		return "Invalid number of parameters.", nil
	}
}