93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
package internal
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gotd/td/telegram/downloader"
|
|
"github.com/gotd/td/tg"
|
|
"github.com/pkg/errors"
|
|
"github.com/samber/lo"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
func (t *TClient) Channel(ctx context.Context, channel *tg.Channel, cfg *DBChannel, modeHistory bool) error {
|
|
inputPeer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
|
|
|
request := &tg.MessagesGetHistoryRequest{
|
|
Peer: inputPeer,
|
|
Limit: 10,
|
|
}
|
|
|
|
if modeHistory { // 提供此ID供遍历历史消息
|
|
request.OffsetID = cfg.Offset
|
|
} else {
|
|
request.MinID = cfg.MinID // 提供此ID供新增加的消息
|
|
}
|
|
|
|
messages, err := t.Client.API().MessagesGetHistory(ctx, request)
|
|
if err != nil {
|
|
return errors.Wrap(err, "messages.getHistory")
|
|
}
|
|
if len(messages.(*tg.MessagesChannelMessages).GetMessages()) == 0 {
|
|
t.logger.Info("no new message")
|
|
return errors.New("no new message")
|
|
}
|
|
|
|
downloader := downloader.NewDownloader()
|
|
lo.ForEach(messages.(*tg.MessagesChannelMessages).GetMessages(), func(item tg.MessageClass, index int) {
|
|
defer func() {
|
|
t.logger.Info("update config", zap.Int("offset", cfg.Offset))
|
|
if err := cfg.Update(ctx, item.GetID()); err != nil {
|
|
t.logger.Error("update config failed", zap.Error(err))
|
|
}
|
|
}()
|
|
|
|
switch item.(type) {
|
|
case *tg.MessageEmpty:
|
|
return
|
|
case *tg.MessageService:
|
|
return
|
|
}
|
|
|
|
msg, ok := item.(*tg.Message)
|
|
if !ok {
|
|
t.logger.Error("convert msg to *tg.Message failed")
|
|
return
|
|
}
|
|
|
|
channelMessage := NewChannelMessage(msg.ID, msg.GetDate())
|
|
defer cfg.SaveMessage(ctx, channelMessage)
|
|
|
|
channelMessage.WithMessage(msg.GetMessage())
|
|
|
|
if mediaClass, ok := msg.GetMedia(); ok {
|
|
if photoClass, ok := mediaClass.(*tg.MessageMediaPhoto).GetPhoto(); ok {
|
|
photo := photoClass.(*tg.Photo)
|
|
|
|
thumbSize := ""
|
|
if len(photo.Sizes) > 1 {
|
|
thumbSize = photo.Sizes[len(photo.Sizes)-1].GetType()
|
|
}
|
|
|
|
location := &tg.InputPhotoFileLocation{
|
|
ID: photo.GetID(),
|
|
AccessHash: photo.GetAccessHash(),
|
|
FileReference: photo.GetFileReference(),
|
|
ThumbSize: thumbSize,
|
|
}
|
|
|
|
saveTo := cfg.Asset(photo.GetID(), "jpg")
|
|
_, err := downloader.Download(t.Client.API(), location).ToPath(ctx, saveTo)
|
|
if err != nil {
|
|
t.logger.Error("download failed", zap.Error(err))
|
|
return
|
|
}
|
|
channelMessage.WithPhoto(photo.GetID(), "jpg")
|
|
t.logger.Info("download photo success", zap.String("location", saveTo))
|
|
}
|
|
}
|
|
})
|
|
|
|
return nil
|
|
}
|