-
Notifications
You must be signed in to change notification settings - Fork 0
/
avatar.go
91 lines (74 loc) · 1.94 KB
/
avatar.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
package main
import (
"errors"
"github.com/markbates/goth"
"io/ioutil"
"path"
)
type TryAvatars []Avatar
func (a TryAvatars) GetAvatarURL(u ChatUser) (string, error) {
for _, avatar := range a {
if url, err := avatar.GetAvatarURL(u); err == nil {
return url, nil
}
}
return "", ErrNoAvatarURL
}
type ChatUser interface {
UniqueID() string
AvatarURL() (string, error)
}
type chatUser struct {
goth.User
uniqueID string
}
func (u chatUser) UniqueID() string {
return u.uniqueID
}
func (u chatUser) AvatarURL() (string, error) {
if u.User.AvatarURL == "" {
return "", ErrNoAvatarURL
}
return u.User.AvatarURL, nil
}
// ErrNoAvatar is the error that is returned when the
// Avatar instance is unable to provide an avatar URL.
var ErrNoAvatarURL = errors.New("chat: Unable to get an avatar URL.")
// Avatar represents types capable of representing
// user profile pictures.
type Avatar interface {
// GetAvatarURL gets the avatar URL for the specified client,
// or returns an error if something goes wrong.
// ErrNoAvatarURL is returned if the object is unable to get
// a URL for the specified client.
GetAvatarURL(ChatUser) (string, error)
}
type AuthAvatar struct{}
var UseAuthAvatar AuthAvatar
type GravatarAvatar struct{}
var UseGravatar GravatarAvatar
func (GravatarAvatar) GetAvatarURL(u ChatUser) (string, error) {
return "//www.gravatar.com/avatar/" + u.UniqueID(), nil
}
func (AuthAvatar) GetAvatarURL(u ChatUser) (string, error) {
url, err := u.AvatarURL()
if err != nil {
return "", err
}
return url, nil
}
type FileSystemAvatar struct{}
var UseFileSystemAvatar FileSystemAvatar
func (FileSystemAvatar) GetAvatarURL(u ChatUser) (string, error) {
if files, err := ioutil.ReadDir("avatars"); err == nil {
for _, file := range files {
if file.IsDir() {
continue
}
if match, _ := path.Match(u.UniqueID()+"*", file.Name()); match {
return "/avatars/" + file.Name(), nil
}
}
}
return "", ErrNoAvatarURL
}