aboutsummaryrefslogtreecommitdiff
path: root/steam/extract.go
blob: 9a7a930d39aadf98579b1b726f7c5884243f552c (plain) (blame)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package steam

import (
	"archive/tar"
	"errors"
	"fmt"
	"io"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// how often are we going to be updating our status information?
const updateEveryNBytes = 10 * 1024 * 1024 // 10mb

// ExtractSmart attempts to discover what kind of resource is behind uri
// and extract it appropriately. It may fail with E_BadURI.
//
// For example the following forms are accepted:
//
//		ExtractSmart("http://127.0.0.1/some-archive")
//		ExtractSmart("https://example.com/some-archive")
//		ExtractSmart("file:///some/local/file/path/to/archive.tar")
//		ExtractSmart("/direct/path/to/archive.tar")
//		ExtractSmart("C:\Users\user\Downloads\archive.tar")
func (l *Library) ExtractSmart(uri string) (*Game, error) {
	if strings.HasPrefix(uri, "http") {
		_, err := url.Parse(uri)
		if err == nil {
			return l.ExtractHTTP(uri)
		}
	} else if strings.HasPrefix(uri, "file") {
		u, err := url.Parse(uri)
		if err == nil {
			return l.ExtractFile(u.Path)
		}
	} else if _, err := os.Stat(uri); err == nil {
		return l.ExtractFile(uri)
	}

	return nil, E_BadURI
}

// ExtractFile is a wrapper around Extract that handles an HTTP endpoint.
// this spawns an "extractFile" on the library. Status will be updated there
// as this goes along. Non fatal and fatal errors will be populated there
func (l *Library) ExtractFile(fn string) (*Game, error) {
	g := &Game{}
	j := newJob("extractFile", g)
	defer j.done()

	l.status.addJob(j)

	fi, err := os.Stat(fn)
	if err != nil {
		j.addError(err)
		return g, err
	}
	j.setSize(fi.Size())

	fh, err := os.Open(fn)
	if err != nil {
		j.addError(err)
		return g, err
	}

	return l.extractUpdate(j, g, fh)
}

// Extract will read a tarball from the io.Reader and install the game into
// the current library path. This offers no visibility into the progress,
// as it does not update the job status on the progress, though it will
// populate errors.
//
// Most callers will want to use ExtractHTTP or ExtractFile instead
func (l *Library) Extract(r io.Reader) (*Game, error) {
	g := &Game{LibraryPath: l.folder}
	j := newJob("extract", g)
	defer j.done()

	l.status.addJob(j)

	return l.extractPrimitive(j, g, r)
}

// extractUpdate takes care of updating the job as it goes along at updateEveryNBytes
// it will be reported back to the Job's status.
func (l *Library) extractUpdate(j *Job, g *Game, rdr io.ReadCloser) (*Game, error) {
	rdr, wrtr := io.Pipe()

	go func() {
		var err error
		g, err = l.extractPrimitive(j, g, rdr)
		if err != nil {
			j.addError(fmt.Errorf("Installer: extracting %s", err))
		}
		// resp.Body.Close()
		rdr.Close()
	}()

	var total int64
	var err error

	for {
		var n int64
		n, err = io.CopyN(wrtr, rdr, updateEveryNBytes)
		if err == io.EOF {
			break
		} else if err != nil {
			j.addError(fmt.Errorf(
				"Error encountered read error: %w", err))
			break
		}

		total += n
		j.setTransferred(total)

		// rate in bytes/sec
		// 	rate := total / int64(time.Since(*j.StartTime()).Seconds())
		rate := float64(total) / float64(time.Since(*j.StartTime()).Seconds())

		estSize := j.GetSize()

		if estSize == nil {
			j.addError(errors.New("Expected an estimated size, got nil"))
			continue
		}

		// remaining := *estSize - total
		remaining := float64(*estSize - total)

		j.setETA(time.Duration((remaining / rate) / 1000 / 1000 / 1000))
	}

	if err == io.EOF {
		return g, nil
	}

	return g, err

}

func (l *Library) extractPrimitive(j *Job, g *Game, r io.Reader) (*Game, error) {
	treader := tar.NewReader(r)

	for {
		hdr, err := treader.Next()
		if err == io.EOF {
			// We've reached the end! Whoee
			break
		}
		if err != nil {
			j.addError(err)
			return nil, err
		}

		fileName := filepath.ToSlash(hdr.Name)

		if g.Name == "" {
			s := strings.Split(fileName, "/")
			if len(s) >= 2 {
				g.Name = s[1]
			}
		}

		fileName = filepath.Join(l.folder, fileName)

		info := hdr.FileInfo()
		if info.IsDir() {
			// I don't like hard-coded permissions but it
			// it helps with overall platform compatibility
			err = os.MkdirAll(fileName, defaultDirectoryMode)
			if err != nil {
				j.addError(err)
				return nil, err
			}

			continue
		}

		err = os.MkdirAll(filepath.Dir(fileName), defaultDirectoryMode)
		if err != nil {
			j.addError(err)
			return nil, err
		}

		// Create a file handle to work with
		f, err := os.OpenFile(fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY,
			defaultFileMode)
		if err != nil {
			j.addError(err)
			return nil, err
		}
		if _, err := io.Copy(f, treader); err != nil {
			j.addError(err)
			f.Close()
			return nil, err
		}
		f.Close()

	}

	err := g.SetSizeInfo()
	if err != nil {
		j.addError(err)
		return nil, err
	}

	l.m.Lock()
	l.games[g.Name] = g
	l.m.Unlock()

	return g, nil
}