2 #include "ytfeedreader.h"
4 #include "networkaccess.h"
5 #include "searchparams.h"
12 YTSearch::YTSearch(SearchParams *searchParams, QObject *parent) :
14 searchParams(searchParams) {
15 searchParams->setParent(this);
18 void YTSearch::loadVideos(int max, int skip) {
21 QUrl url("http://gdata.youtube.com/feeds/api/videos/");
22 url.addQueryItem("v", "2");
24 url.addQueryItem("max-results", QString::number(max));
25 url.addQueryItem("start-index", QString::number(skip));
27 if (!searchParams->keywords().isEmpty()) {
28 if (searchParams->keywords().startsWith("http://") ||
29 searchParams->keywords().startsWith("https://")) {
30 url.addQueryItem("q", YTSearch::videoIdFromUrl(searchParams->keywords()));
31 } else url.addQueryItem("q", searchParams->keywords());
34 if (!searchParams->author().isEmpty())
35 url.addQueryItem("author", searchParams->author());
37 switch (searchParams->sortBy()) {
38 case SearchParams::SortByNewest:
39 url.addQueryItem("orderby", "published");
41 case SearchParams::SortByViewCount:
42 url.addQueryItem("orderby", "viewCount");
44 case SearchParams::SortByRating:
45 url.addQueryItem("orderby", "rating");
49 switch (searchParams->duration()) {
50 case SearchParams::DurationShort:
51 url.addQueryItem("duration", "short");
53 case SearchParams::DurationMedium:
54 url.addQueryItem("duration", "medium");
56 case SearchParams::DurationLong:
57 url.addQueryItem("duration", "long");
61 switch (searchParams->time()) {
62 case SearchParams::TimeToday:
63 url.addQueryItem("time", "today");
65 case SearchParams::TimeWeek:
66 url.addQueryItem("time", "this_week");
68 case SearchParams::TimeMonth:
69 url.addQueryItem("time", "this_month");
73 switch (searchParams->quality()) {
74 case SearchParams::QualityHD:
75 url.addQueryItem("hd", "true");
79 QObject *reply = The::http()->get(url);
80 connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResults(QByteArray)));
81 connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(requestError(QNetworkReply*)));
84 void YTSearch::abort() {
88 const QStringList & YTSearch::getSuggestions() {
92 QString YTSearch::getName() {
93 if (!name.isEmpty()) return name;
94 if (!searchParams->keywords().isEmpty()) return searchParams->keywords();
98 void YTSearch::parseResults(QByteArray data) {
101 YTFeedReader reader(data);
102 QList<Video*> videos = reader.getVideos();
103 suggestions = reader.getSuggestions();
105 if (name.isEmpty() && !searchParams->author().isEmpty()) {
106 if (videos.isEmpty()) name = searchParams->author();
107 else name = videos.first()->author();
108 emit nameChanged(name);
111 emit gotVideos(videos);
112 emit finished(videos.size());
115 void YTSearch::requestError(QNetworkReply *reply) {
116 emit error(reply->errorString());
119 QString YTSearch::videoIdFromUrl(QString url) {
120 QRegExp re = QRegExp("^.*[\\?&]v=([^&#]+).*$");
121 if (re.exactMatch(url)) return re.cap(1);
122 re = QRegExp("^.*://.*/([^&#\\?]+).*$");
123 if (re.exactMatch(url)) return re.cap(1);