2016-06-12 14:32:46 +03:00
|
|
|
import AutocompleteProvider from './AutocompleteProvider';
|
|
|
|
import Q from 'q';
|
|
|
|
import 'whatwg-fetch';
|
|
|
|
|
2016-06-17 02:28:09 +03:00
|
|
|
const DDG_REGEX = /\/ddg\s+(.+)$/;
|
2016-06-12 14:32:46 +03:00
|
|
|
const REFERER = 'vector';
|
|
|
|
|
|
|
|
export default class DuckDuckGoProvider extends AutocompleteProvider {
|
|
|
|
static getQueryUri(query: String) {
|
2016-06-17 02:28:09 +03:00
|
|
|
return `http://api.duckduckgo.com/?q=${encodeURIComponent(query)}`
|
|
|
|
+ `&format=json&no_redirect=1&no_html=1&t=${encodeURIComponent(REFERER)}`;
|
2016-06-12 14:32:46 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
getCompletions(query: String) {
|
2016-06-17 02:28:09 +03:00
|
|
|
let match = DDG_REGEX.exec(query);
|
|
|
|
if(!query || !match)
|
2016-06-12 14:32:46 +03:00
|
|
|
return Q.when([]);
|
|
|
|
|
2016-06-17 02:28:09 +03:00
|
|
|
return fetch(DuckDuckGoProvider.getQueryUri(match[1]), {
|
2016-06-12 14:32:46 +03:00
|
|
|
method: 'GET'
|
2016-06-17 02:28:09 +03:00
|
|
|
})
|
|
|
|
.then(response => response.json())
|
|
|
|
.then(json => {
|
|
|
|
let results = json.Results.map(result => {
|
|
|
|
return {
|
|
|
|
title: result.Text,
|
|
|
|
description: result.Result
|
|
|
|
};
|
|
|
|
});
|
|
|
|
if(json.Answer) {
|
|
|
|
results.unshift({
|
|
|
|
title: json.Answer,
|
|
|
|
description: json.AnswerType
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if(json.RelatedTopics && json.RelatedTopics.length > 0) {
|
|
|
|
results.unshift({
|
|
|
|
title: json.RelatedTopics[0].Text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if(json.AbstractText) {
|
|
|
|
results.unshift({
|
|
|
|
title: json.AbstractText
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// console.log(results);
|
|
|
|
return results;
|
2016-06-12 14:32:46 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
getName() {
|
|
|
|
return 'Results from DuckDuckGo';
|
|
|
|
}
|
|
|
|
}
|