Files
ThreadNet-Web/src/autocomplete/DuckDuckGoProvider.js
T

94 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-07-03 22:15:13 +05:30
import React from 'react';
import AutocompleteProvider from './AutocompleteProvider';
import 'whatwg-fetch';
2016-07-03 22:15:13 +05:30
import {TextualCompletion} from './Components';
const DDG_REGEX = /\/ddg\s+(.+)$/g;
2016-07-03 22:15:13 +05:30
const REFERRER = 'vector';
let instance = null;
export default class DuckDuckGoProvider extends AutocompleteProvider {
constructor() {
super(DDG_REGEX);
}
2017-01-20 14:22:27 +00:00
static getQueryUri(query: String) {
return `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}`
2016-07-03 22:15:13 +05:30
+ `&format=json&no_redirect=1&no_html=1&t=${encodeURIComponent(REFERRER)}`;
}
2016-09-13 15:41:52 +05:30
async getCompletions(query: string, selection: {start: number, end: number}) {
2016-07-03 22:15:13 +05:30
let {command, range} = this.getCurrentCommand(query, selection);
if (!query || !command) {
2016-09-13 15:41:52 +05:30
return [];
2016-07-03 22:15:13 +05:30
}
2016-09-13 15:41:52 +05:30
const response = await fetch(DuckDuckGoProvider.getQueryUri(command[1]), {
2016-07-03 22:15:13 +05:30
method: 'GET',
2016-09-13 15:41:52 +05:30
});
const json = await response.json();
let results = json.Results.map(result => {
return {
completion: result.Text,
component: (
<TextualCompletion
title={result.Text}
description={result.Result} />
),
range,
};
});
if (json.Answer) {
results.unshift({
completion: json.Answer,
component: (
<TextualCompletion
title={json.Answer}
description={json.AnswerType} />
),
range,
});
2016-09-13 15:41:52 +05:30
}
if (json.RelatedTopics && json.RelatedTopics.length > 0) {
results.unshift({
completion: json.RelatedTopics[0].Text,
component: (
<TextualCompletion
title={json.RelatedTopics[0].Text} />
),
range,
});
}
if (json.AbstractText) {
results.unshift({
completion: json.AbstractText,
component: (
<TextualCompletion
title={json.AbstractText} />
),
range,
});
}
return results;
}
getName() {
return '🔍 Results from DuckDuckGo';
}
static getInstance(): DuckDuckGoProvider {
2016-07-03 22:15:13 +05:30
if (instance == null) {
instance = new DuckDuckGoProvider();
2016-07-03 22:15:13 +05:30
}
return instance;
}
2016-08-23 00:36:31 +05:30
renderCompletions(completions: [React.Component]): ?React.Component {
return <div className="mx_Autocomplete_Completion_container_block">
{completions}
</div>;
}
}