2016-06-12 14:32:46 +03:00
|
|
|
import AutocompleteProvider from './AutocompleteProvider';
|
|
|
|
import Q from 'q';
|
|
|
|
import 'whatwg-fetch';
|
|
|
|
|
2016-06-21 13:16:20 +03:00
|
|
|
const DDG_REGEX = /\/ddg\s+(.+)$/g;
|
2016-06-12 14:32:46 +03:00
|
|
|
const REFERER = 'vector';
|
|
|
|
|
2016-06-20 11:22:55 +03:00
|
|
|
let instance = null;
|
|
|
|
|
2016-06-12 14:32:46 +03:00
|
|
|
export default class DuckDuckGoProvider extends AutocompleteProvider {
|
2016-06-21 13:16:20 +03:00
|
|
|
constructor() {
|
|
|
|
super(DDG_REGEX);
|
|
|
|
}
|
|
|
|
|
2016-06-12 14:32:46 +03:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2016-06-21 13:16:20 +03:00
|
|
|
getCompletions(query: string, selection: {start: number, end: number}) {
|
|
|
|
let command = this.getCurrentCommand(query, selection);
|
|
|
|
if(!query || !command)
|
2016-06-12 14:32:46 +03:00
|
|
|
return Q.when([]);
|
|
|
|
|
2016-06-21 13:16:20 +03:00
|
|
|
return fetch(DuckDuckGoProvider.getQueryUri(command[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';
|
|
|
|
}
|
2016-06-20 11:22:55 +03:00
|
|
|
|
|
|
|
static getInstance(): DuckDuckGoProvider {
|
|
|
|
if(instance == null)
|
|
|
|
instance = new DuckDuckGoProvider();
|
|
|
|
|
|
|
|
return instance;
|
|
|
|
}
|
2016-06-12 14:32:46 +03:00
|
|
|
}
|