cmdlib

package
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 4, 2025 License: MIT Imports: 19 Imported by: 4

Documentation

Overview

Package cmdlib contains utlities mostly for bot

Index

Constants

View Source
const (
	SilentVerbosity = 0
	ErrVerbosity    = 1
	InfVerbosity    = 2
	DbgVerbosity    = 3
)

Verbosity constants

Variables

View Source
var AllModels = QueryModelList{All: true}

AllModels should be used to query all statuses

View Source
var ErrFullQueue = errors.New("queue is full")

ErrFullQueue emerges whenever we unable to add a request because the queue is full

View Source
var ModelIDRegexp = regexp.MustCompile(`^[a-z0-9\-_@]+$`)

ModelIDRegexp is a regular expression to check model IDs

View Source
var Version = "(devel)"

Version is the version of the current code state

Functions

func CanonicalModelID

func CanonicalModelID(name string) string

CanonicalModelID preprocesses model ID string to canonical form

func CheckEndpoints

func CheckEndpoints(c endpointChecker, endpoints []string, dbg bool) (map[string]StatusKind, map[string]string, error)

CheckEndpoints performs queries to all available endpoints

func CheckErr

func CheckErr(err error)

CheckErr panics on an error

func CloseBody

func CloseBody(body io.Closer)

CloseBody closes request body

func HashDiffAll

func HashDiffAll(before, after map[string]bool) []string

HashDiffAll returns symmetric difference between before and after

func HashDiffNewRemoved

func HashDiffNewRemoved(before, after map[string]bool) (newElements []string, removedElements []string)

HashDiffNewRemoved returns new and removed elements

func Ldbg

func Ldbg(format string, v ...interface{})

Ldbg logs a debug message

func Lerr

func Lerr(format string, v ...interface{})

Lerr logs an error

func Linf

func Linf(format string, v ...interface{})

Linf logs an info message

func LoadAllAds

func LoadAllAds(files map[string][]string) (trMap map[string]map[string]*Translation, tpl map[string]*template.Template)

LoadAllAds loads all ads

func LoadAllTranslations

func LoadAllTranslations(files map[string][]string) (trMap map[string]*Translations, tpl map[string]*template.Template)

LoadAllTranslations loads all translations

func LoadEndpointTranslations

func LoadEndpointTranslations(files []string) (*Translations, AllTranslations)

LoadEndpointTranslations loads translations for a specific endpoint

func NoRedirect

func NoRedirect(_ *http.Request, _ []*http.Request) error

NoRedirect tells HTTP client not to redirect

func OnlineQuery

func OnlineQuery(
	usersOnlineEndpoint string,
	client *Client,
	headers [][2]string,
) (
	*http.Response,
	*bytes.Buffer,
	error,
)

OnlineQuery creates and performs online request

func OnlineRequest

func OnlineRequest(
	req *http.Request,
	client *Client,
) (
	*http.Response,
	*bytes.Buffer,
	error,
)

OnlineRequest performs online request

Types

type AllTranslations

type AllTranslations map[string]*Translation

AllTranslations represents a collection of translated texts in all supported languages

func LoadAds

func LoadAds(files []string) AllTranslations

LoadAds loads ads for a specific endpoint

type CheckMode

type CheckMode int

CheckMode represents check mode

const (
	CheckOnline CheckMode = iota
	CheckStatuses
)

Model statuses

type Checker

type Checker interface {
	CheckStatusSingle(modelID string) StatusKind
	CheckStatusesMany(specific QueryModelList, checkMode CheckMode) (statuses map[string]StatusKind, images map[string]string, err error)
	Start()
	Init(checker Checker, config CheckerConfig)
	Updater() Updater
	PushStatusRequest(statusRequest StatusRequest) error
	CreateUpdater() Updater
}

Checker is the interface for a checker for specific site

type CheckerCommon

type CheckerCommon struct {
	CheckerConfig
	ClientsLoop clientsLoop
	// contains filtered or unexported fields
}

CheckerCommon contains common fields for all the checkers

func (*CheckerCommon) CreateFullUpdater

func (c *CheckerCommon) CreateFullUpdater(checker Checker) Updater

CreateFullUpdater creates an updater quering for all streams

func (*CheckerCommon) CreateSelectiveUpdater

func (c *CheckerCommon) CreateSelectiveUpdater(checker Checker) Updater

CreateSelectiveUpdater creates an updater for selected streams

