organizer/utils.go

66 lines
1.5 KiB
Go
Raw Normal View History

2023-01-15 13:59:48 +01:00
package main
import (
"fmt"
"io"
2023-01-15 19:43:36 +01:00
"os"
"time"
2023-01-15 13:59:48 +01:00
2023-01-15 19:43:36 +01:00
"git.milar.in/milarin/channel"
2023-01-15 13:59:48 +01:00
"git.milar.in/milarin/gmath"
)
2023-01-15 19:43:36 +01:00
func InitializeRunner() channel.Runner {
if ThreadCount <= 0 {
return channel.NewUnlimitedRunner()
}
return channel.NewLimitedRunner(ThreadCount)
}
2023-01-15 13:59:48 +01:00
func FormatBytes[T gmath.Integer](bytes T) string {
value := float64(bytes)
if value >= 1000000000000 {
return fmt.Sprintf("%.02fT", value/1000000000000)
} else if value >= 1000000000 {
return fmt.Sprintf("%.02fG", value/1000000000)
} else if value >= 1000000 {
return fmt.Sprintf("%.02fM", value/1000000)
} else if value >= 1000 {
return fmt.Sprintf("%.02fK", value/1000)
} else {
return fmt.Sprintf("%.02fB", value)
}
}
func PrintByteChan(w io.Writer, ch <-chan byte) error {
for b := range ch {
if _, err := w.Write([]byte{b}); err != nil {
return err
}
}
fmt.Fprintln(w)
return nil
}
2023-01-15 19:43:36 +01:00
func PrintFileHandle(fh *FileHandle) {
if err := PrintByteChan(os.Stdout, fh.Chan); err != nil {
panic(err) // TODO error handling
2023-01-15 13:59:48 +01:00
}
}
func WaitForNextTelegramSendCycle() {
now := time.Now()
_, offset := now.Zone()
offsetDuration := time.Duration(offset) * time.Second
lastCycle := now.Truncate(TelegramOrganizeMessageSendInterval).Add(-offsetDuration).Add(TelegramOrganizeMessageSendOffset)
if durationUntilLastCycle := time.Until(lastCycle); durationUntilLastCycle > 0 {
time.Sleep(durationUntilLastCycle)
} else {
nextCycle := lastCycle.Add(TelegramOrganizeMessageSendInterval)
time.Sleep(time.Until(nextCycle))
}
}