summaryrefslogtreecommitdiffstats
path: root/models/migrations/v20.go
blob: 0897eada745bef54acb3142e819b516e28574451 (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
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"crypto/md5"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"

	"xorm.io/xorm"
)

func useNewNameAvatars(x *xorm.Engine) error {
	d, err := os.Open(setting.AvatarUploadPath)
	if err != nil {
		if os.IsNotExist(err) {
			// Nothing to do if AvatarUploadPath does not exist
			return nil
		}
		return err
	}
	names, err := d.Readdirnames(0)
	if err != nil {
		return err
	}

	type User struct {
		ID              int64 `xorm:"pk autoincr"`
		Avatar          string
		UseCustomAvatar bool
	}

	for _, name := range names {
		userID, err := strconv.ParseInt(name, 10, 64)
		if err != nil {
			log.Warn("ignore avatar %s rename: %v", name, err)
			continue
		}

		var user User
		if has, err := x.ID(userID).Get(&user); err != nil {
			return err
		} else if !has {
			return errors.New("Avatar user is not exist")
		}

		fPath := filepath.Join(setting.AvatarUploadPath, name)
		bs, err := ioutil.ReadFile(fPath)
		if err != nil {
			return err
		}

		user.Avatar = fmt.Sprintf("%x", md5.Sum(bs))
		err = os.Rename(fPath, filepath.Join(setting.AvatarUploadPath, user.Avatar))
		if err != nil {
			return err
		}
		_, err = x.ID(userID).Cols("avatar").Update(&user)
		if err != nil {
			return err
		}
	}
	return nil
}