File: lyricswidget.cpp

package info (click to toggle)
juk 4%3A25.08.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,236 kB
  • sloc: cpp: 14,818; xml: 763; makefile: 5; sh: 2
file content (184 lines) | stat: -rw-r--r-- 6,441 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/**
 * Copyright (C) 2012 Martin Sandsmark <martin.sandsmark@kde.org>
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "lyricswidget.h"

#include <KActionCollection>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KSharedConfig>
#include <KToggleAction>
#include <QAction>
#include <QDomDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrlQuery>

#include "actioncollection.h"
#include "iconsupport.h"
#include "juk_debug.h"
#include "juktag.h"

static const QUrl BASE_LYRICS_URL = QUrl("https://lyrics.fandom.com/");

using namespace IconSupport; // ""_icon
using namespace ActionCollection; // ""_act

LyricsWidget::LyricsWidget(QWidget* parent)
  : QTextBrowser(parent)
  , m_networkAccessManager(new QNetworkAccessManager)
  , m_lyricsCurrent(false)
{
    setMinimumWidth(200);
    setReadOnly(true);
    setWordWrapMode(QTextOption::WordWrap);
    setOpenExternalLinks(true);

    KToggleAction *show = new KToggleAction("view-media-lyrics"_icon,
                                            i18n("Show &Lyrics"), this);
    ActionCollection::actions()->addAction("showLyrics", show);
    connect(show, SIGNAL(toggled(bool)), this, SLOT(setVisible(bool)));

    KConfigGroup config(KSharedConfig::openConfig(), "LyricsWidget");
    bool shown = config.readEntry("Show", true);
    show->setChecked(shown);
    setVisible(shown);
}

LyricsWidget::~LyricsWidget()
{
    delete m_networkAccessManager;
    saveConfig();
}

void LyricsWidget::saveConfig()
{
    KConfigGroup config(KSharedConfig::openConfig(), "LyricsWidget");
    config.writeEntry("Show", "showLyrics"_act->isChecked());
}

void LyricsWidget::makeLyricsRequest()
{
    m_lyricsCurrent = true;

    if(m_playingFile.isNull()) {
        setHtml(i18n("<i>No file playing.</i>"));
        return;
    }

    m_title = m_playingFile.tag()->artist() + " &#8211; " + m_playingFile.tag()->title();
    setHtml(i18n("<i>Loading...</i>"));

    // lyrics.fandom.com seems to be unavailable as well now so give a better error message
    // and stop pinging the server
    if(1) {
        setHtml(i18n("<i>Lyrics are currently unavailable for %1 (no available lyrics provider)</i>", m_title));
        return;
    }

    QUrl listUrl = BASE_LYRICS_URL;
    listUrl.setPath("/api.php");

    QUrlQuery listUrlQuery;
    listUrlQuery.addQueryItem("action", "lyrics");
    listUrlQuery.addQueryItem("func", "getSong");
    listUrlQuery.addQueryItem("fmt", "xml");
    listUrlQuery.addQueryItem("artist", m_playingFile.tag()->artist());
    listUrlQuery.addQueryItem("song", m_playingFile.tag()->title());
    listUrl.setQuery(listUrlQuery);

    connect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(receiveListReply(QNetworkReply*)));
    m_networkAccessManager->get(QNetworkRequest(listUrl));
}

void LyricsWidget::playing(const FileHandle &file)
{
    m_playingFile = file;
    m_lyricsCurrent = false;

    if(isVisible()) {
        makeLyricsRequest();
    }
}

void LyricsWidget::showEvent(QShowEvent *)
{
    if(!m_lyricsCurrent) {
        makeLyricsRequest();
    }
}

void LyricsWidget::receiveListReply(QNetworkReply* reply)
{
    disconnect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(receiveListReply(QNetworkReply*)));
    if (reply->error() != QNetworkReply::NoError) {
        qCWarning(JUK_LOG) << "Error while fetching lyrics: " << reply->errorString();
        setHtml(i18n("<span style='color:red'>Error while retrieving lyrics!</span>"));
        return;
    }

    QDomDocument document;
    document.setContent(reply);
    QString artist = document.elementsByTagName("artist").at(0).toElement().text();
    QString title = document.elementsByTagName("song").at(0).toElement().text();

    QUrl url = BASE_LYRICS_URL;
    url.setPath("/api.php");

    QUrlQuery urlQuery;
    urlQuery.addQueryItem("action", "query");
    urlQuery.addQueryItem("prop", "revisions");
    urlQuery.addQueryItem("rvprop", "content");
    urlQuery.addQueryItem("format", "xml");
    urlQuery.addQueryItem("titles", artist + ':' + title);
    url.setQuery(urlQuery);

    connect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(receiveLyricsReply(QNetworkReply*)));
    m_networkAccessManager->get(QNetworkRequest(url));
}

void LyricsWidget::receiveLyricsReply(QNetworkReply* reply)
{
    disconnect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(receiveLyricsReply(QNetworkReply*)));
    if (reply->error() != QNetworkReply::NoError) {
        qCWarning(JUK_LOG) << "Error while fetching lyrics: " << reply->errorString();
        setHtml(i18n("<span style='color:red'>Error while retrieving lyrics!</span>"));
        return;
    }
    const QUrlQuery replyUrlQuery(reply->url());
    QString titlesUrlPart = replyUrlQuery.queryItemValue(QStringLiteral("titles"), QUrl::FullyEncoded);
    if (titlesUrlPart.isEmpty()) {
        // default homepage, but this code path should never happen at this point.
        titlesUrlPart = QStringLiteral("Lyrics_Wiki");
    }
    const QString lyricsUrl = BASE_LYRICS_URL.toString() + QStringLiteral("wiki/") + titlesUrlPart;

    QString content = QString::fromUtf8(reply->readAll());
    int lIndex = content.indexOf("&lt;lyrics&gt;");
    int rIndex = content.indexOf("&lt;/lyrics&gt;");
    if (lIndex == -1 || rIndex == -1) {
        qCWarning(JUK_LOG) << Q_FUNC_INFO << "Unable to find lyrics in text";
        setText(i18n("No lyrics available."));
        return;
    }
    lIndex += 15; // We skip the tag
    content = content.mid(lIndex, rIndex - lIndex).trimmed();
    content.replace('\n', "<br />");
    //setText(content);
    setHtml("<h1>" + m_title + "</h1>" +
            content +
            i18n("<br /><br /><i>Lyrics provided by <a href='%1'>LyricWiki</a></i>", lyricsUrl));
}