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("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());
24 if (!searchParams->author().isEmpty())
25 url.addQueryItem("author", searchParams->author());
27 switch (searchParams->sortBy()) {
28 case SearchParams::SortByNewest:
29 url.addQueryItem("orderby", "published");
31 case SearchParams::SortByViewCount:
32 url.addQueryItem("orderby", "viewCount");
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*)));
42 void YouTubeSearch::error(QNetworkReply *reply) {
43 emit error(reply->errorString());
46 void YouTubeSearch::parseResults(QByteArray data) {
48 YouTubeStreamReader reader;
49 if (!reader.read(data)) {
50 qDebug() << "Error parsing XML";
52 videos = reader.getVideos();
54 foreach (Video *video, videos) {
55 // send it to the model
59 foreach (Video *video, videos) {
61 if (abortFlag) return;
62 video->preloadThumbnail();
65 emit finished(videos.size());
68 QList<Video*> YouTubeSearch::getResults() {
72 void YouTubeSearch::abort() {
73 this->abortFlag = true;
76 QString YouTubeSearch::videoIdFromUrl(QString url) {
77 QRegExp re = QRegExp("^.*\\?v=([^&]+).*$");
78 if (re.exactMatch(url)) {
79 QString videoId = re.cap(1);