/
profile.go
227 lines (196 loc) · 6.83 KB
/
profile.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
// Copyright 2022 E99p1ant. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package user
import (
"fmt"
"net/url"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/xuri/excelize/v2"
"github.com/NekoWheel/NekoBox/internal/context"
"github.com/NekoWheel/NekoBox/internal/db"
"github.com/NekoWheel/NekoBox/internal/form"
"github.com/NekoWheel/NekoBox/internal/storage"
)
func Profile(ctx context.Context) {
ctx.Success("user/profile")
}
func ProfileAPI(ctx context.Context) error {
return ctx.JSON(ctx.User)
}
func UpdateProfile(ctx context.Context, f form.UpdateProfile) {
if ctx.HasError() {
ctx.Success("user/profile")
return
}
var avatarURL string
avatarFile, avatarFileHeader, err := ctx.Request().FormFile("avatar")
if err == nil {
if avatarFileHeader.Size > storage.MaxAvatarSize {
ctx.SetError(errors.New("头像文件太大,最大支持 2MB"))
ctx.Success("user/profile")
return
}
avatarURL, err = storage.UploadPictureToS3(avatarFile, avatarFileHeader)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload avatar")
}
}
var backgroundURL string
backgroundFile, backgroundFileHeader, err := ctx.Request().FormFile("background")
if err == nil {
if backgroundFileHeader.Size > storage.MaxBackgroundSize {
ctx.SetError(errors.New("背景图文件太大,最大支持 2MB"))
ctx.Success("user/profile")
return
}
backgroundURL, err = storage.UploadPictureToS3(backgroundFile, backgroundFileHeader)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to upload background")
}
}
if f.NewPassword != "" {
if err := db.Users.ChangePassword(ctx.Request().Context(), ctx.User.ID, f.OldPassword, f.NewPassword); err != nil {
if errors.Is(err, db.ErrBadCredential) {
ctx.SetError(errors.New("旧密码输入错误"))
} else {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update password")
ctx.SetInternalError()
}
ctx.Success("user/profile")
return
}
}
var notify db.NotifyType
if f.NotifyEmail != "" {
notify = db.NotifyTypeEmail
} else {
notify = db.NotifyTypeNone
}
if err := db.Users.Update(ctx.Request().Context(), ctx.User.ID, db.UpdateUserOptions{
Name: f.Name,
Avatar: avatarURL,
Background: backgroundURL,
Intro: f.Intro,
Notify: notify,
}); err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to update user profile")
ctx.SetInternalErrorFlash()
} else {
ctx.SetSuccessFlash("更新个人信息成功")
}
ctx.Redirect("/user/profile")
}
func ExportProfile(ctx context.Context) {
user, err := db.Users.GetByID(ctx.Request().Context(), ctx.User.ID)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get user")
ctx.SetError(errors.New("导出失败:获取用户信息失败"))
ctx.Success("user/profile")
return
}
questions, err := db.Questions.GetByUserID(ctx.Request().Context(), user.ID, db.GetQuestionsByUserIDOptions{
FilterAnswered: false,
ShowPrivate: true,
})
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to get questions")
ctx.SetError(errors.New("导出失败:获取问题信息失败"))
ctx.Success("user/profile")
return
}
f, err := createExportExcelFile(user, questions)
if err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to create excel file")
ctx.SetError(errors.New("导出失败:创建Excel文件失败"))
ctx.Success("user/profile")
return
}
fileName := fmt.Sprintf("NekoBox账号信息导出-%s-%s.xlsx", user.Domain, time.Now().Format("20060102150405"))
ctx.ResponseWriter().Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
ctx.ResponseWriter().Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.QueryEscape(fileName))
if err := f.Write(ctx.ResponseWriter()); err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to write excel file")
ctx.SetError(errors.New("导出失败:写入Excel文件失败"))
ctx.Success("user/profile")
return
}
}
func createXLSXStreamWriter(xlsx *excelize.File, sheet string, headers []string) (*excelize.StreamWriter, error) {
xlsx.NewSheet(sheet)
sw, err := xlsx.NewStreamWriter(sheet)
if err != nil {
return nil, errors.Wrap(err, "new stream writer")
}
cols := make([]interface{}, 0, len(headers))
for _, c := range headers {
cols = append(cols, c)
}
err = sw.SetRow("A1", cols)
if err != nil {
return nil, errors.Wrap(err, "set header row")
}
return sw, nil
}
func createExportExcelFile(user *db.User, questions []*db.Question) (*excelize.File, error) {
f := excelize.NewFile()
sw, err := createXLSXStreamWriter(f, "账号信息", nil)
if err != nil {
return nil, errors.Wrap(err, "create xlsx stream writer: 提问")
}
// Set personal information sheet.
personalData := [][]interface{}{
{"NekoBox 账号信息导出", fmt.Sprintf("导出时间 %s", time.Now().Format("2006-01-02 15:04:05"))},
{"电子邮箱", user.Email},
{"昵称", user.Name},
{"个性域名", user.Domain},
{"介绍", user.Intro},
{"头像 URL", user.Avatar},
{"背景图 URL", user.Background},
{"注册时间", user.CreatedAt},
}
currentRow := 1
for _, row := range personalData {
cell, _ := excelize.CoordinatesToCellName(1, currentRow)
_ = sw.SetRow(cell, row)
currentRow++
}
if err := sw.Flush(); err != nil {
return nil, errors.Wrap(err, "flush personal data")
}
// Set questions sheet.
sw, err = createXLSXStreamWriter(f, "提问", []string{"提问时间", "问题", "回答"})
if err != nil {
return nil, errors.Wrap(err, "create xlsx stream writer: 提问")
}
currentRow = 2 // Include header row.
for _, question := range questions {
question := question
vals := []interface{}{question.CreatedAt, question.Content, question.Answer}
cell, _ := excelize.CoordinatesToCellName(1, currentRow)
_ = sw.SetRow(cell, vals)
currentRow++
}
if err := sw.Flush(); err != nil {
return nil, errors.Wrap(err, "flush personal data")
}
f.SetActiveSheet(f.GetSheetIndex("提问"))
f.DeleteSheet("Sheet1") // Delete default sheet.
return f, nil
}
func DeactivateProfile(ctx context.Context) {
ctx.Success("user/deactivate")
}
func DeactivateProfileAction(ctx context.Context) {
if err := db.Users.Deactivate(ctx.Request().Context(), ctx.User.ID); err != nil {
logrus.WithContext(ctx.Request().Context()).WithError(err).Error("Failed to deactivate user")
ctx.SetInternalError()
ctx.Success("user/deactivate")
return
}
ctx.Session.Flush()
ctx.SetSuccessFlash("您的账号已停用,感谢您使用 NekoBox。期待未来还能再见 👋🏻")
ctx.Redirect("/login")
}