File: s3.go

package info (click to toggle)
syncthing 1.29.5~ds1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 22,848 kB
  • sloc: javascript: 37,288; sh: 1,838; xml: 1,115; makefile: 66
file content (101 lines) | stat: -rw-r--r-- 2,293 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (C) 2024 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package s3

import (
	"io"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
)

type Session struct {
	bucket string
	s3sess *session.Session
}

type Object = s3.Object

func NewSession(endpoint, region, bucket, accessKeyID, secretKey string) (*Session, error) {
	sess, err := session.NewSession(&aws.Config{
		Region:      aws.String(region),
		Endpoint:    aws.String(endpoint),
		Credentials: credentials.NewStaticCredentials(accessKeyID, secretKey, ""),
	})
	if err != nil {
		return nil, err
	}
	return &Session{
		bucket: bucket,
		s3sess: sess,
	}, nil
}

func (s *Session) Upload(r io.Reader, key string) error {
	uploader := s3manager.NewUploader(s.s3sess)
	_, err := uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(s.bucket),
		Key:    aws.String(key),
		Body:   r,
	})
	return err
}

func (s *Session) List(fn func(*Object) bool) error {
	svc := s3.New(s.s3sess)

	opts := &s3.ListObjectsV2Input{
		Bucket: aws.String(s.bucket),
	}
	for {
		resp, err := svc.ListObjectsV2(opts)
		if err != nil {
			return err
		}

		for _, item := range resp.Contents {
			if !fn(item) {
				return nil
			}
		}

		if resp.NextContinuationToken == nil || *resp.NextContinuationToken == "" {
			break
		}
		opts.ContinuationToken = resp.NextContinuationToken
	}

	return nil
}

func (s *Session) LatestKey() (string, error) {
	var latestKey string
	var lastModified time.Time
	if err := s.List(func(obj *Object) bool {
		if latestKey == "" || obj.LastModified.After(lastModified) {
			latestKey = *obj.Key
			lastModified = *obj.LastModified
		}
		return true
	}); err != nil {
		return "", err
	}
	return latestKey, nil
}

func (s *Session) Download(w io.WriterAt, key string) error {
	downloader := s3manager.NewDownloader(s.s3sess)
	_, err := downloader.Download(w, &s3.GetObjectInput{
		Bucket: aws.String(s.bucket),
		Key:    aws.String(key),
	})
	return err
}