1 from __future__
import division
, absolute_import
, unicode_literals
5 from qtpy
import QtCore
7 from qtpy
import QtWidgets
8 from qtpy
import QtNetwork
12 from .compat
import bstr
13 from .compat
import ustr
14 from .compat
import parse
15 from .widgets
import defs
18 class Gravatar(object):
21 def url_for_email(email
, imgsize
):
22 email_hash
= core
.decode(hashlib
.md5(core
.encode(email
)).hexdigest())
23 # Python2.6 requires byte strings for urllib2.quote() so we have
25 default_url
= 'https://git-cola.github.io/images/git-64x64.jpg'
26 encoded_url
= parse
.quote(core
.encode(default_url
), core
.encode(''))
27 query
= '?s=%d&d=%s' % (imgsize
, core
.decode(encoded_url
))
28 url
= 'https://gravatar.com/avatar/' + email_hash
+ query
32 class GravatarLabel(QtWidgets
.QLabel
):
34 def __init__(self
, parent
=None):
35 QtWidgets
.QLabel
.__init
__(self
, parent
)
40 self
.imgsize
= defs
.medium_icon
43 self
.network
= QtNetwork
.QNetworkAccessManager()
44 self
.network
.finished
.connect(self
.network_finished
)
46 def set_email(self
, email
):
47 if email
in self
.pixmaps
:
48 self
.setPixmap(self
.pixmaps
[email
])
50 if (self
.timeout
> 0 and
51 (int(time
.time()) - self
.timeout
) < (5 * 60)):
52 self
.set_pixmap_from_response()
54 if email
== self
.email
and self
.response
is not None:
55 self
.set_pixmap_from_response()
60 def request(self
, email
):
61 url
= Gravatar
.url_for_email(email
, self
.imgsize
)
62 self
.network
.get(QtNetwork
.QNetworkRequest(QtCore
.QUrl(url
)))
64 def default_pixmap_as_bytes(self
):
66 pixmap
= icons
.cola().pixmap(xres
)
67 byte_array
= QtCore
.QByteArray()
68 buf
= QtCore
.QBuffer(byte_array
)
69 buf
.open(QtCore
.QIODevice
.WriteOnly
)
70 pixmap
.save(buf
, 'PNG')
74 def network_finished(self
, reply
):
77 header
= QtCore
.QByteArray(bstr('Location'))
78 location
= ustr(reply
.rawHeader(header
)).strip()
80 request_location
= Gravatar
.url_for_email(self
.email
, self
.imgsize
)
81 relocated
= location
!= request_location
85 if reply
.error() == QtNetwork
.QNetworkReply
.NoError
:
87 # We could do get_url(parse.unquote(location)) to
88 # download the default image.
89 # Save bandwidth by using a pixmap.
90 self
.response
= self
.default_pixmap_as_bytes()
92 self
.response
= reply
.readAll()
95 self
.response
= self
.default_pixmap_as_bytes()
96 self
.timeout
= int(time
.time())
98 pixmap
= self
.set_pixmap_from_response()
100 # If the email has not changed (e.g. no other requests)
101 # then we know that this pixmap corresponds to this specific
102 # email address. We can't blindly trust self.email else
103 # we may add cache entries for thee wrong email address.
104 url
= Gravatar
.url_for_email(email
, self
.imgsize
)
105 if url
== reply
.url().toString():
106 self
.pixmaps
[email
] = pixmap
108 def set_pixmap_from_response(self
):
109 pixmap
= QtGui
.QPixmap()
110 pixmap
.loadFromData(self
.response
)
111 self
.setPixmap(pixmap
)