rofi-blocks-search/ddg.go

75 lines
1.4 KiB
Go
Raw Permalink Normal View History

2020-08-08 16:28:29 +00:00
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
2020-08-08 17:14:21 +00:00
"./rofi"
)
2020-08-08 16:28:29 +00:00
2020-09-07 17:23:03 +00:00
var (
serial = 0
)
2020-08-08 16:28:29 +00:00
func getSuggestions(query string) []string {
param := url.Values{}
param.Add("q", query)
param.Add("type", "list")
param.Add("kl", "en-US")
resp, _ := http.Get("https://ac.duckduckgo.com/ac?" + param.Encode())
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
var result []interface{}
json.Unmarshal(body, &result)
if len(result) < 2 {
2020-08-08 20:37:33 +00:00
return []string{query}
2020-08-08 16:28:29 +00:00
}
2020-08-08 20:37:33 +00:00
rtn := make([]string, len(result[1].([]interface{}))+1)
rtn[0] = query
2020-08-08 16:28:29 +00:00
for i, v := range result[1].([]interface{}) {
2020-08-08 20:37:33 +00:00
rtn[i+1] = v.(string)
2020-08-08 16:28:29 +00:00
}
return rtn
}
2020-08-08 17:14:21 +00:00
func handleSelect(input rofi.Input) {
param := url.Values{}
param.Add("q", input.Value)
exec.Command("xdg-open", "https://duckduckgo.com/?"+param.Encode()).Start()
os.Exit(0)
2020-08-08 16:28:29 +00:00
}
2020-08-08 17:14:21 +00:00
func handleInputChange(input rofi.Input) {
2020-09-07 17:23:03 +00:00
serial++
go genOutput(input, serial)
}
func genOutput(input rofi.Input, mySerial int) {
2020-08-08 17:14:21 +00:00
output := rofi.NewOutput()
output.Lines = rofi.ConvertStringsToLine(getSuggestions(input.Value))
2020-09-07 17:23:03 +00:00
if serial == mySerial {
rofi.SendOutput(output)
}
2020-08-08 16:28:29 +00:00
}
func main() {
// Setup rofi
2020-08-08 17:14:21 +00:00
initialOutput := rofi.NewOutput()
2020-08-08 16:28:29 +00:00
initialOutput.Prompt = "Search"
initialOutput.InputAction = "send"
2020-08-08 17:14:21 +00:00
rofi.SendOutput(initialOutput)
2020-08-08 16:28:29 +00:00
2020-08-08 17:14:21 +00:00
rofi.InputChangeCallback = handleInputChange
rofi.SelectEntryCallback = handleSelect
rofi.InputLoop()
2020-08-08 16:28:29 +00:00
}