avatar.go 7.0 KB

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