avatar.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // for www.gravatar.com image cache
  5. /*
  6. It is recommend to use this way
  7. cacheDir := "./cache"
  8. defaultImg := "./default.jpg"
  9. http.Handle("/avatar/", avatar.HttpHandler(cacheDir, defaultImg))
  10. */
  11. package avatar
  12. import (
  13. "crypto/md5"
  14. "encoding/hex"
  15. "errors"
  16. "fmt"
  17. "image"
  18. "image/jpeg"
  19. "image/png"
  20. "io"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "path/filepath"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/gogits/gogs/modules/log"
  29. "github.com/nfnt/resize"
  30. )
  31. var (
  32. gravatar = "http://www.gravatar.com/avatar"
  33. )
  34. // hash email to md5 string
  35. // keep this func in order to make this package indenpent
  36. func HashEmail(email string) string {
  37. h := md5.New()
  38. h.Write([]byte(strings.ToLower(email)))
  39. return hex.EncodeToString(h.Sum(nil))
  40. }
  41. type Avatar struct {
  42. Hash string
  43. AlterImage string // image path
  44. cacheDir string // image save dir
  45. reqParams string
  46. imagePath string
  47. expireDuration time.Duration
  48. }
  49. func New(hash string, cacheDir string) *Avatar {
  50. return &Avatar{
  51. Hash: hash,
  52. cacheDir: cacheDir,
  53. expireDuration: time.Minute * 10,
  54. reqParams: url.Values{
  55. "d": {"retro"},
  56. "size": {"200"},
  57. "r": {"pg"}}.Encode(),
  58. imagePath: filepath.Join(cacheDir, hash+".image"), //maybe png or jpeg
  59. }
  60. }
  61. func (this *Avatar) HasCache() bool {
  62. fileInfo, err := os.Stat(this.imagePath)
  63. return err == nil && fileInfo.Mode().IsRegular()
  64. }
  65. func (this *Avatar) Modtime() (modtime time.Time, err error) {
  66. fileInfo, err := os.Stat(this.imagePath)
  67. if err != nil {
  68. return
  69. }
  70. return fileInfo.ModTime(), nil
  71. }
  72. func (this *Avatar) Expired() bool {
  73. modtime, err := this.Modtime()
  74. return err != nil || time.Since(modtime) > this.expireDuration
  75. }
  76. // default image format: jpeg
  77. func (this *Avatar) Encode(wr io.Writer, size int) (err error) {
  78. var img image.Image
  79. decodeImageFile := func(file string) (img image.Image, err error) {
  80. fd, err := os.Open(file)
  81. if err != nil {
  82. return
  83. }
  84. defer fd.Close()
  85. img, err = jpeg.Decode(fd)
  86. if err != nil {
  87. fd.Seek(0, os.SEEK_SET)
  88. img, err = png.Decode(fd)
  89. }
  90. return
  91. }
  92. imgPath := this.imagePath
  93. if !this.HasCache() {
  94. if this.AlterImage == "" {
  95. return errors.New("request image failed, and no alt image offered")
  96. }
  97. imgPath = this.AlterImage
  98. }
  99. img, err = decodeImageFile(imgPath)
  100. if err != nil {
  101. return
  102. }
  103. m := resize.Resize(uint(size), 0, img, resize.Lanczos3)
  104. return jpeg.Encode(wr, m, nil)
  105. }
  106. // get image from gravatar.com
  107. func (this *Avatar) Update() {
  108. thunder.Fetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
  109. this.imagePath)
  110. }
  111. func (this *Avatar) UpdateTimeout(timeout time.Duration) error {
  112. var err error
  113. select {
  114. case <-time.After(timeout):
  115. err = fmt.Errorf("get gravatar image %s timeout", this.Hash)
  116. case err = <-thunder.GoFetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
  117. this.imagePath):
  118. }
  119. return err
  120. }
  121. type avatarHandler struct {
  122. cacheDir string
  123. altImage string
  124. }
  125. func (this *avatarHandler) mustInt(r *http.Request, defaultValue int, keys ...string) int {
  126. var v int
  127. for _, k := range keys {
  128. if _, err := fmt.Sscanf(r.FormValue(k), "%d", &v); err == nil {
  129. defaultValue = v
  130. }
  131. }
  132. return defaultValue
  133. }
  134. func (this *avatarHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  135. urlPath := r.URL.Path
  136. hash := urlPath[strings.LastIndex(urlPath, "/")+1:]
  137. size := this.mustInt(r, 80, "s", "size") // default size = 80*80
  138. avatar := New(hash, this.cacheDir)
  139. avatar.AlterImage = this.altImage
  140. if avatar.Expired() {
  141. err := avatar.UpdateTimeout(time.Millisecond * 500)
  142. if err != nil {
  143. log.Trace("avatar update error: %v", err)
  144. }
  145. }
  146. if modtime, err := avatar.Modtime(); err == nil {
  147. etag := fmt.Sprintf("size(%d)", size)
  148. if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modtime.Before(t.Add(1*time.Second)) && etag == r.Header.Get("If-None-Match") {
  149. h := w.Header()
  150. delete(h, "Content-Type")
  151. delete(h, "Content-Length")
  152. w.WriteHeader(http.StatusNotModified)
  153. return
  154. }
  155. w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat))
  156. w.Header().Set("ETag", etag)
  157. }
  158. w.Header().Set("Content-Type", "image/jpeg")
  159. err := avatar.Encode(w, size)
  160. if err != nil {
  161. log.Warn("avatar encode error: %v", err)
  162. w.WriteHeader(500)
  163. }
  164. }
  165. // http.Handle("/avatar/", avatar.HttpHandler("./cache"))
  166. func HttpHandler(cacheDir string, defaultImgPath string) http.Handler {
  167. return &avatarHandler{
  168. cacheDir: cacheDir,
  169. altImage: defaultImgPath,
  170. }
  171. }
  172. // thunder downloader
  173. var thunder = &Thunder{QueueSize: 10}
  174. type Thunder struct {
  175. QueueSize int // download queue size
  176. q chan *thunderTask
  177. once sync.Once
  178. }
  179. func (t *Thunder) init() {
  180. if t.QueueSize < 1 {
  181. t.QueueSize = 1
  182. }
  183. t.q = make(chan *thunderTask, t.QueueSize)
  184. for i := 0; i < t.QueueSize; i++ {
  185. go func() {
  186. for {
  187. task := <-t.q
  188. task.Fetch()
  189. }
  190. }()
  191. }
  192. }
  193. func (t *Thunder) Fetch(url string, saveFile string) error {
  194. t.once.Do(t.init)
  195. task := &thunderTask{
  196. Url: url,
  197. SaveFile: saveFile,
  198. }
  199. task.Add(1)
  200. t.q <- task
  201. task.Wait()
  202. return task.err
  203. }
  204. func (t *Thunder) GoFetch(url, saveFile string) chan error {
  205. c := make(chan error)
  206. go func() {
  207. c <- t.Fetch(url, saveFile)
  208. }()
  209. return c
  210. }
  211. // thunder download
  212. type thunderTask struct {
  213. Url string
  214. SaveFile string
  215. sync.WaitGroup
  216. err error
  217. }
  218. func (this *thunderTask) Fetch() {
  219. this.err = this.fetch()
  220. this.Done()
  221. }
  222. var client = &http.Client{}
  223. func (this *thunderTask) fetch() error {
  224. req, _ := http.NewRequest("GET", this.Url, nil)
  225. req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8")
  226. req.Header.Set("Accept-Encoding", "deflate,sdch")
  227. req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
  228. req.Header.Set("Cache-Control", "no-cache")
  229. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36")
  230. resp, err := client.Do(req)
  231. if err != nil {
  232. return err
  233. }
  234. defer resp.Body.Close()
  235. if resp.StatusCode != 200 {
  236. return fmt.Errorf("status code: %d", resp.StatusCode)
  237. }
  238. /*
  239. log.Println("headers:", resp.Header)
  240. switch resp.Header.Get("Content-Type") {
  241. case "image/jpeg":
  242. this.SaveFile += ".jpeg"
  243. case "image/png":
  244. this.SaveFile += ".png"
  245. }
  246. */
  247. /*
  248. imgType := resp.Header.Get("Content-Type")
  249. if imgType != "image/jpeg" && imgType != "image/png" {
  250. return errors.New("not png or jpeg")
  251. }
  252. */
  253. tmpFile := this.SaveFile + ".part" // mv to destination when finished
  254. fd, err := os.Create(tmpFile)
  255. if err != nil {
  256. return err
  257. }
  258. _, err = io.Copy(fd, resp.Body)
  259. fd.Close()
  260. if err != nil {
  261. os.Remove(tmpFile)
  262. return err
  263. }
  264. return os.Rename(tmpFile, this.SaveFile)
  265. }