]> git.sur5r.net Git - minitube/blob - src/ytcategories.cpp
92e2dbc5db61933350371c66e43e410cd180fa72
[minitube] / src / ytcategories.cpp
1 #include "ytcategories.h"
2 #include "networkaccess.h"
3 #include <QtXml>
4
5 namespace The {
6 NetworkAccess* http();
7 }
8
9 YTCategories::YTCategories(QObject *parent) : QObject(parent) { }
10
11 void YTCategories::loadCategories(QString language) {
12     if (language.isEmpty())
13         language = QLocale::system().uiLanguages().first();
14     lastLanguage = language;
15
16     QString url = "http://gdata.youtube.com/schemas/2007/categories.cat?hl=" + language;
17     QObject *reply = The::http()->get(url);
18     connect(reply, SIGNAL(data(QByteArray)), SLOT(parseCategories(QByteArray)));
19     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(requestError(QNetworkReply*)));
20 }
21
22 void YTCategories::parseCategories(QByteArray bytes) {
23     QList<YTCategory> categories;
24
25     QXmlStreamReader xml(bytes);
26     while (!xml.atEnd()) {
27         xml.readNext();
28         if (xml.isStartElement() && xml.name() == QLatin1String("category")) {
29             QString term = xml.attributes().value("term").toString();
30             QString label = xml.attributes().value("label").toString();
31             while(xml.readNextStartElement())
32                 if (xml.name() == QLatin1String("assignable")) {
33                     YTCategory category;
34                     category.term = term;
35                     category.label = label;
36                     categories << category;
37                 } else xml.skipCurrentElement();
38         }
39     }
40
41     if (xml.hasError()) {
42         emit error(xml.errorString());
43         return;
44     }
45
46     emit categoriesLoaded(categories);
47 }
48
49 void YTCategories::requestError(QNetworkReply *reply) {
50     if (lastLanguage != "en") loadCategories("en");
51     else emit error(reply->errorString());
52 }