Skip to content

Commit

Permalink
头像使用七牛云存储
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmykuu committed Apr 5, 2013
1 parent 95406e7 commit 82cf432
Show file tree
Hide file tree
Showing 16 changed files with 272 additions and 91 deletions.
6 changes: 3 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ _testmain.go
etc/config.json
bin
pkg
src/github.com/jimmykuu/webhelpers/

src/github.com/jimmykuu/wtforms/
src/github.com
src/code.google.com
src/labix.org
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ Golang中国([www.golang.tc](http://www.golang.tc))源代码.
- MongoDB
- github.com/gorilla/mux
- github.com/gorilla/sessions
- github.com/qiniu/api
- github.com/qiniu/bytes
- github.com/qiniu/rpc
- labix.org/v2/mgo
- code.google.com/p/go-uuid/uuid
- github.com/jimmykuu/webhelpers
Expand All @@ -18,9 +21,12 @@ Golang中国([www.golang.tc](http://www.golang.tc))源代码.
go get -u github.com/gorilla/mux
go get -u github.com/gorilla/sessions
go get -u labix.org/v2/mgo
go get -u code.google.com/p/go-uuid/uuid
go get -u github.com/jimmykuu/webhelpers
go get -u github.com/jimmykuu/wtforms
go get -u code.google.com/p/go-uuid/uuid
go get -u github.com/jimmykuu/webhelpers
go get -u github.com/jimmykuu/wtforms
go get -u github.com/qiniu/api
go get -u github.com/qiniu/bytes
go get -u github.com/qiniu/rpc
git clone git://github.com/jimmykuu/gopher.git

修改文件 *etc/config.json.default**etc/config.json* 作为配置文件
Expand Down
2 changes: 1 addition & 1 deletion build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ OLDGOPATH="$GOPATH"
export GOPATH="$CURDIR"

go install server
go install movetocontents
go install gravatar2qiniu

export GOPATH="$OLDGOPATH"

Expand Down
2 changes: 2 additions & 0 deletions etc/config.json.default
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@
"from_email": "who@example.com",
"superusers": "jimmykuu,another",
"analytics_file": "",
"qiniu_access_key": "",
"qiniu_secret_key": "",
"static_file_version": 1
}
122 changes: 97 additions & 25 deletions src/gopher/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import (
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/jimmykuu/wtforms"
. "github.com/qiniu/api/conf"
qiniu_io "github.com/qiniu/api/io"
"github.com/qiniu/api/rs"
"io"
"labix.org/v2/mgo/bson"
"net/http"
"os"
//"qbox/api/conf"
//"qbox/api/rs"
// "os"
"strings"
"time"
)
Expand Down Expand Up @@ -91,12 +92,12 @@ func signupHandler(w http.ResponseWriter, r *http.Request) {
c2.Find(nil).One(&status)

id := bson.NewObjectId()

username := form.Value("username")
validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
index := status.UserIndex + 1
err = c.Insert(&User{
Id_: id,
Username: form.Value("username"),
Username: username,
Password: encryptPassword(form.Value("password")),
Email: form.Value("email"),
ValidateCode: validateCode,
Expand Down Expand Up @@ -126,7 +127,13 @@ func signupHandler(w http.ResponseWriter, r *http.Request) {
message(w, r, "注册成功", "请查看你的邮箱进行验证,如果收件箱没有,请查看垃圾邮件,如果还没有,请给jimmykuu@126.com发邮件,告知你的用户名。", "success")
*/
message(w, r, "注册成功", fmt.Sprintf(`感谢您的注册,您已经成为Golang中国第 <strong>%d</strong>位用户,<a href="/signin">登录</a>。`, index), "success")
// 注册成功后设成登录状态
session, _ := store.Get(r, "user")
session.Values["username"] = username
session.Save(r, w)

// 跳到修改用户信息页面
http.Redirect(w, r, "/profile", http.StatusFound)
return
}
}
Expand Down Expand Up @@ -419,6 +426,10 @@ func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, r, "account/reset_password.html", map[string]interface{}{"form": form, "code": code, "account": user.Username})
}

type Sizer interface {
Size() int64
}

// URL: /profile/avatar
// 修改头像,提交到七牛云存储
func changeAvatarHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -438,25 +449,86 @@ func changeAvatarHandler(w http.ResponseWriter, r *http.Request) {

defer formFile.Close()

fmt.Println(formFile)

fmt.Println(formHeader.Header["Content-Type"][0])
filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + ".png"
f, err := os.Create(filename)
defer f.Close()
io.Copy(f, formFile)

//service := rs.New(http.DefaultTransport)
//fmt.Println(service)
//fmt.Println(filename)
//ret, code, err := service.Put("gopher:avatar/"+filename, "", formFile, 340719)
//if err != nil {
// fmt.Println("upload error:", err.Error())
// return
//}

//fmt.Println(ret)
//fmt.Println("code:", code)
// 检查是否是jpg或png文件
uploadFileType := formHeader.Header["Content-Type"][0]

isValidateType := false
for _, imgType := range [3]string{"image/png", "image/jpeg"} {
if imgType == uploadFileType {
isValidateType = true
break
}
}

if !isValidateType {
fmt.Println("upload image type error:", uploadFileType)
// 提示错误
renderTemplate(w, r, "account/avatar.html", map[string]interface{}{
"user": user,
"error": "文件类型错误,请选择jpg/png图片上传。",
})
return
}

// 检查文件尺寸是否在500K以内
fileSize := formFile.(Sizer).Size()

if fileSize > 500*1024 {
// > 500K
fmt.Printf("upload image size > 500K: %dK\n", fileSize/1024)
renderTemplate(w, r, "account/avatar.html", map[string]interface{}{
"user": user,
"error": "图片大小大于500K,请选择500K以内图片上传。",
})
return
}

extra := &qiniu_io.PutExtra{
Bucket: "gopher",
MimeType: "",
CustomMeta: "",
CallbackParams: "",
}

ACCESS_KEY = Config.QiniuAccessKey
SECRET_KEY = Config.QiniuSecretKey

filenameExtension := ".jpg"
if uploadFileType == "image/png" {
filenameExtension = ".png"
}

// 文件名:32位uuid,不带减号和后缀组成
filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension

key := "avatar/" + filename

ret := new(qiniu_io.PutRet)

var policy = rs.PutPolicy{
Scope: "gopher",
}

err = qiniu_io.Put(nil, ret, policy.Token(), key, formFile, extra)

if err != nil {
fmt.Println("upload to qiniu failed:", err.Error())
renderTemplate(w, r, "account/avatar.html", map[string]interface{}{
"user": user,
"error": "上传失败,请反馈错误",
})
return
}

// 存储远程文件名
c := DB.C("users")
c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}})

renderTemplate(w, r, "account/avatar.html", map[string]interface{}{
"user": user,
"success": "图片上传成功",
})
return
}

