1 #include "youtubesearch.h"
2 #include "youtubestreamreader.h"
4 #include "networkaccess.h"
10 YouTubeSearch::YouTubeSearch() : QObject() {}
12 void YouTubeSearch::search(SearchParams *searchParams, int max, int skip) {
13 this->abortFlag = false;
15 QUrl url("http://gdata.youtube.com/feeds/api/videos/");
16 url.addQueryItem("v", "2");
18 url.addQueryItem("max-results", QString::number(max));
19 url.addQueryItem("start-index", QString::number(skip));
21 if (!searchParams->keywords().isEmpty()) {
22 if (searchParams->keywords().startsWith("http://") ||
23 searchParams->keywords().startsWith("https://")) {
24 url.addQueryItem("q", YouTubeSearch::videoIdFromUrl(searchParams->keywords()));
25 } else url.addQueryItem("q", searchParams->keywords());
28 if (!searchParams->author().isEmpty())
29 url.addQueryItem("author", searchParams->author());
31 switch (searchParams->sortBy()) {
32 case SearchParams::SortByNewest:
33 url.addQueryItem("orderby", "published");
35 case SearchParams::SortByViewCount:
36 url.addQueryItem("orderby", "viewCount");
38 case SearchParams::SortByRating:
39 url.addQueryItem("orderby", "rating");
43 switch (searchParams->duration()) {
44 case SearchParams::DurationShort:
45 url.addQueryItem("duration", "short");
47 case SearchParams::DurationMedium:
48 url.addQueryItem("duration", "medium");
50 case SearchParams::DurationLong:
51 url.addQueryItem("duration", "long");
55 switch (searchParams->time()) {
56 case SearchParams::TimeToday:
57 url.addQueryItem("time", "today");
59 case SearchParams::TimeWeek:
60 url.addQueryItem("time", "this_week");
62 case SearchParams::TimeMonth:
63 url.addQueryItem("time", "this_month");
67 switch (searchParams->quality()) {
68 case SearchParams::QualityHD:
69 url.addQueryItem("hd", "true");
73 QObject *reply = The::http()->get(url);
74 connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResults(QByteArray)));
75 connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(error(QNetworkReply*)));
79 void YouTubeSearch::error(QNetworkReply *reply) {
80 emit error(reply->errorString());
83 void YouTubeSearch::parseResults(QByteArray data) {
85 YouTubeStreamReader reader;
86 if (!reader.read(data)) {
87 qDebug() << "Error parsing XML";
89 videos = reader.getVideos();
90 suggestions = reader.getSuggestions();
92 foreach (Video *video, videos) {
93 // send it to the model
97 foreach (Video *video, videos) {
99 if (abortFlag) return;
100 video->preloadThumbnail();
103 emit finished(videos.size());
106 QList<Video*> YouTubeSearch::getResults() {
110 const QStringList & YouTubeSearch::getSuggestions() const {
114 void YouTubeSearch::abort() {
115 this->abortFlag = true;
118 QString YouTubeSearch::videoIdFromUrl(QString url) {
119 QRegExp re = QRegExp("^.*\\?v=([^&]+).*$");
120 if (re.exactMatch(url)) {
121 QString videoId = re.cap(1);