handler

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultCacheDuration = 10 * time.Minute

DefaultCacheDuration is how long a Store entry lives when the caller does not ask for a specific TTL.

View Source
const SettingsCommand = "/settings"

SettingsCommand opens the administrator settings screen.

The name lives here rather than in pkg/constant because the command was added together with its handler; it can move to the constants package once that file is next touched, and command_registry.go already references this constant.

Variables

View Source
var ErrDomainNotAllowed = errors.New("URL domain is not allowed")

ErrDomainNotAllowed reports a notice URL outside the configured server. Both callers turn it into a user-visible rejection, so the text is part of the contract rather than a diagnostic.

Functions

func DebugHandler added in v1.4.2

func DebugHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func HelpText added in v1.4.9

func HelpText(appEnabled bool) string

HelpText generates the /start help message from the command registry. When the Mini App is available the retired commands are omitted and a closing line points at the app instead.

func MeHandler

func MeHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func TelegramCommands added in v1.4.9

func TelegramCommands(appEnabled bool) []models.BotCommand

TelegramCommands returns the command list for SetMyCommands. Admin-only commands are still exposed in the Telegram command menu (the handlers enforce the permission), matching the previous behaviour.

appEnabled removes the commands retired in favour of the Mini App: advertising a command that only answers "use the app" would make the menu misleading.

Types

type AttachmentRetrier added in v1.4.10

type AttachmentRetrier struct {
	// contains filtered or unexported fields
}

AttachmentRetrier re-sends the PDF attachments that could not be delivered while a notice's text message was pushed.

A notice whose table is too complex to flatten is announced as a placeholder plus an attachment; when the conversion or the upload fails the text has already reached the user, so the claim is not rolled back. The pending row is retried here with a backoff instead, which turns a Gotenberg outage into a delayed attachment instead of a silently missing one.

func NewAttachmentRetrier added in v1.4.10

func NewAttachmentRetrier(ctx *BotContext) *AttachmentRetrier

NewAttachmentRetrier wires the retrier to the bot context. A missing bot or Gotenberg client leaves the corresponding collaborator nil and disables the sweeps, which keeps a conversion-less deployment (or a partial test context) from panicking.

func (*AttachmentRetrier) RunOnce added in v1.4.10

func (r *AttachmentRetrier) RunOnce(ctx context.Context)

RunOnce sends every attachment that is due, oldest deadline first.

func (*AttachmentRetrier) Start added in v1.4.10

func (r *AttachmentRetrier) Start(ctx context.Context)

Start sweeps until ctx is cancelled. The first sweep runs immediately so a restart after an outage re-sends the backlog without waiting a full interval.

type BotContext added in v1.4.1

type BotContext struct {
	Bot       *bot.Bot
	Store     *Store[model.RequestInfo]
	Logger    *utils.Logger
	Config    *config.ServiceConfig
	Gotenberg *GotenbergClient
	// contains filtered or unexported fields
}

func NewBotContext added in v1.4.1

func NewBotContext() (*BotContext, error)

func (*BotContext) IsAdmin added in v1.5.0

func (ctx *BotContext) IsAdmin(userID int64) bool

IsAdmin reports whether userID is an enabled administrator. Rights are independent of the access mode: an open bot does not promote every account.

func (*BotContext) RecentDenied added in v1.5.0

func (ctx *BotContext) RecentDenied() []DeniedEntry

RecentDenied returns the most recent denied access attempts, oldest first. The slice is a copy: callers may keep it while new attempts are recorded.

func (*BotContext) RecentDeniedEntries added in v1.5.0

func (ctx *BotContext) RecentDeniedEntries() []DeniedEntry

RecentDeniedEntries is the accessor the administrator status provider uses. It is an alias of RecentDenied kept under the name the P5 API is expected to call, so the server package does not need a second implementation.

func (*BotContext) Start added in v1.4.1

func (ctx *BotContext) Start() error

Start binds the HTTP listener, starts Telegram delivery in the mode the configuration selects, and launches the background workers. The only error returned is a listener that could not bind: everything after that is retried or logged, because a bot whose Telegram API is temporarily unreachable still serves the Gotenberg callback and the scheduler.

func (*BotContext) StartConversion added in v1.5.0

func (c *BotContext) StartConversion(ctx context.Context, chatID int64, noticeURL string,
	kind model.FileType, replyMessageID int,
) (string, error)

