-
Notifications
You must be signed in to change notification settings - Fork 0
/
duplicate-finder.go
243 lines (196 loc) · 4.31 KB
/
duplicate-finder.go
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
package goautowp
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/jpeg" // support JPEG decoding.
_ "image/png" // support PNG decoding.
"io"
"net/http"
"strconv"
"github.com/autowp/goautowp/util"
"github.com/corona10/goimagehash"
"github.com/doug-martin/goqu/v9"
"github.com/getsentry/sentry-go"
"github.com/sirupsen/logrus"
)
const (
threshold = 3
decimal = 10
)
// DuplicateFinder Main Object.
type DuplicateFinder struct {
db *goqu.Database
}
// DuplicateFinderInputMessage InputMessage.
type DuplicateFinderInputMessage struct {
PictureID int `json:"picture_id"`
URL string `json:"url"`
}
// NewDuplicateFinder constructor.
func NewDuplicateFinder(db *goqu.Database) (*DuplicateFinder, error) {
s := &DuplicateFinder{
db: db,
}
return s, nil
}
// ListenAMQP for incoming messages.
func (s *DuplicateFinder) ListenAMQP(url string, queue string, quitChan chan bool) error {
rabbitMQ, err := util.ConnectRabbitMQ(url)
if err != nil {
logrus.Error(err)
return err
}
ch, err := rabbitMQ.Channel()
if err != nil {
return err
}
defer util.Close(ch)
inQ, err := ch.QueueDeclare(
queue, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
msgs, err := ch.Consume(
inQ.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return err
}
done := false
for !done {
select {
case <-quitChan:
logrus.Info("DuplicateFinder got quit signal")
done = true
break
case d := <-msgs:
if d.ContentType != "application/json" {
sentry.CaptureException(fmt.Errorf("unexpected mime `%v`", d.ContentType))
continue
}
var message DuplicateFinderInputMessage
err := json.Unmarshal(d.Body, &message)
if err != nil {
sentry.CaptureException(fmt.Errorf("failed to parse json `%w`: %s", err, d.Body))
continue
}
err = s.Index(message.PictureID, message.URL)
if err != nil {
sentry.CaptureException(err)
}
}
}
logrus.Info("Disconnecting RabbitMQ")
return rabbitMQ.Close()
}
// Index picture image
// #nosec G107
func (s *DuplicateFinder) Index(id int, url string) error {
logrus.Infof("Indexing picture %v", id)
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req) //nolint:bodyclose
if err != nil {
return err
}
defer util.Close(resp.Body)
logrus.Infof("Calculate hash for %v", url)
hash, err := getFileHash(resp.Body)
if err != nil {
return err
}
stmt, err := s.db.Prepare(`
INSERT INTO df_hash (picture_id, hash)
VALUES (?, ?)
`)
if err != nil {
return err
}
defer util.Close(stmt)
_, err = stmt.Exec(id, hash)
if err != nil {
return err
}
return s.updateDistance(id)
}
func getFileHash(reader io.Reader) (uint64, error) {
img, _, err := image.Decode(reader)
if err != nil {
return 0, err
}
hash, err := goimagehash.PerceptionHash(img)
if err != nil {
return 0, err
}
return hash.GetHash(), nil
}
func (s *DuplicateFinder) updateDistance(id int) error {
if id <= 0 {
return errors.New("invalid id provided")
}
var hash uint64
err := s.db.QueryRow("SELECT hash FROM df_hash WHERE picture_id = ?", id).Scan(&hash)
if err != nil {
return err
}
insertStmt, err := s.db.Prepare(`
INSERT INTO df_distance (src_picture_id, dst_picture_id, distance)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE distance=distance;
`)
if err != nil {
return err
}
defer util.Close(insertStmt)
rows, err := s.db.Query(`
SELECT picture_id, BIT_COUNT(hash ^ `+strconv.FormatUint(hash, decimal)+`) AS distance
FROM df_hash
WHERE picture_id != ?
HAVING distance <= ?
`, id, threshold)
if err != nil {
return err
}
if errors.Is(err, sql.ErrNoRows) {
return nil
}
defer util.Close(rows)
for rows.Next() {
var (
pictureID int
distance int
)
serr := rows.Scan(&pictureID, &distance)
if serr != nil {
return serr
}
_, serr = insertStmt.Exec(id, pictureID, distance)
if serr != nil {
return serr
}
_, serr = insertStmt.Exec(pictureID, id, distance)
if serr != nil {
return serr
}
}
return nil
}