renderTemplate(w, r, "account/avatar.html", map[string]interface{}{"user": user})
Expand Down
2 changes: 2 additions & 0 deletions src/gopher/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ type ConfigStruct struct {
Superusers string `json:"superusers"`
AnalyticsFile string `json:"analytics_file"`
StaticFileVersion int `json:"static_file_version"`
QiniuAccessKey string `json:"qiniu_access_key"`
QiniuSecretKey string `json:"qiniu_secret_key"`
}

var Config ConfigStruct
Expand Down
12 changes: 12 additions & 0 deletions src/gopher/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type User struct {
Username string
Password string
Email string
Avatar string
Website string
Location string
Tagline string
Expand All @@ -40,6 +41,17 @@ type User struct {
Index int
}

// 头像的图片地址
func (u *User) AvatarImgSrc() string {
// 如果没有设置头像,用默认头像
filename := u.Avatar
if filename == "" {
filename = "gopher.jpg"
}

return "http://gopher.qiniudn.com/avatar/" + filename
}

// 用户发表的最近10个主题
func (u *User) LatestTopics() *[]Topic {
c := DB.C("contents")
Expand Down
10 changes: 5 additions & 5 deletions src/gopher/views.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ type Utils struct {
}

func (u *Utils) Gravatar(email string, size uint16) string {
h := md5.New()
io.WriteString(h, email)
return fmt.Sprintf("http://www.gravatar.com/avatar/%x?s=%d", h.Sum(nil), size)
return webhelpers.Gravatar(email, size)
}

func (u *Utils) StaticUrl(path string) string {
Expand Down Expand Up @@ -105,12 +103,12 @@ func (u *Utils) UserInfo(username string) template.HTML {
c.Find(bson.M{"username": username}).One(&user)

format := `<div>
<a href="/member/%s"><img class="gravatar" src="%s" style="float:left;"></a>
<a href="/member/%s"><img class="gravatar" src="%s-middle" style="float:left;"></a>
<h3><a href="/member/%s">%s</a></h3>
<div class="clearfix"></div>
</div>`

return template.HTML(fmt.Sprintf(format, username, u.Gravatar(user.Email, 50), username, username))
return template.HTML(fmt.Sprintf(format, username, user.AvatarImgSrc(), username, username))
}

func (u *Utils) Truncate(html template.HTML, length int) string {
Expand Down Expand Up @@ -299,6 +297,8 @@ func renderTemplate(w http.ResponseWriter, r *http.Request, file string, data ma

data["analyticsCode"] = analyticsCode
data["staticFileVersion"] = Config.StaticFileVersion
flash, _ := store.Get(r, "flash")
data["flash"] = flash

_, ok := data["active"]
if !ok {
Expand Down
75 changes: 75 additions & 0 deletions src/gravatar2qiniu/gravatar2qiniu.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
把用户的Gravatar头像都下载并上传到七牛云存储
*/

package main

import (
"crypto/md5"
"fmt"
"github.com/jimmykuu/webhelpers"
. "github.com/qiniu/api/conf"
qiniu_io "github.com/qiniu/api/io"
"github.com/qiniu/api/rs"
"gopher"
"io"
"labix.org/v2/mgo/bson"
"net/http"
"strings"
)

func main() {
ACCESS_KEY = gopher.Config.QiniuAccessKey
SECRET_KEY = gopher.Config.QiniuSecretKey

extra := &qiniu_io.PutExtra{
Bucket: "gopher",
MimeType: "",
CustomMeta: "",
CallbackParams: "",
}

var policy = rs.PutPolicy{
Scope: "gopher",
}

c := gopher.DB.C("users")
var users []gopher.User
c.Find(nil).Limit(2).All(&users)

for _, user := range users {
url := webhelpers.Gravatar(user.Email, 256)
resp, err := http.Get(url)
if err != nil {
fmt.Println("get gravatar image error:", url, err.Error())
return
}

fmt.Println(url)
// [inline; filename="8c8dbc14a00702dd50e9fd597c2b4df8.jpg"]
temp := strings.Split(resp.Header["Content-Disposition"][0], "=")[1]
filename := string([]byte(temp)[1 : len(temp)-1])
fmt.Println(filename)

h := md5.New()
io.Copy(h, resp.Body)
md5Str := fmt.Sprintf("%x", h.Sum(nil))

if md5Str != "ac83818c6d5b6aca4b6f796b6d3cb338" {
// 不是默认头像,上传
key := "avatar/" + filename
ret := new(qiniu_io.PutRet)

err = qiniu_io.Put(nil, ret, policy.Token(), key, resp.Body, extra)

if err == nil {
c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}})
fmt.Printf("upload %s's avatar success\n", user.Email)
} else {
fmt.Printf("upload %s' avatar error: %s\n", user.Email, err.Error())
}
}

resp.Body.Close()
}
}
Loading

0 comments on commit 82cf432

Please sign in to comment.