summaryrefslogtreecommitdiff
path: root/internal/api/utilities.go
blob: 508e3416cbf15a8e2267dba30c6c40bc083f8240 (plain) (blame)
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
// This file is a part of Taskflow.
// Copyright (C) 2025  Robby Zambito
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package api

import (
	"math/rand"
	"net"
	"regexp"
	"strings"
)

func runChance(likelihood float64, action func()) {
	if likelihood <= 0 {
		return // never run
	}
	if likelihood >= 1 {
		action()
		return
	}

	if rand.Float64() < likelihood {
		action()
	}
}

func redactIP(input string) string {
	ipRegex := `\b(?:\d{1,3}\.){3}\d{1,3}\b`
	re := regexp.MustCompile(ipRegex)

	return re.ReplaceAllStringFunc(input, func(match string) string {
		if ip := net.ParseIP(match); ip != nil {
			parts := strings.Split(match, ".")
			if len(parts) == 4 {
				parts[3] = "XXX"
				return strings.Join(parts, ".")
			}
		}
		return match
	})
}

func addRotLog(logs *[LogLength]string, last *int, parser chan string, value string) {
	if strings.Contains(value, "\n") {
		for _, v := range strings.Split(value, "\n") {
			addRotLog(logs, last, parser, v)
		}
	} else {
		if *last == LogLength {
			for i := 0; i < LogLength-1; i++ {
				logs[i] = logs[i+1]
			}
			logs[LogLength-1] = value
			parser <- value
		} else {
			logs[*last] = value
			*last++
			parser <- value
		}
	}
}