[bugfix] Wrap media reader in length reader to determine length if no content-length given (#848)

* use lengthReader 2 determine fileSize if not given

* update tests

* small fixes

* go fmt
This commit is contained in:
tobi 2022-09-24 11:11:47 +02:00 committed by GitHub
commit 78409f1985
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 397 additions and 30 deletions

View file

@ -19,12 +19,15 @@
package media
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/h2non/filetype"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/storage"
)
// AllSupportedMIMETypes just returns all media
@ -144,3 +147,31 @@ func parseOlderThan(olderThanDays int) (time.Time, error) {
return olderThan, nil
}
// lengthReader wraps a reader and reads the length of total bytes written as it goes.
type lengthReader struct {
source io.Reader
length int
}
func (r *lengthReader) Read(b []byte) (int, error) {
n, err := r.source.Read(b)
r.length += n
return n, err
}
// putStream either puts a file with a known fileSize into storage directly, and returns the
// fileSize unchanged, or it wraps the reader with a lengthReader and returns the discovered
// fileSize.
func putStream(ctx context.Context, storage storage.Driver, key string, r io.Reader, fileSize int) (int, error) {
if fileSize > 0 {
return fileSize, storage.PutStream(ctx, key, r)
}
lr := &lengthReader{
source: r,
}
err := storage.PutStream(ctx, key, lr)
return lr.length, err
}