2016-06-12 11:32:46 +00:00
|
|
|
import AutocompleteProvider from './AutocompleteProvider';
|
|
|
|
import Q from 'q';
|
|
|
|
import 'whatwg-fetch';
|
|
|
|
|
2016-06-21 10:16:20 +00:00
|
|
|
const DDG_REGEX = /\/ddg\s+(.+)$/g;
|
2016-06-12 11:32:46 +00:00
|
|
|
const REFERER = 'vector';
|
|
|
|
|
2016-06-20 08:22:55 +00:00
|
|
|
let instance = null;
|
|
|
|
|
2016-06-12 11:32:46 +00:00
|
|
|
export default class DuckDuckGoProvider extends AutocompleteProvider {
|
2016-06-21 10:16:20 +00:00
|
|
|
constructor() {
|
|
|
|
super(DDG_REGEX);
|
|
|
|
}
|
|
|
|
|
2016-06-12 11:32:46 +00:00
|
|
|
static getQueryUri(query: String) {
|
2016-06-16 23:28:09 +00:00
|
|
|
return `http://api.duckduckgo.com/?q=${encodeURIComponent(query)}`
|
|
|
|
+ `&format=json&no_redirect=1&no_html=1&t=${encodeURIComponent(REFERER)}`;
|
2016-06-12 11:32:46 +00:00
|
|
|
}
|
|
|
|
|
2016-06-21 10:16:20 +00:00
|
|
|
getCompletions(query: string, selection: {start: number, end: number}) {
|
|
|
|
let command = this.getCurrentCommand(query, selection);
|
|
|
|
if(!query || !command)
|
2016-06-12 11:32:46 +00:00
|
|
|
return Q.when([]);
|
|
|
|
|
2016-06-21 10:16:20 +00:00
|
|
|
return fetch(DuckDuckGoProvider.getQueryUri(command[1]), {
|
2016-06-12 11:32:46 +00:00
|
|
|
method: 'GET'
|
2016-06-16 23:28:09 +00: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 11:32:46 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
getName() {
|
|
|
|
return 'Results from DuckDuckGo';
|
|
|
|
}
|
2016-06-20 08:22:55 +00:00
|
|
|
|
|
|
|
static getInstance(): DuckDuckGoProvider {
|
|
|
|
if(instance == null)
|
|
|
|
instance = new DuckDuckGoProvider();
|
|
|
|
|
|
|
|
return instance;
|
|
|
|
}
|
2016-06-12 11:32:46 +00:00
|
|
|
}
|