-
Notifications
You must be signed in to change notification settings - Fork 62
/
mysql_repository.go
350 lines (316 loc) · 9.88 KB
/
mysql_repository.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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// SPDX-License-Identifier: AGPL-3.0-only
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
package revision
import (
"bytes"
"compress/flate"
"context"
"errors"
"fmt"
"io"
"reflect"
"time"
"github.com/elliotchance/phpserialize"
"github.com/mitchellh/mapstructure"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/bangumi/server/internal/dal/dao"
"github.com/bangumi/server/internal/dal/query"
"github.com/bangumi/server/internal/domain"
"github.com/bangumi/server/internal/model"
"github.com/bangumi/server/internal/pkg/errgo"
)
type mysqlRepo struct {
q *query.Query
log *zap.Logger
}
func NewMysqlRepo(q *query.Query, log *zap.Logger) (domain.RevisionRepo, error) {
return mysqlRepo{q: q, log: log.Named("revision.mysqlRepo")}, nil
}
func (r mysqlRepo) CountPersonRelated(ctx context.Context, personID model.PersonID) (int64, error) {
c, err := r.q.RevisionHistory.WithContext(ctx).
Where(r.q.RevisionHistory.Mid.Eq(uint32(personID)), r.q.RevisionHistory.Type.In(model.PersonRevisionTypes()...)).
Count()
if err != nil {
return 0, errgo.Wrap(err, "dal")
}
return c, nil
}
func (r mysqlRepo) ListPersonRelated(
ctx context.Context, personID model.PersonID, limit int, offset int,
) ([]model.PersonRevision, error) {
revisions, err := r.q.RevisionHistory.WithContext(ctx).
Where(r.q.RevisionHistory.Mid.Eq(uint32(personID)), r.q.RevisionHistory.Type.In(model.PersonRevisionTypes()...)).
Order(r.q.RevisionHistory.ID.Desc()).
Limit(limit).
Offset(offset).Find()
if err != nil {
return nil, errgo.Wrap(err, "dal")
}
result := make([]model.PersonRevision, 0, len(revisions))
for _, revision := range revisions {
result = append(result, convertPersonRevisionDao(revision, nil))
}
return result, nil
}
func (r mysqlRepo) GetPersonRelated(ctx context.Context, id model.RevisionID) (model.PersonRevision, error) {
revision, err := r.q.RevisionHistory.WithContext(ctx).
Where(r.q.RevisionHistory.ID.Eq(id),
r.q.RevisionHistory.Type.In(model.PersonRevisionTypes()...)).
First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return model.PersonRevision{}, domain.ErrNotFound
}
r.log.Error("unexpected error happened", zap.Error(err))
return model.PersonRevision{}, errgo.Wrap(err, "dal")
}
data, err := r.q.RevisionText.WithContext(ctx).
Where(r.q.RevisionText.TextID.Eq(revision.TextID)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
r.log.Error("can't find revision text", zap.Uint32("id", revision.TextID))
return model.PersonRevision{}, domain.ErrNotFound
}
r.log.Error("unexpected error happened", zap.Error(err))
return model.PersonRevision{}, errgo.Wrap(err, "dal")
}
return convertPersonRevisionDao(revision, data), nil
}
func (r mysqlRepo) CountCharacterRelated(ctx context.Context, characterID model.CharacterID) (int64, error) {
c, err := r.q.RevisionHistory.WithContext(ctx).
Where(
r.q.RevisionHistory.Mid.Eq(uint32(characterID)),
r.q.RevisionHistory.Type.In(model.CharacterRevisionTypes()...),
).Count()
return c, wrapGORMError(err)
}
func (r mysqlRepo) ListCharacterRelated(
ctx context.Context, characterID model.CharacterID, limit int, offset int,
) ([]model.CharacterRevision, error) {
revisions, err := r.q.RevisionHistory.WithContext(ctx).
Where(
r.q.RevisionHistory.Mid.Eq(uint32(characterID)),
r.q.RevisionHistory.Type.In(model.CharacterRevisionTypes()...),
).
Order(r.q.RevisionHistory.ID.Desc()).
Limit(limit).
Offset(offset).Find()
if err != nil {
return nil, wrapGORMError(err)
}
result := make([]model.CharacterRevision, 0, len(revisions))
for _, revision := range revisions {
result = append(result, convertCharacterRevisionDao(revision, nil))
}
return result, nil
}
func (r mysqlRepo) GetCharacterRelated(ctx context.Context, id model.RevisionID) (model.CharacterRevision, error) {
revision, err := r.q.RevisionHistory.WithContext(ctx).
Where(r.q.RevisionHistory.ID.Eq(id),
r.q.RevisionHistory.Type.In(model.CharacterRevisionTypes()...)).
First()
if err != nil {
return model.CharacterRevision{}, wrapGORMError(err)
}
data, err := r.q.RevisionText.WithContext(ctx).
Where(r.q.RevisionText.TextID.Eq(revision.TextID)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
r.log.Error("can't find revision text", zap.Uint32("id", revision.TextID))
return model.CharacterRevision{}, domain.ErrNotFound
}
r.log.Error("unexpected error happened", zap.Error(err))
return model.CharacterRevision{}, errgo.Wrap(err, "dal")
}
return convertCharacterRevisionDao(revision, data), nil
}
func wrapGORMError(err error) error {
if errors.Is(err, gorm.ErrRecordNotFound) {
return domain.ErrNotFound
}
return errgo.Wrap(err, "dal")
}
func (r mysqlRepo) CountSubjectRelated(ctx context.Context, id model.SubjectID) (int64, error) {
c, err := r.q.SubjectRevision.WithContext(ctx).
Where(r.q.SubjectRevision.SubjectID.Eq(id)).Count()
if err != nil {
return 0, errgo.Wrap(err, "dal")
}
return c, nil
}
func (r mysqlRepo) ListSubjectRelated(
ctx context.Context, id model.SubjectID, limit int, offset int,
) ([]model.SubjectRevision, error) {
revisions, err := r.q.SubjectRevision.WithContext(ctx).
Where(r.q.SubjectRevision.SubjectID.Eq(id)).
Order(r.q.SubjectRevision.ID.Desc()).
Limit(limit).
Offset(offset).Find()
if err != nil {
return nil, errgo.Wrap(err, "dal")
}
result := make([]model.SubjectRevision, 0, len(revisions))
for _, revision := range revisions {
result = append(result, convertSubjectRevisionDao(revision, false))
}
return result, nil
}
func (r mysqlRepo) GetSubjectRelated(ctx context.Context, id model.RevisionID) (model.SubjectRevision, error) {
revision, err := r.q.SubjectRevision.WithContext(ctx).
Where(r.q.SubjectRevision.ID.Eq(id)).
First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return model.SubjectRevision{}, domain.ErrNotFound
}
r.log.Error("unexpected error happened", zap.Error(err))
return model.SubjectRevision{}, errgo.Wrap(err, "dal")
}
return convertSubjectRevisionDao(revision, true), nil
}
func toValidJSON(data any) any {
if data == nil {
return nil
}
t := reflect.TypeOf(data).Kind()
switch t {
case reflect.Array:
case reflect.Slice:
if arr, ok := data.([]any); ok {
for i, val := range arr {
arr[i] = toValidJSON(val)
}
return arr
}
case reflect.Map:
if m, ok := data.(map[any]any); ok {
ret := map[string]any{}
for k, v := range m {
ret[fmt.Sprint(k)] = toValidJSON(v)
}
return ret
}
default:
}
return data
}
func convertRevisionText(text []byte) map[string]any {
gr := flate.NewReader(bytes.NewBuffer(text))
defer gr.Close()
b, err := io.ReadAll(gr)
if err != nil {
return nil
}
result, err := phpserialize.UnmarshalAssociativeArray(b)
if err != nil {
return nil
}
if d, ok := toValidJSON(result).(map[string]any); ok {
return d
}
return nil
}
func safeDecodeExtra(k1 reflect.Type, k2 reflect.Type, input any) (any, error) {
if k2.Name() == "Extra" && k1.Kind() != reflect.Map {
return map[string]string{}, nil
}
return input, nil
}
func castCharacterData(raw map[string]any) model.CharacterRevisionData {
if raw == nil {
return nil
}
result := make(map[string]model.CharacterRevisionDataItem, len(raw))
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: safeDecodeExtra,
Result: &result,
})
if err != nil || decoder.Decode(raw) != nil {
return nil
}
return result
}
func castPersonData(raw map[string]any) model.PersonRevisionData {
if raw == nil {
return nil
}
result := make(map[string]model.PersonRevisionDataItem, len(raw))
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: safeDecodeExtra,
Result: &result,
})
if err != nil || decoder.Decode(raw) != nil {
return nil
}
return result
}
func convertPersonRevisionDao(r *dao.RevisionHistory, text *dao.RevisionText) model.PersonRevision {
var data model.PersonRevisionData
if text != nil {
data = castPersonData(convertRevisionText(text.Text))
}
return model.PersonRevision{
RevisionCommon: model.RevisionCommon{
ID: r.ID,
Type: r.Type,
Summary: r.Summary,
CreatorID: r.CreatorID,
CreatedAt: time.Unix(int64(r.CreatedTime), 0),
},
Data: data,
}
}
func convertCharacterRevisionDao(r *dao.RevisionHistory, text *dao.RevisionText) model.CharacterRevision {
var data model.CharacterRevisionData
if text != nil {
data = castCharacterData(convertRevisionText(text.Text))
}
return model.CharacterRevision{
RevisionCommon: model.RevisionCommon{
ID: r.ID,
Type: r.Type,
Summary: r.Summary,
CreatorID: r.CreatorID,
CreatedAt: time.Unix(int64(r.CreatedTime), 0),
},
Data: data,
}
}
func convertSubjectRevisionDao(r *dao.SubjectRevision, isDetailed bool) model.SubjectRevision {
var data *model.SubjectRevisionData
if isDetailed {
data = &model.SubjectRevisionData{
SubjectID: r.SubjectID,
Name: r.Name,
NameCN: r.NameCN,
VoteField: r.VoteField,
Type: r.Type,
TypeID: r.TypeID,
FieldInfobox: r.FieldInfobox,
FieldSummary: r.FieldSummary,
FieldEps: r.FieldEps,
Platform: r.Platform,
}
}
return model.SubjectRevision{RevisionCommon: model.RevisionCommon{
ID: r.ID,
Type: r.Type,
Summary: r.EditSummary,
CreatorID: r.CreatorID,
CreatedAt: time.Unix(int64(r.Dateline), 0),
},
Data: data,
}
}