StartConversion submits one asynchronous conversion and returns the request id the webhook will use to claim the result.

It runs the same steps for the chat commands and the Mini App: enforce the notice host allow-list, derive the output file name, post the "please wait" placeholder, submit the job to Gotenberg, and record the request. The file itself still arrives out of band on POST /pdf/{id}; only the submission is synchronous, because the caller must learn whether the job was accepted (and the placeholder has to be swapped for a failure notice when it was not).

func (*BotContext) Stop added in v1.4.1

func (ctx *BotContext) Stop()

Stop shuts the process down. The webhook registration is deliberately kept: Telegram retains undelivered updates for up to 24 hours and resumes delivery to the same URL, so deleting it would only add a registration gap.

func (*BotContext) SystemStatus added in v1.5.0

func (ctx *BotContext) SystemStatus(statusCtx context.Context) server.AdminStatus

SystemStatus implements server.AdminStatusProvider: it projects the local denial history and the Telegram webhook registration into the shape the administrator status screen renders.

The webhook is only inspected in webhook mode. In polling mode there is no registration to report, and asking Telegram anyway could surface a stale one left by an earlier deployment.

func (*BotContext) WebhookSnapshot added in v1.5.0

func (ctx *BotContext) WebhookSnapshot(parent context.Context) (url, lastError string, pending int, ok bool)

WebhookSnapshot returns the current Telegram webhook registration. It is a best-effort view for the administrator status page: the call is bounded and a failure is reported as ok=false instead of an error the status page cannot render.

type ClaimHandle added in v1.4.9

type ClaimHandle struct {
	// Key 是进程内锁(KeyedLock)的键;为空表示调用方已自行管理并发
	//(例如 projects 的预筛锁已覆盖整个渲染+发送生命周期)。
	Key string
	// Claim 执行 DB 原子抢占(InsertIfAbsent),返回是否抢到。
	// 只有真正抢到的调用才允许发送。
	Claim func() (bool, error)
	// Send 执行发送;返回 error 表示发送失败,会触发 Rollback 回滚。
	Send func() error
	// Rollback 在发送失败时回滚抢占(Remove),供下一轮重试。
	Rollback func() error
}

ClaimHandle 定义一条可抢占推送的最小单元。

处理骨架固定为:内存锁 → DB 抢占 → 发送 → 失败回滚。 管线只关心骨架,具体业务(唯一键组成、发送内容、回滚语义)由回调提供。

type CommandSpec added in v1.4.9

type CommandSpec struct {
	Command     string
	Description string
	// Usage is the argument placeholder shown in help, e.g. "<k1,k2>".
	// Leave empty for commands without arguments.
	Usage     string
	AdminOnly bool
}

CommandSpec describes a bot command. It is the single source of truth for both SetMyCommands registration and the /start help text, so adding a command requires touching exactly one place.

type CommandsHandler

type CommandsHandler struct {
	// contains filtered or unexported fields
}

func NewCommandsHandler

func NewCommandsHandler(ctx *BotContext) *CommandsHandler

func (*CommandsHandler) AddAlarmKeywordHandler added in v1.2.0

func (c *CommandsHandler) AddAlarmKeywordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) AddKeywordHandler

func (c *CommandsHandler) AddKeywordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) AlarmRecordHandler added in v1.4.2

func (c *CommandsHandler) AlarmRecordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) ConvertURLToIMGHandler added in v1.4.1

func (c *CommandsHandler) ConvertURLToIMGHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) ConvertURLToPDFHandler added in v1.3.0

func (c *CommandsHandler) ConvertURLToPDFHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) DeleteKeywordHandler

func (c *CommandsHandler) DeleteKeywordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) EditKeywordHandler added in v1.4.0

func (c *CommandsHandler) EditKeywordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) HandleCallbackQuery added in v1.3.0

func (c *CommandsHandler) HandleCallbackQuery(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) ListTodayHandler added in v1.4.7

func (c *CommandsHandler) ListTodayHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) SearchAlarmRecordHandler added in v1.4.2

func (c *CommandsHandler) SearchAlarmRecordHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) SearchHistoryHandler added in v1.3.0

func (c *CommandsHandler) SearchHistoryHandler(ctx context.Context, b *bot.Bot, update *models.Update)

