init
This commit is contained in:
171
internal/client.go
Normal file
171
internal/client.go
Normal file
@@ -0,0 +1,171 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"exporter/config"
|
||||
|
||||
"github.com/gotd/td/telegram"
|
||||
"github.com/gotd/td/telegram/auth"
|
||||
"github.com/gotd/td/telegram/downloader"
|
||||
"github.com/gotd/td/tg"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/samber/lo"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type TClient struct {
|
||||
Config *config.Config
|
||||
Client *telegram.Client
|
||||
logger *zap.Logger
|
||||
api *tg.Client
|
||||
|
||||
waitLogin chan error
|
||||
block chan struct{}
|
||||
}
|
||||
|
||||
// func (t *TClient) Close() {
|
||||
// t.block <- struct{}{}
|
||||
// }
|
||||
|
||||
func NewClient(config *config.Config) *TClient {
|
||||
c := &TClient{
|
||||
Config: config,
|
||||
Client: telegram.NewClient(config.AppID, config.AppHash, telegram.Options{
|
||||
Logger: logger,
|
||||
UpdateHandler: nil,
|
||||
SessionStorage: &telegram.FileSessionStorage{
|
||||
Path: lo.Must(filepath.Abs(config.SessionFile)),
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// func (t *TClient) Run(ctx context.Context) {
|
||||
// err := t.Client.Run(ctx, func(ctx context.Context) error {
|
||||
// flow := auth.NewFlow(Terminal{PhoneNumber: t.Config.Phone}, auth.SendCodeOptions{})
|
||||
// if err := t.Client.Auth().IfNecessary(ctx, flow); err != nil {
|
||||
// return errors.Wrap(err, "auth")
|
||||
// }
|
||||
// t.api = t.Client.API()
|
||||
|
||||
// t.waitLogin <- nil
|
||||
// <-t.block
|
||||
// return nil
|
||||
// })
|
||||
// if err != nil {
|
||||
// t.waitLogin <- err
|
||||
// }
|
||||
// }
|
||||
|
||||
// func (t *TClient) Wait() <-chan error {
|
||||
// return t.waitLogin
|
||||
// }
|
||||
|
||||
func (t *TClient) Login(ctx context.Context) error {
|
||||
flow := auth.NewFlow(Terminal{PhoneNumber: client.Config.Phone}, auth.SendCodeOptions{})
|
||||
if err := t.Client.Auth().IfNecessary(context.Background(), flow); err != nil {
|
||||
return errors.Wrap(err, "auth")
|
||||
}
|
||||
|
||||
self, err := t.Client.Self(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "call self")
|
||||
}
|
||||
|
||||
logger.Info("Login",
|
||||
zap.String("first_name", self.FirstName),
|
||||
zap.String("last_name", self.LastName),
|
||||
zap.String("username", self.Username),
|
||||
zap.Int64("id", self.ID),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChannelInfo
|
||||
func (t *TClient) ChannelInfoByAlias(ctx context.Context, channelAlias string) (*tg.Channel, error) {
|
||||
p, err := t.Client.API().ContactsResolveUsername(ctx, channelAlias)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "contacts.resolveUsername")
|
||||
}
|
||||
chats := p.GetChats()
|
||||
if len(chats) == 0 {
|
||||
return nil, errors.New("chat not found")
|
||||
}
|
||||
channel := chats[0].(*tg.Channel)
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (t *TClient) ChannelInfoByID(ctx context.Context, channelID int64) (*tg.Channel, error) {
|
||||
p, err := t.Client.API().ChannelsGetChannels(ctx, []tg.InputChannelClass{
|
||||
&tg.InputChannel{ChannelID: channelID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "contacts.resolveUsername")
|
||||
}
|
||||
chats := p.GetChats()
|
||||
if len(chats) == 0 {
|
||||
return nil, errors.New("chat not found")
|
||||
}
|
||||
channel := chats[0].(*tg.Channel)
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (t *TClient) Channel(ctx context.Context, channel *tg.Channel, offset int) error {
|
||||
inputPeer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
messages, err := t.api.MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{
|
||||
Peer: inputPeer,
|
||||
Limit: 10,
|
||||
OffsetID: offset,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "messages.getHistory")
|
||||
}
|
||||
|
||||
downloader := downloader.NewDownloader()
|
||||
lo.ForEach(messages.(*tg.MessagesChannelMessages).GetMessages(), func(item tg.MessageClass, index int) {
|
||||
msg, ok := item.(*tg.Message)
|
||||
if !ok {
|
||||
fmt.Println("ID: get failed")
|
||||
return
|
||||
}
|
||||
|
||||
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 := lo.Must(filepath.Abs(fmt.Sprintf("./photos/%d.jpg", photo.GetID())))
|
||||
storage, err := downloader.Download(t.api, location).ToPath(ctx, saveTo)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
} else {
|
||||
fmt.Println("Downloaded : ", storage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("")
|
||||
fmt.Println("------------------------------------------------------------------------------------------------------")
|
||||
fmt.Println("")
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
20
internal/client_print_channels.go
Normal file
20
internal/client_print_channels.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gotd/td/tg"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (t *TClient) PrintChannels(ctx context.Context) error {
|
||||
channels, err := t.Client.API().ChannelsGetChannels(context.Background(), []tg.InputChannelClass{
|
||||
&tg.InputChannelEmpty{},
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get channels")
|
||||
}
|
||||
_ = channels
|
||||
|
||||
return nil
|
||||
}
|
||||
46
internal/cmd_export.go
Normal file
46
internal/cmd_export.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gotd/td/tg"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
channelID int64
|
||||
channelAlias string
|
||||
)
|
||||
|
||||
func ExportCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "export",
|
||||
Short: "export channels",
|
||||
RunE: wrapE(func(ctx context.Context) error {
|
||||
if channelID == 0 && channelAlias == "" {
|
||||
return errors.New("channel id or alias is required")
|
||||
}
|
||||
|
||||
var channel *tg.Channel
|
||||
var err error
|
||||
if channelAlias != "" {
|
||||
channel, err = client.ChannelInfoByAlias(ctx, channelAlias)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
channel, err = client.ChannelInfoByID(ctx, channelID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return client.Channel(ctx, channel, 0)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.Flags().Int64Var(&channelID, "channel", 0, "channel id")
|
||||
cmd.Flags().StringVar(&channelAlias, "alias", "", "channel alias")
|
||||
|
||||
return cmd
|
||||
}
|
||||
15
internal/cmd_login.go
Normal file
15
internal/cmd_login.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func LoginCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "login account",
|
||||
RunE: wrapE(client.Login),
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
46
internal/common.go
Normal file
46
internal/common.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"exporter/config"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
lj "gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
client *TClient
|
||||
logger *zap.Logger
|
||||
)
|
||||
|
||||
func InitClient(cfg *config.Config) error {
|
||||
logWriter := zapcore.AddSync(&lj.Logger{
|
||||
Filename: cfg.LogFile,
|
||||
MaxBackups: 3,
|
||||
MaxSize: 1, // megabytes
|
||||
MaxAge: 7, // days
|
||||
})
|
||||
logCore := zapcore.NewCore(
|
||||
zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
|
||||
logWriter,
|
||||
zap.DebugLevel,
|
||||
)
|
||||
logger = zap.New(logCore)
|
||||
|
||||
client = NewClient(cfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
_ = logger.Sync()
|
||||
return nil
|
||||
}
|
||||
|
||||
func wrapE(f func(context.Context) error) func(cmd *cobra.Command, args []string) error {
|
||||
return func(cmd *cobra.Command, args []string) error {
|
||||
return client.Client.Run(context.Background(), f)
|
||||
}
|
||||
}
|
||||
63
internal/terminal.go
Normal file
63
internal/terminal.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/gotd/td/telegram/auth"
|
||||
"github.com/gotd/td/tg"
|
||||
)
|
||||
|
||||
// Terminal implements auth.UserAuthenticator prompting the terminal for
|
||||
// input.
|
||||
//
|
||||
// This is only example implementation, you should not use it in your code.
|
||||
// Copy it and modify to fit your needs.
|
||||
type Terminal struct {
|
||||
PhoneNumber string // optional, will be prompted if empty
|
||||
}
|
||||
|
||||
func (Terminal) SignUp(ctx context.Context) (auth.UserInfo, error) {
|
||||
return auth.UserInfo{}, errors.New("signing up not implemented in Terminal")
|
||||
}
|
||||
|
||||
func (Terminal) AcceptTermsOfService(ctx context.Context, tos tg.HelpTermsOfService) error {
|
||||
return &auth.SignUpRequired{TermsOfService: tos}
|
||||
}
|
||||
|
||||
func (Terminal) Code(ctx context.Context, sentCode *tg.AuthSentCode) (string, error) {
|
||||
fmt.Print("Enter code: ")
|
||||
code, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(code), nil
|
||||
}
|
||||
|
||||
func (a Terminal) Phone(_ context.Context) (string, error) {
|
||||
if a.PhoneNumber != "" {
|
||||
return a.PhoneNumber, nil
|
||||
}
|
||||
fmt.Print("Enter phone in international format (e.g. +1234567890): ")
|
||||
phone, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(phone), nil
|
||||
}
|
||||
|
||||
func (Terminal) Password(_ context.Context) (string, error) {
|
||||
fmt.Print("Enter 2FA password: ")
|
||||
bytePwd, err := term.ReadPassword(int(syscall.Stdin))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(bytePwd)), nil
|
||||
}
|
||||
Reference in New Issue
Block a user