func (*CheckerCommon) DoGetRequest

func (c *CheckerCommon) DoGetRequest(url string) (net.Addr, *http.Response)

DoGetRequest performs a GET request respecting the configuration

func (*CheckerCommon) Init

func (c *CheckerCommon) Init(checker Checker, config CheckerConfig)

Init initializes checker common fields

func (*CheckerCommon) PushStatusRequest

func (c *CheckerCommon) PushStatusRequest(statusRequest StatusRequest) error

PushStatusRequest adds a status request to the queue

func (*CheckerCommon) QueryStatusCode

func (c *CheckerCommon) QueryStatusCode(url string) int

QueryStatusCode performs a GET request and returns only the status code

func (*CheckerCommon) StartFullCheckerDaemon

func (c *CheckerCommon) StartFullCheckerDaemon(checker Checker)

StartFullCheckerDaemon starts a checker for all streams

func (*CheckerCommon) StartSelectiveCheckerDaemon

func (c *CheckerCommon) StartSelectiveCheckerDaemon(checker Checker)

StartSelectiveCheckerDaemon starts a checker for selected streams

func (*CheckerCommon) Updater

func (c *CheckerCommon) Updater() Updater

Updater returns default updater

type CheckerConfig

type CheckerConfig struct {
	UsersOnlineEndpoints []string
	Clients              []*Client
	Headers              [][2]string
	Dbg                  bool
	SpecificConfig       map[string]string
	QueueSize            int
	SiteOnlineModels     map[string]bool
	Subscriptions        map[string]StatusKind
	IntervalMs           int
}

CheckerConfig represents checker config

type Client

type Client struct {
	// Client is HTTP client
	Client *http.Client
	// Addr is source IP address
	Addr net.Addr
}

Client wraps HTTP client and source IP address

func HTTPClientWithTimeoutAndAddress

func HTTPClientWithTimeoutAndAddress(timeoutSeconds int, address string, cookies bool) *Client

HTTPClientWithTimeoutAndAddress returns HTTP client bound to specific IP address

type ParseKind

type ParseKind int

ParseKind specifies Telegram message parsing method

const (
	// ParseRaw parses Telegram message as a raw text
	ParseRaw ParseKind = iota
	// ParseHTML parses Telegram message as HTML
	ParseHTML
	// ParseMarkdown parses Telegram message as Markdown
	ParseMarkdown
)

func (ParseKind) MarshalYAML

func (r ParseKind) MarshalYAML() ([]byte, error)

MarshalYAML is generated so ParseKind satisfies yaml.Marshaler.

func (ParseKind) String

func (r ParseKind) String() string

func (*ParseKind) UnmarshalYAML

func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error

UnmarshalYAML is generated so ParseKind satisfies yaml.Unmarshaler.

type QueryModelList

type QueryModelList struct {
	All  bool
	List []string
}

QueryModelList represents a model list to query

func NewQueryModelList

func NewQueryModelList(list []string) QueryModelList

NewQueryModelList returns a query list for specific models

type StatusKind

type StatusKind int

StatusKind represents a status of a model

const (
	StatusUnknown  StatusKind = 0
	StatusOffline  StatusKind = 1
	StatusOnline   StatusKind = 2
	StatusNotFound StatusKind = 4
	StatusDenied   StatusKind = 8
)

Model statuses

func (StatusKind) String

func (s StatusKind) String() string

type StatusRequest

type StatusRequest struct {
	SpecialModels map[string]bool
	Specific      map[string]bool
	Callback      func(StatusResults)
	CheckMode     CheckMode
}

StatusRequest represents a request of model status

type StatusResults

type StatusResults struct {
	Data   *StatusResultsData
	Errors int
}

StatusResults contains results from online checking algorithm

type StatusResultsData

type StatusResultsData struct {
	Statuses map[string]StatusKind
	Images   map[string]string
	Elapsed  time.Duration
}

StatusResultsData contains data from online checking algorithm

type StatusUpdate

type StatusUpdate struct {
	ModelID string
	Status  StatusKind
}

StatusUpdate represents an update of model status

type StatusUpdateRequest

type StatusUpdateRequest struct {
	SpecialModels map[string]bool
	Subscriptions map[string]StatusKind
	Specific      map[string]bool
	Callback      func(StatusUpdateResults)
}

StatusUpdateRequest represents a request of models updates

