teldrive/internal/reader/reader.go

81 lines
1.2 KiB
Go
Raw Normal View History

2023-12-08 05:46:06 +08:00
package reader
import (
"context"
"io"
"github.com/divyam234/teldrive/pkg/types"
"github.com/gotd/td/telegram"
)
type linearReader struct {
2024-03-10 22:40:09 +08:00
ctx context.Context
parts []types.Part
pos int
client *telegram.Client
reader io.ReadCloser
limit int64
err error
2023-12-08 05:46:06 +08:00
}
func NewLinearReader(ctx context.Context,
client *telegram.Client,
parts []types.Part,
2024-03-10 22:40:09 +08:00
limit int64,
2023-12-08 05:46:06 +08:00
) (reader io.ReadCloser, err error) {
r := &linearReader{
2024-03-10 22:40:09 +08:00
ctx: ctx,
parts: parts,
client: client,
limit: limit,
2023-12-08 05:46:06 +08:00
}
2024-03-10 22:40:09 +08:00
reader, err = newTGReader(r.ctx, r.client, r.parts[r.pos])
2023-12-08 05:46:06 +08:00
if err != nil {
return nil, err
}
r.reader = reader
return r, nil
}
func (r *linearReader) Read(p []byte) (n int, err error) {
2024-03-10 22:40:09 +08:00
if r.err != nil {
return 0, r.err
}
if r.limit <= 0 {
return 0, io.EOF
}
2023-12-08 05:46:06 +08:00
n, err = r.reader.Read(p)
2024-03-10 22:40:09 +08:00
if err == nil {
r.limit -= int64(n)
}
if err == io.EOF {
if r.limit > 0 {
err = nil
}
2023-12-08 05:46:06 +08:00
r.pos++
if r.pos < len(r.parts) {
2024-03-10 22:40:09 +08:00
r.reader, err = newTGReader(r.ctx, r.client, r.parts[r.pos])
2023-12-08 05:46:06 +08:00
}
}
2024-03-10 22:40:09 +08:00
r.err = err
return
2023-12-08 05:46:06 +08:00
}
func (r *linearReader) Close() (err error) {
if r.reader != nil {
err = r.reader.Close()
r.reader = nil
return err
}
return nil
}