teldrive/internal/reader/reader.go

119 lines
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"
)
2024-03-20 01:01:56 +08:00
func calculatePartByteRanges(startByte, endByte, partSize int64) []types.Range {
partByteRanges := []types.Range{}
startPart := startByte / partSize
endPart := endByte / partSize
startOffset := startByte % partSize
for part := startPart; part <= endPart; part++ {
partStartByte := int64(0)
partEndByte := partSize - 1
if part == startPart {
partStartByte = startOffset
}
if part == endPart {
partEndByte = int64(endByte % partSize)
}
partByteRanges = append(partByteRanges, types.Range{Start: partStartByte, End: partEndByte, PartNo: part})
startOffset = 0
}
return partByteRanges
}
2023-12-08 05:46:06 +08:00
type linearReader struct {
2024-03-10 22:40:09 +08:00
ctx context.Context
parts []types.Part
2024-03-20 01:01:56 +08:00
ranges []types.Range
2024-03-10 22:40:09 +08:00
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-20 01:01:56 +08:00
start, end 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,
2024-03-20 01:01:56 +08:00
limit: end - start + 1,
ranges: calculatePartByteRanges(start, end, parts[0].Size),
2023-12-08 05:46:06 +08:00
}
2024-03-20 01:01:56 +08:00
r.reader, err = r.nextPart()
2023-12-08 05:46:06 +08:00
if err != nil {
return nil, err
}
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++
2024-03-20 01:01:56 +08:00
if r.pos < len(r.ranges) {
r.reader, err = r.nextPart()
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
}
2024-03-20 01:01:56 +08:00
func (r *linearReader) nextPart() (io.ReadCloser, error) {
location := r.parts[r.ranges[r.pos].PartNo].Location
startByte := r.ranges[r.pos].Start
endByte := r.ranges[r.pos].End
return newTGReader(r.ctx, r.client, location, startByte, endByte)
}
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
}