Skip to content

Commit

Permalink
fix: FILE_REFERENCE_EXPIRED in ctx.DownloadMedia (#62)
Browse files Browse the repository at this point in the history
* feat: add thumbSize for photo media download

* docs: fix readme sqlite session

* feat: add GetMediaFileNameWithId and GetMediaFileName for getting media's filenames

* feat: add Downloader example

* fix: fix nil pointer diref panic

* feat: add reply for downloaded file

* fix: set correct thumbSizes

* ref: rollback go mod changes

* ref: run go mod tidy

* fix: add fillUserIdFromMessage for UpdateNewChannelMessage

* ref: remove image

* ref: move helpers to functions/mediaHelpers

* ref: get creds from env

* ref: remove unnecessary changes

* fix: fix nil pointer deref in EffectiveUser

* ref: remove redundant fix

---------

Co-authored-by: pibragimov <pibragimov@whoosh.bike>
  • Loading branch information
TeaDove and pibragimov authored Apr 5, 2024
1 parent eb70628 commit e1a2d1f
Show file tree
Hide file tree
Showing 9 changed files with 261 additions and 88 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (

"github.com/celestix/gotgproto"
"github.com/celestix/gotgproto/sessionMaker"
"github.com/glebarez/sqlite"
)

func main() {
Expand All @@ -43,7 +44,7 @@ func main() {
clientType,
// Optional parameters of client
&gotgproto.ClientOpts{
Session: sessionMaker.SqliteSession("echobot"),
Session: sessionMaker.SqlSession(sqlite.Open("echobot")),
},
)
if err != nil {
Expand Down
85 changes: 85 additions & 0 deletions examples/downloader/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package main

import (
"fmt"
"github.com/celestix/gotgproto"
"github.com/celestix/gotgproto/dispatcher/handlers"
"github.com/celestix/gotgproto/dispatcher/handlers/filters"
"github.com/celestix/gotgproto/ext"
"github.com/celestix/gotgproto/functions"
"github.com/celestix/gotgproto/sessionMaker"
"github.com/go-faster/errors"
"log"
"os"
"strconv"
)

func main() {
// Type of client to login to, can be of 2 types:
// 1.) Bot (Fill BotToken in this case)
// 2.) User (Fill Phone in this case)
clientType := gotgproto.ClientType{
BotToken: os.Getenv("TG_BOT_TOKEN"),
}

appIdEnv := os.Getenv("TG_APP_ID")
appId, err := strconv.Atoi(appIdEnv)
if err != nil {
log.Fatalln("failed to convert app id to int:", err)
}

client, err := gotgproto.NewClient(
// Get AppID from https://my.telegram.org/apps
appId,
// Get ApiHash from https://my.telegram.org/apps
os.Getenv("TG_API_HASH"),
// ClientType, as we defined above
clientType,
// Optional parameters of client
&gotgproto.ClientOpts{
InMemory: true,
Session: sessionMaker.SimpleSession(),
},
)
if err != nil {
log.Fatalln("failed to start client:", err)
}

clientDispatcher := client.Dispatcher

// This Message Handler will download any media passed to bot
clientDispatcher.AddHandlerToGroup(handlers.NewMessage(filters.Message.Media, download), 1)

fmt.Printf("client (@%s) has been started...\n", client.Self.Username)

err = client.Idle()
if err != nil {
log.Fatalln("failed to start client:", err)
}
}

func download(ctx *ext.Context, update *ext.Update) error {
filename, err := functions.GetMediaFileNameWithId(update.EffectiveMessage.Media)
if err != nil {
return errors.Wrap(err, "failed to get media file name")
}

_, err = ctx.DownloadMedia(
update.EffectiveMessage.Media,
ext.DownloadOutputPath(filename),
nil,
)
if err != nil {
return errors.Wrap(err, "failed to download media")
}

msg := fmt.Sprintf(`File "%s" downloaded`, filename)
_, err = ctx.Reply(update, msg, nil)
if err != nil {
return errors.Wrap(err, "failed to reply")
}

fmt.Println(msg)

return nil
}
14 changes: 7 additions & 7 deletions examples/middleware/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.21.4
require (
github.com/celestix/gotgproto v1.0.0-beta17
github.com/gotd/contrib v0.19.0
github.com/gotd/td v0.98.0
github.com/gotd/td v0.99.1
golang.org/x/time v0.5.0
)

Expand All @@ -28,16 +28,16 @@ require (
github.com/pkg/errors v0.9.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.2.0 // indirect
go.opentelemetry.io/otel v1.23.1 // indirect
go.opentelemetry.io/otel/trace v1.23.1 // indirect
go.opentelemetry.io/otel v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.22.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.17.0 // indirect
gorm.io/gorm v1.25.5 // indirect
golang.org/x/sys v0.18.0 // indirect
gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
Expand Down
32 changes: 16 additions & 16 deletions examples/middleware/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk=
github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0=
github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ=
github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ=
github.com/gotd/td v0.98.0 h1:WNS6ob/Nl1OBskXiOO/JNxCO2j3zGG2oKqm/ELHDjQY=
github.com/gotd/td v0.98.0/go.mod h1:Px8r98qWVHjQ3l68PVBCJfK1+Y9ZaAIkflqx0mqKcAg=
github.com/gotd/td v0.99.1 h1:eYneWHvNukWKxHBM47ZKbN/TEcbGZo/lHGfjfUZkSic=
github.com/gotd/td v0.99.1/go.mod h1:1SSAkksV4pg2TodyDX9e40Nue9os3CqdrBs6dQClNRY=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
Expand All @@ -48,12 +48,12 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.opentelemetry.io/otel v1.23.1 h1:Za4UzOqJYS+MUczKI320AtqZHZb7EqxO00jAHE0jmQY=
go.opentelemetry.io/otel v1.23.1/go.mod h1:Td0134eafDLcTS4y+zQ26GE8u3dEuRBiBCTUIRHaikA=
go.opentelemetry.io/otel/trace v1.23.1 h1:4LrmmEd8AU2rFvU1zegmvqW7+kWarxtNOPyeL6HmYY8=
go.opentelemetry.io/otel/trace v1.23.1/go.mod h1:4IpnpJFwr1mo/6HL8XIPJaE9y0+u1KcVmuW7dwFSVrI=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
Expand All @@ -62,24 +62,24 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/exp v0.0.0-20230116083435-1de6713980de h1:DBWn//IJw30uYCgERoxCg84hWtA97F4wMiKOIh00Uf0=
golang.org/x/exp v0.0.0-20230116083435-1de6713980de/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde h1:9DShaph9qhkIYw7QF91I/ynrr4cOO2PZra2PFD7Mfeg=
gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
Expand Down
40 changes: 6 additions & 34 deletions ext/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ func NewContext(ctx context.Context, client *tg.Client, peerStorage *storage.Pee
}
}

func (c *Context) generateRandomID() int64 {
return c.random.Int63()
func (ctx *Context) generateRandomID() int64 {
return ctx.random.Int63()
}

// ReplyOpts object contains optional parameters for Context.Reply.
Expand Down Expand Up @@ -692,34 +692,6 @@ func (ctx *Context) ExportSessionString() (string, error) {
return functions.EncodeSessionToString(ctx.PeerStorage.GetSession())
}

func getInputFileLocation(media tg.MessageMediaClass) (tg.InputFileLocationClass, error) {
switch v := media.(type) {
case *tg.MessageMediaPhoto: // messageMediaPhoto#695150d7
f, ok := v.Photo.AsNotEmpty()
if !ok {
return nil, mtp_errors.ErrUnknownTypeMedia
}
return &tg.InputPhotoFileLocation{
ID: f.ID,
AccessHash: f.AccessHash,
FileReference: f.FileReference,
}, nil
case *tg.MessageMediaDocument: // messageMediaDocument#4cf4d72d
f, ok := v.Document.AsNotEmpty()
if !ok {
return nil, mtp_errors.ErrUnknownTypeMedia
}
return f.AsInputDocumentFileLocation(), nil
case *tg.MessageMediaStory: // messageMediaStory#68cb6283
f, ok := v.Story.(*tg.StoryItem)
if !ok {
return nil, mtp_errors.ErrUnknownTypeMedia
}
return getInputFileLocation(f.Media)
}
return nil, mtp_errors.ErrUnknownTypeMedia
}

// DownloadOutputClass is an interface which is used to download media.
// It can be one from DownloadOutputStream, DownloadOutputPath and DownloadOutputParallel.
type DownloadOutputClass interface {
Expand Down Expand Up @@ -771,15 +743,15 @@ func (ctx *Context) DownloadMedia(media tg.MessageMediaClass, downloadOutput Dow
if opts == nil {
opts = &DownloadMediaOpts{}
}
downloader := downloader.NewDownloader()
mediaDownloader := downloader.NewDownloader()
if opts.PartSize > 0 {
downloader.WithPartSize(opts.PartSize)
mediaDownloader.WithPartSize(opts.PartSize)
}
inputFileLocation, err := getInputFileLocation(media)
inputFileLocation, err := functions.GetInputFileLocation(media)
if err != nil {
return nil, err
}
d := downloader.Download(ctx.Raw, inputFileLocation)
d := mediaDownloader.Download(ctx.Raw, inputFileLocation)
if opts.Threads > 0 {
d.WithThreads(opts.Threads)
}
Expand Down
7 changes: 5 additions & 2 deletions ext/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func (u *Update) EffectiveUser() *tg.User {
if u.Entities == nil {
return nil
}
if u.userId != 0 {
if u.userId == 0 {
return nil
}
return u.Entities.Users[u.userId]
Expand Down Expand Up @@ -224,9 +224,12 @@ func (u *Update) fillUserIdFromMessage(m tg.MessageClass) {
case *tg.MessageService:
userPeer = _m.FromID
}

uId, ok := userPeer.(*tg.PeerUser)
if !ok {
u.userId = u.Entities.Users[0].ID
if u.Entities != nil {
u.userId = u.Entities.Users[0].ID
}
} else {
u.userId = uId.UserID
}
Expand Down
Loading

0 comments on commit e1a2d1f

Please sign in to comment.