func (*CommandsHandler) StaticHandler added in v1.4.0

func (c *CommandsHandler) StaticHandler(ctx context.Context, b *bot.Bot, update *models.Update)

StaticHandler answers /statistics with the counters and an inline keyboard.

func (*CommandsHandler) StatisticsCallback added in v1.4.10

func (c *CommandsHandler) StatisticsCallback(ctx context.Context, b *bot.Bot, update *models.Update)

StatisticsCallback serves the inline keyboard of /statistics. The message is edited in place, so a click never adds a message to the chat.

type Crawler added in v1.4.1

type Crawler struct {
	// contains filtered or unexported fields
}

func NewCrawler added in v1.4.1

func NewCrawler(ctx *BotContext) *Crawler

func (*Crawler) Alarms added in v1.4.1

func (c *Crawler) Alarms(keywords []string, userId int64) []*model.Alarm

func (*Crawler) Projects added in v1.4.1

func (c *Crawler) Projects() []*Project

type DeniedEntry added in v1.5.0

type DeniedEntry struct {
	UserID   int64
	Username string
	Name     string
	At       time.Time
}

DeniedEntry is one rejected access attempt, kept in memory for the administrator status view. It deliberately carries no message text: the bot records who tried, not what they wrote.

type GotenbergClient added in v1.4.1

type GotenbergClient struct {
	// contains filtered or unexported fields
}

func NewGotenbergClient added in v1.4.1

func NewGotenbergClient(host, hookURL, token string) (*GotenbergClient, error)

func (*GotenbergClient) FetchPDF added in v1.4.10

func (g *GotenbergClient) FetchPDF(ctx context.Context, u string) ([]byte, error)

FetchPDF converts a URL to PDF and returns the file itself. Unlike URLToPDF it does not use a webhook, so it suits the push pipeline where the caller wants the bytes in hand before sending them as an attachment.

func (*GotenbergClient) HtmlToImage added in v1.4.1

func (g *GotenbergClient) HtmlToImage(ctx context.Context, content string) (string, error)

HtmlToImage asks Gotenberg to screenshot inline HTML and deliver it to the webhook.

func (*GotenbergClient) URLToImage added in v1.4.1

func (g *GotenbergClient) URLToImage(ctx context.Context, u string) (string, error)

URLToImage asks Gotenberg to screenshot a URL and deliver it to the webhook.

func (*GotenbergClient) URLToPDF added in v1.4.1

func (g *GotenbergClient) URLToPDF(ctx context.Context, u string) (string, error)

URLToPDF asks Gotenberg to convert a URL and deliver the PDF to the webhook.

type InfoProcessor added in v1.4.1

type InfoProcessor struct {
	// contains filtered or unexported fields
}

func NewInfoProcessor added in v1.4.1

func NewInfoProcessor(ctx *BotContext) (*InfoProcessor, error)

func (*InfoProcessor) Get added in v1.4.1

func (r *InfoProcessor) Get(userId int64)

func (*InfoProcessor) Handler added in v1.4.2

func (r *InfoProcessor) Handler(i any)

func (*InfoProcessor) Process added in v1.4.1

func (r *InfoProcessor) Process()

func (*InfoProcessor) Release added in v1.4.1

func (r *InfoProcessor) Release()

func (*InfoProcessor) ToMessage added in v1.4.2

func (r *InfoProcessor) ToMessage(project *Project) ([]string, int)

ToMessage renders one project into Telegram-sized message chunks. Content is already sanitised for Telegram's HTML parse mode by the crawler.

type KeyedLock added in v1.4.9

type KeyedLock struct {
	// contains filtered or unexported fields
}

KeyedLock is a keyed in-process lock. Callers mark a resource (a project URL, an alarm credit code, ...) as being handled with TryLock, so a concurrent invocation in the same process skips it instead of duplicating the work. Unlock releases the key once the work is done.

KeyedLock is process-local by design. For cross-instance safety (multiple bot processes sharing the same DB), pair it with a DB-backed claim such as dal.InsertIfAbsent, where the table's unique constraint is the authority.

func NewKeyedLock added in v1.4.9

func NewKeyedLock() *KeyedLock

NewKeyedLock returns an empty KeyedLock.

func (*KeyedLock) TryLock added in v1.4.9

func (l *KeyedLock) TryLock(key string) bool

