File indexing completed on 2025-01-05 05:14:50

0001 #include "avatarview.h"
0002 
0003 #include <QCryptographicHash>
0004 #include <QDir>
0005 #include <QNetworkReply>
0006 #include <QNetworkRequest>
0007 #include <QStandardPaths>
0008 
0009 AvatarView::AvatarView(QWidget *parent)
0010     : QLabel{parent}
0011 {
0012     setScaledContents(true);
0013 }
0014 
0015 QString AvatarView::userEmail() const
0016 {
0017     return mUserEmail;
0018 }
0019 
0020 void AvatarView::setUserEmail(const QString &userEmail)
0021 {
0022     mUserEmail = userEmail;
0023 
0024     auto emailHash = QCryptographicHash::hash(userEmail.toLower().toUtf8(), QCryptographicHash::Md5).toHex().toLower();
0025     auto path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/avatars";
0026 
0027     QDir d;
0028     d.mkpath(path);
0029 
0030     mAvatarFileName = path + "/" + emailHash;
0031 
0032     if (QFile::exists(mAvatarFileName)) {
0033         setPixmap(QPixmap{mAvatarFileName});
0034     } else {
0035         auto avatarUrl = "https://www.gravatar.com/avatar/" + emailHash;
0036 
0037         QNetworkRequest request{QUrl{avatarUrl}};
0038 
0039         QNetworkReply *reply = mNet.get(request);
0040         connect(reply, &QNetworkReply::finished, this, &AvatarView::slotAvatarDownloadFinished);
0041     }
0042 }
0043 
0044 void AvatarView::slotAvatarDownloadFinished()
0045 {
0046     auto reply = qobject_cast<QNetworkReply *>(sender());
0047     QFile avatarFile{mAvatarFileName};
0048     if (!avatarFile.open(QIODevice::WriteOnly))
0049         return;
0050     avatarFile.write(reply->readAll());
0051     avatarFile.close();
0052 
0053     setPixmap(QPixmap{mAvatarFileName});
0054 }