1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
|
/*
* Copyright 2015 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Scott Sweeny
*/
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <scope/localization.h>
#include <scope/query.h>
#include <unity/scopes/Annotation.h>
#include <unity/scopes/CategorisedResult.h>
#include <unity/scopes/CategoryRenderer.h>
#include <unity/scopes/Department.h>
#include <unity/scopes/QueryBase.h>
#include <unity/scopes/CannedQuery.h>
#include <unity/scopes/SearchReply.h>
#include <unity/scopes/VariantBuilder.h>
#include <unity/scopes/SearchMetadata.h>
#include <iomanip>
#include <sstream>
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>
namespace sc = unity::scopes;
namespace alg = boost::algorithm;
using namespace std;
using namespace api;
using namespace scope;
std::string FIRST_NEWS_LAYOUT = R"(
{
"schema-version" : 1,
"template" : {
"category-layout" : "grid",
"card-size": "large",
"overlay": true
},
"components" : {
"title" : "title",
"art" : {
"field": "art",
"aspect-ratio": 2.1
}
}
}
)";
std::string NEWS_LAYOUT = R"(
{
"schema-version" : 1,
"template" : {
"category-layout" : "vertical-journal",
"card-layout": "horizontal",
"card-size": "small"
},
"components" : {
"title" : "title",
"subtitle":"published",
"summary":"summary",
"art":"art"
}
}
)";
std::string ERROR_GRID = R"(
{
"schema-version" : 1,
"template" : {
"category-layout" : "grid",
"card-layout": "horizontal",
"card-size": "small"
},
"components" : {
"title" : "title",
"mascot":"art",
"art" : {
"field": "art",
"aspect-ratio": 1.6,
"fill-mode": "fit"
}
}
}
)";
QString Query::getDepartments(QString filePath, sc::SearchReplyProxy const& reply) {
sc::DepartmentList depts;
QString rootDeptUrl;
// Read department names and URLs from the file
QFile departmentsFile(filePath);
if (!departmentsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Departments file" << filePath << "not found";
return "";
}
QByteArray data = departmentsFile.readAll();
departmentsFile.close();
QJsonDocument doc = QJsonDocument::fromJson(data);
if (doc.isNull()){
qWarning() << "JSON parsing failed";
return "";
}
QJsonArray results = doc.array();
sc::CannedQuery myquery(SCOPE_NAME);
myquery.set_department_id("");
sc::Department::SPtr topDept;
auto value = results[0];
auto obj = value.toObject();
rootDeptUrl = obj["id"].toString();
topDept = move(sc::Department::create("",myquery,obj["label"].toString().toStdString()));
insert_keyword_feed(obj["keyword"].toString().toStdString(), rootDeptUrl.toStdString());
if (results.size() > 1) {
for (int i = 1; i < results.size(); ++i)
{
auto value = results[i];
auto obj = value.toObject();
sc::Department::SPtr aDept= move(sc::Department::create(obj["id"].toString().toStdString(),\
myquery,obj["label"].toString().toStdString()));
depts.insert(depts.end(),aDept);
insert_keyword_feed(obj["keyword"].toString().toStdString(), aDept->id());
}
topDept->set_subdepartments(depts);
reply->register_departments(topDept);
}
return rootDeptUrl;
}
void Query::insert_keyword_feed(const string& keyword, const string& feed_url) {
if (!keyword.empty()) {
keyword_feeds_.insert( pair<string, string>(keyword, feed_url) );
}
}
pair<string,string> Query::find_url_for_keywords(const set<string>& search_keywords) {
for(const string& search_keyword : search_keywords) {
auto it = keyword_feeds_.find(search_keyword);
if (it != keyword_feeds_.end()) {
const string& found_url = it->second;
return std::pair<string, string>(search_keyword, found_url);
}
}
return std::pair<string, string>{};
}
Query::Query(const sc::CannedQuery &query,
const sc::SearchMetadata &search_metadata,
const string& scope_directory,
const QSharedPointer<QSettings>& scopeConfig)
: sc::SearchQueryBase(query, search_metadata)
, client_{}
, scope_directory_{scope_directory}
, mScopeConfig{scopeConfig} {
}
void Query::cancelled() {
client_.cancel();
}
void Query::run(sc::SearchReplyProxy const& reply) {
try {
// Start by getting information about the query
const sc::CannedQuery &query(sc::SearchQueryBase::query());
// Trim the query string of whitespace
string query_string = alg::trim_copy(query.query_string());
// Get the departments
QString deptFile = QString::fromStdString(scope_directory_) + "/feeds.json";
string feedUrl = getDepartments(deptFile, reply).toStdString(); // feedUrl has the root URL
// Check if the search comes from an aggregator scope
const sc::SearchMetadata &meta(sc::SearchQueryBase::search_metadata());
string found_keyword; // this var will store the keyword related with a found url in case of agg. scope search.
if (meta.is_aggregated()) {
auto found_pair = find_url_for_keywords(meta.aggregated_keywords());
found_keyword = found_pair.first;
feedUrl = found_pair.second;
} else {
// If the current dept ID is empty use the root URL otherwise use
// the dept ID, which should be a department feed URL
if (!query.department_id().empty()) {
feedUrl = query.department_id();
}
}
if (feedUrl.empty()) {
// We can't proceed if we don't have a feed URL
qWarning() << "No feed URL found";
return;
}
vector<Client::Item> results = client_.getItems(feedUrl);
// Register a category for the common news
auto news_cat = reply->register_category("news",
"", "", sc::CategoryRenderer(NEWS_LAYOUT));
auto first_news_cat = reply->register_category("first_news",
"", "", sc::CategoryRenderer(FIRST_NEWS_LAYOUT));
if (results.size() > 0) {
// Get common values for all results to avoid asking for them in every iteration
std::string emblem = get_emblem();
std::string date_time_format = get_date_time_format();
bool show_big_result = get_big_first_result();
// For each of the results vector items
for (const auto &item : results) {
// Filter by search term if we have one
if (!query_string.empty()) {
QString qry = QString::fromStdString(query_string);
QString title = QString::fromStdString(item.title);
QString summary = QString::fromStdString(item.summary);
QString content = QString::fromStdString(item.content);
if (!title.contains(qry, Qt::CaseInsensitive) &&
!summary.contains(qry, Qt::CaseInsensitive) &&
!content.contains(qry, Qt::CaseInsensitive)) {
continue;
}
}
// Create a result if having title at least
if (!item.title.empty() && !item.uri.empty()) {
// If surfacing in not aggregated mode and set big-first-result setting to true, show first result in big
sc::Category::SCPtr cat =
show_big_result && !meta.is_aggregated() && query_string.empty() ?
first_news_cat :
news_cat;
show_big_result = false;
sc::CategorisedResult res(cat);
// We must have a URI
res.set_uri(item.uri);
res.set_dnd_uri(item.uri);
// Set the rest of the attributes
res.set_title(item.title);
res.set_art(item.art);
res["author"] = sc::Variant(item.author);
res["summary"] = sc::Variant(item.summary);
res["content"] = sc::Variant(item.content);
res["emblem"] = sc::Variant(emblem);
if (res.art().empty()) {
res.set_art(get_icon());
}
QString date = QString::fromStdString(item.published);
if (!date.isEmpty()){
QDateTime ipostTime = QDateTime::fromString(date, Qt::ISODate);
QString readableTime = ipostTime.toString(QString::fromStdString(date_time_format));
res["published"] = readableTime.toStdString();
}
// if searched from aggregated, set formatted date to subtitle in case found keyword is related with news
if (meta.is_aggregated()) {
if (boost::starts_with(found_keyword, "news.")) {
res["subtitle"] = res["published"];
}
}
sc::VariantBuilder actions;
actions.add_tuple({
{"id", sc::Variant("open")},
{"label", sc::Variant(_("Open"))},
{"uri", sc::Variant(res.dnd_uri())}
});
if (meta.is_aggregated()) {
actions.add_tuple({
{"id", sc::Variant("more")},
{"label", sc::Variant(_("More from ") + get_display_name())},
{"uri", sc::Variant(query.to_uri())}
});
}
res["actions"] = actions.end();
// Push the result
if (!reply->push(res)) {
// If we fail to push, it means the query has been cancelled.
// So don't continue;
return;
}
} // end if (!item.title.empty() && !item.uri.empty()) ...
} // end for (const auto &item : results) ...
} // end if (results.size > 0) ...
} catch (domain_error &e) {
// Handle exceptions being thrown by the client API
cerr << e.what() << endl;
reply->error(current_exception());
}
}
string Query::get_icon() {
return scope_directory_ + "/" + mScopeConfig->value("ScopeConfig/Icon", "/icon.png").toString().toStdString();
}
string Query::get_display_name() {
return mScopeConfig->value("ScopeConfig/DisplayName", "").toString().toStdString();
}
string Query::get_emblem() {
return scope_directory_ + "/" + mScopeConfig->value("Appearance/Emblem", "/emblem.png").toString().toStdString();
}
string Query::get_date_time_format() {
return mScopeConfig->value("Appearance/DateTimeFormat", "hh:mm, d MMMM").toString().toStdString();
}
bool Query::get_big_first_result() {
return mScopeConfig->value("Appearance/BigFirstResult", false).toBool();
}
|