You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

avatar.go 6.7KB

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.CacheServer(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/nfnt/resize"
  29. "github.com/gogits/gogs/modules/log"
  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. // Avatar represents the avatar object.
  42. type Avatar struct {
  43. Hash string
  44. AlterImage string // image path
  45. cacheDir string // image save dir
  46. reqParams string
  47. imagePath string
  48. expireDuration time.Duration
  49. }
  50. func New(hash string, cacheDir string) *Avatar {
  51. return &Avatar{
  52. Hash: hash,
  53. cacheDir: cacheDir,
  54. expireDuration: time.Minute * 10,
  55. reqParams: url.Values{
  56. "d": {"retro"},
  57. "size": {"200"},
  58. "r": {"pg"}}.Encode(),
  59. imagePath: filepath.Join(cacheDir, hash+".image"), //maybe png or jpeg
  60. }
  61. }
  62. func (this *Avatar) HasCache() bool {
  63. fileInfo, err := os.Stat(this.imagePath)
  64. return err == nil && fileInfo.Mode().IsRegular()
  65. }
  66. func (this *Avatar) Modtime() (modtime time.Time, err error) {
  67. fileInfo, err := os.Stat(this.imagePath)
  68. if err != nil {
  69. return
  70. }
  71. return fileInfo.ModTime(), nil
  72. }
  73. func (this *Avatar) Expired() bool {
  74. modtime, err := this.Modtime()
  75. return err != nil || time.Since(modtime) > this.expireDuration
  76. }
  77. // default image format: jpeg
  78. func (this *Avatar) Encode(wr io.Writer, size int) (err error) {
  79. var img image.Image
  80. decodeImageFile := func(file string) (img image.Image, err error) {
  81. fd, err := os.Open(file)
  82. if err != nil {
  83. return
  84. }
  85. defer fd.Close()
  86. if img, err = jpeg.Decode(fd); 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. if img, err = decodeImageFile(imgPath); err != nil {
  100. return
  101. }
  102. m := resize.Resize(uint(size), 0, img, resize.Lanczos3)
  103. return jpeg.Encode(wr, m, nil)
  104. }
  105. // get image from gravatar.com
  106. func (this *Avatar) Update() {
  107. thunder.Fetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
  108. this.imagePath)
  109. }
  110. func (this *Avatar) UpdateTimeout(timeout time.Duration) (err error) {
  111. select {
  112. case <-time.After(timeout):
  113. err = fmt.Errorf("get gravatar image %s timeout", this.Hash)
  114. case err = <-thunder.GoFetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
  115. this.imagePath):
  116. }
  117. return err
  118. }
  119. type service struct {
  120. cacheDir string
  121. altImage string
  122. }
  123. func (this *service) mustInt(r *http.Request, defaultValue int, keys ...string) (v int) {
  124. for _, k := range keys {
  125. if _, err := fmt.Sscanf(r.FormValue(k), "%d", &v); err == nil {
  126. defaultValue = v
  127. }
  128. }
  129. return defaultValue
  130. }
  131. func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  132. urlPath := r.URL.Path
  133. hash := urlPath[strings.LastIndex(urlPath, "/")+1:]
  134. size := this.mustInt(r, 80, "s", "size") // default size = 80*80
  135. avatar := New(hash, this.cacheDir)
  136. avatar.AlterImage = this.altImage
  137. if avatar.Expired() {
  138. err := avatar.UpdateTimeout(time.Millisecond * 500)
  139. if err != nil {
  140. log.Trace("avatar update error: %v", err)
  141. }
  142. }
  143. if modtime, err := avatar.Modtime(); err == nil {
  144. etag := fmt.Sprintf("size(%d)", size)
  145. 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") {
  146. h := w.Header()
  147. delete(h, "Content-Type")
  148. delete(h, "Content-Length")
  149. w.WriteHeader(http.StatusNotModified)
  150. return
  151. }
  152. w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat))
  153. w.Header().Set("ETag", etag)
  154. }
  155. w.Header().Set("Content-Type", "image/jpeg")
  156. if err := avatar.Encode(w, size); err != nil {
  157. log.Warn("avatar encode error: %v", err)
  158. w.WriteHeader(500)
  159. }
  160. }
  161. // http.Handle("/avatar/", avatar.CacheServer("./cache"))
  162. func CacheServer(cacheDir string, defaultImgPath string) http.Handler {
  163. return &service{
  164. cacheDir: cacheDir,
  165. altImage: defaultImgPath,
  166. }
  167. }
  168. // thunder downloader
  169. var thunder = &Thunder{QueueSize: 10}
  170. type Thunder struct {
  171. QueueSize int // download queue size
  172. q chan *thunderTask
  173. once sync.Once
  174. }
  175. func (t *Thunder) init() {
  176. if t.QueueSize < 1 {
  177. t.QueueSize = 1
  178. }
  179. t.q = make(chan *thunderTask, t.QueueSize)
  180. for i := 0; i < t.QueueSize; i++ {
  181. go func() {
  182. for {
  183. task := <-t.q
  184. task.Fetch()
  185. }
  186. }()
  187. }
  188. }
  189. func (t *Thunder) Fetch(url string, saveFile string) error {
  190. t.once.Do(t.init)
  191. task := &thunderTask{
  192. Url: url,
  193. SaveFile: saveFile,
  194. }
  195. task.Add(1)
  196. t.q <- task
  197. task.Wait()
  198. return task.err
  199. }
  200. func (t *Thunder) GoFetch(url, saveFile string) chan error {
  201. c := make(chan error)
  202. go func() {
  203. c <- t.Fetch(url, saveFile)
  204. }()
  205. return c
  206. }
  207. // thunder download
  208. type thunderTask struct {
  209. Url string
  210. SaveFile string
  211. sync.WaitGroup
  212. err error
  213. }
  214. func (this *thunderTask) Fetch() {
  215. this.err = this.fetch()
  216. this.Done()
  217. }
  218. var client = &http.Client{}
  219. func (this *thunderTask) fetch() error {
  220. req, _ := http.NewRequest("GET", this.Url, nil)
  221. req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8")
  222. req.Header.Set("Accept-Encoding", "deflate,sdch")
  223. req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
  224. req.Header.Set("Cache-Control", "no-cache")
  225. 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")
  226. resp, err := client.Do(req)
  227. if err != nil {
  228. return err
  229. }
  230. defer resp.Body.Close()
  231. if resp.StatusCode != 200 {
  232. return fmt.Errorf("status code: %d", resp.StatusCode)
  233. }
  234. /*
  235. log.Println("headers:", resp.Header)
  236. switch resp.Header.Get("Content-Type") {
  237. case "image/jpeg":
  238. this.SaveFile += ".jpeg"
  239. case "image/png":
  240. this.SaveFile += ".png"
  241. }
  242. */
  243. /*
  244. imgType := resp.Header.Get("Content-Type")
  245. if imgType != "image/jpeg" && imgType != "image/png" {
  246. return errors.New("not png or jpeg")
  247. }
  248. */
  249. tmpFile := this.SaveFile + ".part" // mv to destination when finished
  250. fd, err := os.Create(tmpFile)
  251. if err != nil {
  252. return err
  253. }
  254. _, err = io.Copy(fd, resp.Body)
  255. fd.Close()
  256. if err != nil {
  257. os.Remove(tmpFile)
  258. return err
  259. }
  260. return os.Rename(tmpFile, this.SaveFile)
  261. }