]> git.sur5r.net Git - minitube/blob - src/youtubesearch.cpp
5eced6080b0bbc4b471a1f8fe33ea4d0466fc6c8
[minitube] / src / youtubesearch.cpp
1 #include "youtubesearch.h"
2 #include "youtubestreamreader.h"
3 #include "constants.h"
4 #include "networkaccess.h"
5
6 namespace The {
7     NetworkAccess* http();
8 }
9
10 YouTubeSearch::YouTubeSearch() : QObject() {}
11
12 void YouTubeSearch::search(SearchParams *searchParams, int max, int skip) {
13     this->abortFlag = false;
14
15     QUrl url("http://gdata.youtube.com/feeds/api/videos/");
16     url.addQueryItem("max-results", QString::number(max));
17     url.addQueryItem("start-index", QString::number(skip));
18     if (!searchParams->keywords().isEmpty()) {
19         if (searchParams->keywords().startsWith("http://") ||
20                 searchParams->keywords().startsWith("https://")) {
21             url.addQueryItem("q", YouTubeSearch::videoIdFromUrl(searchParams->keywords()));
22         } else url.addQueryItem("q", searchParams->keywords());
23     }
24     if (!searchParams->author().isEmpty())
25         url.addQueryItem("author", searchParams->author());
26
27     switch (searchParams->sortBy()) {
28     case SearchParams::SortByNewest:
29         url.addQueryItem("orderby", "published");
30         break;
31     case SearchParams::SortByViewCount:
32         url.addQueryItem("orderby", "viewCount");
33         break;
34     }
35
36     QObject *reply = The::http()->get(url);
37     connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResults(QByteArray)));
38     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(error(QNetworkReply*)));
39
40 }
41
42 void YouTubeSearch::error(QNetworkReply *reply) {
43     emit error(reply->errorString());
44 }
45
46 void YouTubeSearch::parseResults(QByteArray data) {
47
48     YouTubeStreamReader reader;
49     if (!reader.read(data)) {
50         qDebug() << "Error parsing XML";
51     }
52     videos = reader.getVideos();
53
54     foreach (Video *video, videos) {
55         // send it to the model
56         emit gotVideo(video);
57     }
58
59     foreach (Video *video, videos) {
60         // preload the thumb
61         if (abortFlag) return;
62         video->preloadThumbnail();
63     }
64
65     emit finished(videos.size());
66 }
67
68 QList<Video*> YouTubeSearch::getResults() {
69     return videos;
70 }
71
72 void YouTubeSearch::abort() {
73     this->abortFlag = true;
74 }
75
76 QString YouTubeSearch::videoIdFromUrl(QString url) {
77     QRegExp re = QRegExp("^.*\\?v=([^&]+).*$");
78     if (re.exactMatch(url)) {
79         QString videoId = re.cap(1);
80         videoId.remove('-');
81         return videoId;
82     }
83     return QString();
84 }