type StatusUpdateResults

type StatusUpdateResults struct {
	Data   *StatusUpdateResultsData
	Errors int
}

StatusUpdateResults contains results from updates checking algorithm

type StatusUpdateResultsData

type StatusUpdateResultsData struct {
	Updates []StatusUpdate
	Images  map[string]string
	Elapsed time.Duration
}

StatusUpdateResultsData contains data from updates checking algorithm

type StringSetFlag

type StringSetFlag map[string]bool

StringSetFlag is a flag representing a set of strings

func (*StringSetFlag) Set

func (s *StringSetFlag) Set(value string) error

Set implements flag.Value interface

func (*StringSetFlag) String

func (s *StringSetFlag) String() string

String implements flag.Value interface

type Translation

type Translation struct {
	Key            string    `yaml:"-"`
	Str            string    `yaml:"str"`
	Parse          ParseKind `yaml:"parse"`
	DisablePreview bool      `yaml:"disable_preview"`
	Image          string    `yaml:"image"`
	ImageBytes     []byte    `yaml:"-"`
}

Translation represents a translated text for a Telegram message

type Translations

type Translations struct {
	Start                       *Translation `yaml:"start"`
	Help                        *Translation `yaml:"help"`
	Online                      *Translation `yaml:"online"`
	List                        *Translation `yaml:"list"`
	Offline                     *Translation `yaml:"offline"`
	Denied                      *Translation `yaml:"denied"`
	SyntaxAdd                   *Translation `yaml:"syntax_add"`
	SyntaxRemove                *Translation `yaml:"syntax_remove"`
	SyntaxFeedback              *Translation `yaml:"syntax_feedback"`
	InvalidSymbols              *Translation `yaml:"invalid_symbols"`
	AlreadyAdded                *Translation `yaml:"already_added"`
	AddError                    *Translation `yaml:"add_error"`
	ModelAdded                  *Translation `yaml:"model_added"`
	ModelNotInList              *Translation `yaml:"model_not_in_list"`
	ModelRemoved                *Translation `yaml:"model_removed"`
	CheckingModel               *Translation `yaml:"checking_model"`
	Feedback                    *Translation `yaml:"feedback"`
	Social                      *Translation `yaml:"social"`
	UnknownCommand              *Translation `yaml:"unknown_command"`
	InvalidCommand              *Translation `yaml:"invalid_command"`
	Languages                   *Translation `yaml:"languages"`
	Version                     *Translation `yaml:"version"`
	ProfileRemoved              *Translation `yaml:"profile_removed"`
	NoOnlineModels              *Translation `yaml:"no_online_models"`
	RemoveAll                   *Translation `yaml:"remove_all"`
	AllModelsRemoved            *Translation `yaml:"all_models_removed"`
	ReferralLink                *Translation `yaml:"referral_link"`
	InvalidReferralLink         *Translation `yaml:"invalid_referral_link"`
	FollowerExists              *Translation `yaml:"follower_exists"`
	ReferralApplied             *Translation `yaml:"referral_applied"`
	OwnReferralLinkHit          *Translation `yaml:"own_referral_link_hit"`
	SubscriptionUsage           *Translation `yaml:"subscription_usage"`
	SubscriptionUsageAd         *Translation `yaml:"subscription_usage_ad"`
	NotEnoughSubscriptions      *Translation `yaml:"not_enough_subscriptions"`
	Week                        *Translation `yaml:"week"`
	ZeroSubscriptions           *Translation `yaml:"zero_subscriptions"`
	FAQ                         *Translation `yaml:"faq"`
	RawCommands                 *Translation `yaml:"raw_commands"`
	Settings                    *Translation `yaml:"settings"`
	OK                          *Translation `yaml:"ok"`
	TooManySubscriptionsForPics *Translation `yaml:"too_many_subscriptions_for_pics"`
	WeAreUp                     *Translation `yaml:"we_are_up"`
}

Translations represents a collection of translated texts for Telegram messages

func (*Translations) ToMap

func (x *Translations) ToMap() map[string]*Translation

ToMap returns translations as a map

type Updater

type Updater interface {
	PushUpdateRequest(updateRequest StatusUpdateRequest) error
}

Updater implements updater adapter

type VerbosityKind

type VerbosityKind int

VerbosityKind represents logging verbosity

var Verbosity VerbosityKind = DbgVerbosity

Verbosity is the current logging verbosity

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL