]> git.sur5r.net Git - minitube/blob - src/youtubesearch.cpp
664240b4fc62e11b705f111c303b467e3ffbe695
[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     QString urlString = QString(
16             "http://gdata.youtube.com/feeds/api/videos?q=%1&max-results=%2&start-index=%3")
17             .arg(searchParams->keywords(), QString::number(max), QString::number(skip));
18
19     // Useful to test with a local webserver
20     /*
21     urlString = QString("http://localhost/oringo/video.xml?q=%1&max-results=%2&start-index=%3")
22                 .arg(searchParams->keywords(), QString::number(max), QString::number(skip));
23                 */
24
25     switch (searchParams->sortBy()) {
26     case SearchParams::SortByNewest:
27         urlString.append("&orderby=published");
28         break;
29     case SearchParams::SortByViewCount:
30         urlString.append("&orderby=viewCount");
31         break;
32     }
33
34     QUrl url(urlString);
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 }