TryLock marks key as held and reports whether the caller acquired it. A second concurrent TryLock for the same key returns false.

func (*KeyedLock) Unlock added in v1.4.9

func (l *KeyedLock) Unlock(key string)

Unlock releases a previously acquired key. It is safe to call for a key that is not held (no-op).

type ManagerHandler

type ManagerHandler struct {
	// contains filtered or unexported fields
}

func NewManagerHandler

func NewManagerHandler(ctx *BotContext) *ManagerHandler

func (*ManagerHandler) Clean added in v1.1.0

func (h *ManagerHandler) Clean(ctx context.Context, b *bot.Bot, update *models.Update)

func (*ManagerHandler) Retry

func (h *ManagerHandler) Retry(ctx context.Context, b *bot.Bot, update *models.Update)

type ProcessData added in v1.4.1

type ProcessData struct {
	UserId       int64
	ProjectRules []*rule.ComplexRule
	AlarmKeyword []string
	Projects     []*Project
	Alarms       []*model.Alarm
	IsForced     bool
}

ProcessData holds the data for processing

type Project added in v1.4.1

type Project struct {
	NoticeTime     string `json:"noticeTime,omitempty"`
	OpenTenderCode string `json:"openTenderCode,omitempty"`
	Title          string `json:"title,omitempty"`
	ShortTitle     string `json:"-"`
	Content        string `json:"content,omitempty"`
	Pageurl        string `json:"pageurl,omitempty"`
	Keyword        string `json:"keyword,omitempty"`
	HasTenderCode  bool   `json:"-"`
	// HasComplexTable marks a notice whose table cannot be flattened into the
	// message body; the pipeline attaches the original page as a PDF instead.
	HasComplexTable bool `json:"-"`
	// contains filtered or unexported fields
}

func (*Project) SplitMessage added in v1.4.2

func (p *Project) SplitMessage() ([]string, int)

SplitMessage renders the project and splits it into Telegram-sized chunks.

func (*Project) ToMessage added in v1.4.2

func (p *Project) ToMessage() string

type Projects added in v1.4.1

type Projects struct {
	Projects []*Project
	// contains filtered or unexported fields
}

func NewProjects added in v1.4.1

func NewProjects(ctx *BotContext, projects []*Project, rules []*rule.ComplexRule) *Projects

func (*Projects) Filter added in v1.4.2

func (r *Projects) Filter() []*Project

Filter returns the projects matched by at least one rule.

Every matched project is a shallow copy carrying its own Keyword: the caller's slice is shared by every user processed in one run (InfoProcessor fans users out to the ants pool), so writing the match result back into the original structs would both race and leak one user's keywords into another user's message. The copies also own Content/HasTenderCode, which the render step rewrites, and the matched keyword ids, which the pipeline counts only after the notice has actually been delivered.

type PushPipeline added in v1.4.9

type PushPipeline struct {
	// contains filtered or unexported fields
}

PushPipeline 串行处理一批可抢占推送。同一进程内相同 Key 的 handle 只会 被处理一次;跨实例的互斥由 Claim 背后的 DB 唯一约束保证。

func NewPushPipeline added in v1.4.9

func NewPushPipeline() *PushPipeline

NewPushPipeline 返回一个空的 PushPipeline。

func (*PushPipeline) Run added in v1.4.9

func (p *PushPipeline) Run(handles []ClaimHandle)

Run 依次处理 handles。单个 handle 的失败不影响其余 handle。

type Store added in v1.4.1

type Store[T any] struct {
	// contains filtered or unexported fields
}

Store is a small TTL cache keyed by string.

Entries are evicted by a timer armed in Set, so a key that is written but never read again (a webhook that never arrives) cannot leak. All access is serialised by a single mutex: Get may delete an expired entry, so a read lock would be wrong.

func NewStore added in v1.4.1

func NewStore[T any]() *Store[T]

NewStore returns an empty Store.

func (*Store[T]) Delete added in v1.4.1

func (s *Store[T]) Delete(key string)

Delete removes key.

func (*Store[T]) Get added in v1.4.1

func (s *Store[T]) Get(key string) (T, bool)

Get returns the value stored under key and reports whether it is still live.

func (*Store[T]) Set added in v1.4.1

func (s *Store[T]) Set(key string, value T, duration time.Duration)

Set stores value under key for the given duration.

Jump to

Keyboard shortcuts

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