summaryrefslogtreecommitdiff
path: root/internal/api/utilities.go
blob: 4a816fc94c55d1efd3eb879121b60bc93db07850 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// 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
		}
	}
}

func randomSelect[T any](src []T, n int) []T {
    if n <= 0 || len(src) == 0 {
        return nil
    }
    if n >= len(src) {
        // Return a copy of the whole slice
        cpy := make([]T, len(src))
        copy(cpy, src)
        return cpy
    }

    // Make a copy so we don't modify the original slice
    tmp := make([]T, len(src))
    copy(tmp, src)

    // Shuffle the copy in‑place
    rand.Shuffle(len(tmp), func(i, j int) {
        tmp[i], tmp[j] = tmp[j], tmp[i]
    })

    // Return the first n elements of the shuffled slice
    return tmp[:n]
}