aboutsummaryrefslogtreecommitdiffhomepage
path: root/resources/images/exif/exif.go
blob: 90198eeed5957225046514d5534fd39f08d3f3e2 (plain)
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package exif

import (
	"bytes"
	"fmt"
	"io"
	"math/big"
	"regexp"
	"strings"
	"time"
	"unicode"
	"unicode/utf8"

	"github.com/bep/tmc"

	_exif "github.com/rwcarlsen/goexif/exif"
	"github.com/rwcarlsen/goexif/tiff"
)

const exifTimeLayout = "2006:01:02 15:04:05"

// ExifInfo holds the decoded Exif data for an Image.
type ExifInfo struct {
	// GPS latitude in degrees.
	Lat float64

	// GPS longitude in degrees.
	Long float64

	// Image creation date/time.
	Date time.Time

	// A collection of the available Exif tags for this Image.
	Tags Tags
}

type Decoder struct {
	includeFieldsRe  *regexp.Regexp
	excludeFieldsrRe *regexp.Regexp
	noDate           bool
	noLatLong        bool
}

func IncludeFields(expression string) func(*Decoder) error {
	return func(d *Decoder) error {
		re, err := compileRegexp(expression)
		if err != nil {
			return err
		}
		d.includeFieldsRe = re
		return nil
	}
}

func ExcludeFields(expression string) func(*Decoder) error {
	return func(d *Decoder) error {
		re, err := compileRegexp(expression)
		if err != nil {
			return err
		}
		d.excludeFieldsrRe = re
		return nil
	}
}

func WithLatLongDisabled(disabled bool) func(*Decoder) error {
	return func(d *Decoder) error {
		d.noLatLong = disabled
		return nil
	}
}

func WithDateDisabled(disabled bool) func(*Decoder) error {
	return func(d *Decoder) error {
		d.noDate = disabled
		return nil
	}
}

func compileRegexp(expression string) (*regexp.Regexp, error) {
	expression = strings.TrimSpace(expression)
	if expression == "" {
		return nil, nil
	}
	if !strings.HasPrefix(expression, "(") {
		// Make it case insensitive
		expression = "(?i)" + expression
	}

	return regexp.Compile(expression)
}

func NewDecoder(options ...func(*Decoder) error) (*Decoder, error) {
	d := &Decoder{}
	for _, opt := range options {
		if err := opt(d); err != nil {
			return nil, err
		}
	}

	return d, nil
}

func (d *Decoder) Decode(r io.Reader) (ex *ExifInfo, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Exif failed: %v", r)
		}
	}()

	var x *_exif.Exif
	x, err = _exif.Decode(r)
	if err != nil {
		if err.Error() == "EOF" {
			// Found no Exif
			return nil, nil
		}
		return
	}

	var tm time.Time
	var lat, long float64

	if !d.noDate {
		tm, _ = x.DateTime()
	}

	if !d.noLatLong {
		lat, long, _ = x.LatLong()
	}

	walker := &exifWalker{x: x, vals: make(map[string]any), includeMatcher: d.includeFieldsRe, excludeMatcher: d.excludeFieldsrRe}
	if err = x.Walk(walker); err != nil {
		return
	}

	ex = &ExifInfo{Lat: lat, Long: long, Date: tm, Tags: walker.vals}

	return
}

func decodeTag(x *_exif.Exif, f _exif.FieldName, t *tiff.Tag) (any, error) {
	switch t.Format() {
	case tiff.StringVal, tiff.UndefVal:
		s := nullString(t.Val)
		if strings.Contains(string(f), "DateTime") {
			if d, err := tryParseDate(x, s); err == nil {
				return d, nil
			}
		}
		return s, nil
	case tiff.OtherVal:
		return "unknown", nil
	}

	var rv []any

	for i := 0; i < int(t.Count); i++ {
		switch t.Format() {
		case tiff.RatVal:
			n, d, _ := t.Rat2(i)
			rat := big.NewRat(n, d)
			// if t is int or t > 1, use float64
			if rat.IsInt() || rat.Cmp(big.NewRat(1, 1)) == 1 {
				f, _ := rat.Float64()
				rv = append(rv, f)
			} else {
				rv = append(rv, rat)
			}

		case tiff.FloatVal:
			v, _ := t.Float(i)
			rv = append(rv, v)
		case tiff.IntVal:
			v, _ := t.Int(i)
			rv = append(rv, v)
		}
	}

	if t.Count == 1 {
		if len(rv) == 1 {
			return rv[0], nil
		}
	}

	return rv, nil
}

// Code borrowed from exif.DateTime and adjusted.
func tryParseDate(x *_exif.Exif, s string) (time.Time, error) {
	dateStr := strings.TrimRight(s, "\x00")
	// TODO(bep): look for timezone offset, GPS time, etc.
	timeZone := time.Local
	if tz, _ := x.TimeZone(); tz != nil {
		timeZone = tz
	}
	return time.ParseInLocation(exifTimeLayout, dateStr, timeZone)
}

type exifWalker struct {
	x              *_exif.Exif
	vals           map[string]any
	includeMatcher *regexp.Regexp
	excludeMatcher *regexp.Regexp
}

func (e *exifWalker) Walk(f _exif.FieldName, tag *tiff.Tag) error {
	name := string(f)
	if e.excludeMatcher != nil && e.excludeMatcher.MatchString(name) {
		return nil
	}
	if e.includeMatcher != nil && !e.includeMatcher.MatchString(name) {
		return nil
	}
	val, err := decodeTag(e.x, f, tag)
	if err != nil {
		return err
	}
	e.vals[name] = val
	return nil
}

func nullString(in []byte) string {
	var rv bytes.Buffer
	for len(in) > 0 {
		r, size := utf8.DecodeRune(in)
		if unicode.IsGraphic(r) {
			rv.WriteRune(r)
		}
		in = in[size:]
	}
	return rv.String()
}

var tcodec *tmc.Codec

func init() {
	var err error
	tcodec, err = tmc.New()
	if err != nil {
		panic(err)
	}
}

// Tags is a map of EXIF tags.
type Tags map[string]any

// UnmarshalJSON is for internal use only.
func (v *Tags) UnmarshalJSON(b []byte) error {
	vv := make(map[string]any)
	if err := tcodec.Unmarshal(b, &vv); err != nil {
		return err
	}

	*v = vv

	return nil
}

// MarshalJSON is for internal use only.
func (v Tags) MarshalJSON() ([]byte, error) {
	return tcodec.Marshal(v)
}