diff --git a/config.sample.yaml b/config.sample.yaml index 91186e4..a80e87a 100644 --- a/config.sample.yaml +++ b/config.sample.yaml @@ -87,6 +87,11 @@ services: Config: api_key: "AIzaSyA4FD39m9" + - ID: "wikipedia_service" + Type: "wikipedia" + UserID: "@goneb:localhost" # requires a Syncing client + Config: + - ID: "rss_service" Type: "rssbot" UserID: "@another_goneb:localhost" diff --git a/src/github.com/matrix-org/go-neb/goneb.go b/src/github.com/matrix-org/go-neb/goneb.go index ee7f2cc..6431554 100644 --- a/src/github.com/matrix-org/go-neb/goneb.go +++ b/src/github.com/matrix-org/go-neb/goneb.go @@ -29,6 +29,7 @@ import ( _ "github.com/matrix-org/go-neb/services/rssbot" _ "github.com/matrix-org/go-neb/services/slackapi" _ "github.com/matrix-org/go-neb/services/travisci" + _ "github.com/matrix-org/go-neb/services/wikipedia" "github.com/matrix-org/go-neb/types" "github.com/matrix-org/util" _ "github.com/mattn/go-sqlite3" diff --git a/src/github.com/matrix-org/go-neb/services/google/google.go b/src/github.com/matrix-org/go-neb/services/google/google.go index 728bfe1..347011b 100644 --- a/src/github.com/matrix-org/go-neb/services/google/google.go +++ b/src/github.com/matrix-org/go-neb/services/google/google.go @@ -123,7 +123,7 @@ func (s *Service) cmdGoogleImgSearch(client *gomatrix.Client, roomID, userID str // FIXME -- Sometimes upload fails with a cryptic error - "msg=Upload request failed code=400" resUpload, err := client.UploadLink(imgURL) if err != nil { - return nil, fmt.Errorf("Failed to upload Google image to matrix: %s", err.Error()) + return nil, fmt.Errorf("Failed to upload Google image at URL %s (content type %s) to matrix: %s", imgURL, searchResult.Mime, err.Error()) } return gomatrix.ImageMessage{ diff --git a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go new file mode 100644 index 0000000..39d9fab --- /dev/null +++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go @@ -0,0 +1,183 @@ +// Package wikipedia implements a Service which adds !commands for Wikipedia search. +package wikipedia + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" + + log "github.com/Sirupsen/logrus" + "github.com/jaytaylor/html2text" + "github.com/matrix-org/go-neb/types" + "github.com/matrix-org/gomatrix" +) + +// ServiceType of the Wikipedia service +const ServiceType = "wikipedia" +const maxExtractLength = 1024 // Max length of extract string in bytes + +var httpClient = &http.Client{} + +// Search results (returned by search query) +type wikipediaSearchResults struct { + Query wikipediaQuery `json:"query"` +} + +// Wikipeda pages returned in search results +type wikipediaQuery struct { + Pages map[string]wikipediaPage `json:"pages"` +} + +// Representation of an individual wikipedia page +type wikipediaPage struct { + PageID int64 `json:"pageid"` + NS int `json:"ns"` + Title string `json:"title"` + Touched string `json:"touched"` + LastRevID int64 `json:"lastrevid"` + Extract string `json:"extract"` +} + +// Service contains the Config fields for the Wikipedia service. +type Service struct { + types.DefaultService +} + +// Commands supported: +// !wikipedia some_search_query_without_quotes +// Responds with a suitable article extract and link to the referenced page into the same room as the command. +func (s *Service) Commands(client *gomatrix.Client) []types.Command { + return []types.Command{ + types.Command{ + Path: []string{"wikipedia"}, + Command: func(roomID, userID string, args []string) (interface{}, error) { + return s.cmdWikipediaSearch(client, roomID, userID, args) + }, + }, + } +} + +// usageMessage returns a matrix TextMessage representation of the service usage +func usageMessage() *gomatrix.TextMessage { + return &gomatrix.TextMessage{"m.notice", + `Usage: !wikipedia search_text`} +} + +func (s *Service) cmdWikipediaSearch(client *gomatrix.Client, roomID, userID string, args []string) (interface{}, error) { + // Check for query text + if len(args) < 1 { + return usageMessage(), nil + } + + // Get the query text and per,form search + querySentence := strings.Join(args, " ") + searchResultPage, err := s.text2Wikipedia(querySentence) + if err != nil { + return nil, err + } + + // No article extracts + if searchResultPage == nil || searchResultPage.Extract == "" { + return gomatrix.TextMessage{ + MsgType: "m.notice", + Body: "No results", + }, nil + } + + // Convert article HTML to text + extractText, err := html2text.FromString(searchResultPage.Extract) + if err != nil { + return gomatrix.TextMessage{ + MsgType: "m.notice", + Body: "Failed to convert extract to plain text - " + err.Error(), + }, nil + } + + // Truncate the extract text, if necessary + if len(extractText) > maxExtractLength { + extractText = extractText[:maxExtractLength] + "..." + } + + // Add a link to the bottom of the extract + extractText += fmt.Sprintf("\nhttp://en.wikipedia.org/?curid=%d", searchResultPage.PageID) + + // Return article extract + return gomatrix.TextMessage{ + MsgType: "m.notice", + Body: extractText, + }, nil +} + +// text2Wikipedia returns a Wikipedia article summary +func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) { + log.Info("Searching Wikipedia for: ", query) + + u, err := url.Parse("https://en.wikipedia.org/w/api.php") + if err != nil { + return nil, err + } + + // Example query - https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=RMS+Titanic + q := u.Query() + q.Set("action", "query") // Action - query for articles + q.Set("prop", "extracts") // Return article extracts + q.Set("format", "json") + q.Set("redirects", "") + // q.Set("exintro", "") + q.Set("titles", query) // Text to search for + + u.RawQuery = q.Encode() + // log.Info("Request URL: ", u) + + // Perform wikipedia search request + res, err := httpClient.Get(u.String()) + if res != nil { + defer res.Body.Close() + } + if err != nil { + return nil, err + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + return nil, fmt.Errorf("Request error: %d, %s", res.StatusCode, response2String(res)) + } + + // Parse search results + var searchResults wikipediaSearchResults + // log.Info(response2String(res)) + if err := json.NewDecoder(res.Body).Decode(&searchResults); err != nil { + return nil, fmt.Errorf("ERROR - %s", err.Error()) + } else if len(searchResults.Query.Pages) < 1 { + return nil, fmt.Errorf("No articles found") + } + + // Return only the first search result with an extract + for _, page := range searchResults.Query.Pages { + if page.Extract != "" { + return &page, nil + } + } + + return nil, fmt.Errorf("No articles with extracts found") +} + +// response2String returns a string representation of an HTTP response body +func response2String(res *http.Response) string { + bs, err := ioutil.ReadAll(res.Body) + if err != nil { + return "Failed to decode response body" + } + str := string(bs) + return str +} + +// Initialise the service +func init() { + types.RegisterService(func(serviceID, serviceUserID, webhookEndpointURL string) types.Service { + return &Service{ + DefaultService: types.NewDefaultService(serviceID, serviceUserID, ServiceType), + } + }) +} diff --git a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia_test.go b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia_test.go new file mode 100644 index 0000000..d60b8da --- /dev/null +++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia_test.go @@ -0,0 +1,99 @@ +package wikipedia + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strings" + "testing" + + "github.com/matrix-org/go-neb/database" + "github.com/matrix-org/go-neb/testutils" + "github.com/matrix-org/go-neb/types" + "github.com/matrix-org/gomatrix" +) + +// TODO: It would be nice to tabularise this test so we can try failing different combinations of responses to make +// sure all cases are handled, rather than just the general case as is here. +func TestCommand(t *testing.T) { + database.SetServiceDB(&database.NopStorage{}) + searchText := "Czechoslovakian bananna" + wikipediaAPIURL := "https://en.wikipedia.org/w/api.php" + + // Mock the response from Wikipedia + wikipediaTrans := testutils.NewRoundTripper(func(req *http.Request) (*http.Response, error) { + query := req.URL.Query() + + // Check the base API URL + if !strings.HasPrefix(req.URL.String(), wikipediaAPIURL) { + t.Fatalf("Bad URL: got %s want prefix %s", req.URL.String(), wikipediaAPIURL) + } + // Check the request method + if req.Method != "GET" { + t.Fatalf("Bad method: got %s want GET", req.Method) + } + // Check the search query + // Example query - https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=RMS+Titanic + var searchString = query.Get("titles") + var searchStringLength = len(searchString) + if searchStringLength > 0 && searchString != searchText { + t.Fatalf("Bad search string: got \"%s\" (%d characters) ", searchString, searchStringLength) + } + + page := wikipediaPage{ + PageID: 1, + NS: 1, + Title: "Test page", + Touched: "2017-02-21 00:00:00", + LastRevID: 1, + Extract: "Some extract text", + } + pages := map[string]wikipediaPage{ + "1": page, + } + res := wikipediaSearchResults{ + Query: wikipediaQuery{ + Pages: pages, + }, + } + + b, err := json.Marshal(res) + if err != nil { + t.Fatalf("Failed to marshal Wikipedia response - %s", err) + } + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewBuffer(b)), + }, nil + }) + // clobber the Wikipedia service http client instance + httpClient = &http.Client{Transport: wikipediaTrans} + + // Create the Wikipedia service + srv, err := types.CreateService("id", ServiceType, "@wikipediabot:hyrule", []byte(`{}`)) + if err != nil { + t.Fatal("Failed to create Wikipedia service: ", err) + } + wikipedia := srv.(*Service) + + // Mock the response from Matrix + matrixTrans := struct{ testutils.MockTransport }{} + matrixTrans.RT = func(req *http.Request) (*http.Response, error) { + return nil, fmt.Errorf("Unknown URL: %s", req.URL.String()) + } + matrixCli, _ := gomatrix.NewClient("https://hyrule", "@wikipediabot:hyrule", "its_a_secret") + matrixCli.Client = &http.Client{Transport: matrixTrans} + + // Execute the matrix !command + cmds := wikipedia.Commands(matrixCli) + if len(cmds) != 1 { + t.Fatalf("Unexpected number of commands: %d", len(cmds)) + } + cmd := cmds[0] + _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{searchText}) + if err != nil { + t.Fatalf("Failed to process command: %s", err.Error()) + } +} diff --git a/vendor/manifest b/vendor/manifest index 3070089..1bf7484 100644 --- a/vendor/manifest +++ b/vendor/manifest @@ -129,6 +129,12 @@ "revision": "d02018f006d98f58512bf3adfc171d88d17626df", "branch": "master" }, + { + "importpath": "github.com/jaytaylor/html2text", + "repository": "https://github.com/jaytaylor/html2text", + "revision": "24f9b0f63599c6bbecc3b773636b54f8d302db67", + "branch": "master" + }, { "importpath": "github.com/matrix-org/dugong", "repository": "https://github.com/matrix-org/dugong", diff --git a/vendor/src/github.com/jaytaylor/html2text/LICENSE b/vendor/src/github.com/jaytaylor/html2text/LICENSE new file mode 100644 index 0000000..24dc4ab --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jay Taylor + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/src/github.com/jaytaylor/html2text/README.md b/vendor/src/github.com/jaytaylor/html2text/README.md new file mode 100644 index 0000000..ac11247 --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/README.md @@ -0,0 +1,116 @@ +# html2text + +[![Documentation](https://godoc.org/github.com/jaytaylor/html2text?status.svg)](https://godoc.org/github.com/jaytaylor/html2text) +[![Build Status](https://travis-ci.org/jaytaylor/html2text.svg?branch=master)](https://travis-ci.org/jaytaylor/html2text) +[![Report Card](https://goreportcard.com/badge/github.com/jaytaylor/html2text)](https://goreportcard.com/report/github.com/jaytaylor/html2text) + +### Converts HTML into text + + +## Introduction + +Ensure your emails are readable by all! + +Turns HTML into raw text, useful for sending fancy HTML emails with a equivalently nicely formatted TXT document as a fallback (e.g. for people who don't allow HTML emails or have other display issues). + +html2text is a simple golang package for rendering HTML into plaintext. + +There are still lots of improvements to be had, but FWIW this has worked fine for my [basic] HTML-2-text needs. + +It requires go 1.x or newer ;) + + +## Download the package + +```bash +go get github.com/jaytaylor/html2text +``` + +## Example usage + +```go +package main + +import ( + "fmt" + + "github.com/jaytaylor/html2text" +) + +func main() { + inputHtml := ` + +
++ Here is some more information: + +
Test text
", + "Test text", + }, + { + "Test text
Test text
", + "Test text\n\nTest text", + }, + { + "\nTest text
\n\n\n\tTest text
\n", + "Test text\n\nTest text", + }, + { + "\nTest text
Test text
Test text
\tTest text
cell1 | cell2 |
row1 |
row2 |
cell1-1 | cell1-2 |
cell2-1 | cell2-2 |
cell |
This is link1 and link2 is next.
", + `This is link1 ( http://www.google.com ) and link2 ( http://www.google.com ) is next.`, + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestImageAltTags(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + ``, + ``, + }, + { + ``, + ``, + }, + { + ``, + ``, + }, + { + ``, + ``, + }, + // Images do matter if they are in a link + { + ``, + `Example ( http://example.com/ )`, + }, + { + ``, + `Example ( http://example.com/ )`, + }, + { + ``, + `Example ( http://example.com/ )`, + }, + { + ``, + `Example ( http://example.com/ )`, + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestHeadings(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "level 1level 2level 1
TestTest", + "> \n> Test\n\nTest", + }, + { + "\t
\nTest", + "> \n> Test\n>", + }, + { + "\t
\nTest line 1", + "> \n> Test line 1\n> Test 2", + }, + { + "
Test 2
Test
TestOther Test", + "> \n> Test\n\n> \n> Test\n\nOther Test", + }, + { + "
Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse labore aute quis commodo non sit dolore officia Excepteur cillum amet cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor irure do", + "> \n> Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad\n> sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat\n> voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse\n> labore aute quis commodo non sit dolore officia Excepteur cillum amet\n> cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor\n> irure do", + }, + { + "
LoremipsumCommodoidconsecteturpariatureaoccaecatminimaliquaadsitconsequatquisexcommodoDuisincididunteumollitconsecteturfugiatvoluptatedoloreinpariaturincommodooccaecatUtoccaecatvelitesselaboreautequiscommodononsitdoloreofficiaExcepteurcillumametcupidatatculpavelitlaboreullamcodoloremollitelitinaliquadoloriruredo", + "> \n> Lorem *ipsum* *Commodo* *id* *consectetur* *pariatur* *ea* *occaecat* *minim*\n> *aliqua* *ad* *sit* *consequat* *quis* *ex* *commodo* *Duis* *incididunt* *eu*\n> *mollit* *consectetur* *fugiat* *voluptate* *dolore* *in* *pariatur* *in* *commodo*\n> *occaecat* *Ut* *occaecat* *velit* *esse* *labore* *aute* *quis* *commodo*\n> *non* *sit* *dolore* *officia* *Excepteur* *cillum* *amet* *cupidatat* *culpa*\n> *velit* *labore* *ullamco* *dolore* *mollit* *elit* *in* *aliqua* *dolor* *irure*\n> *do*", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } + +} + +func TestIgnoreStylesScriptsHead(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + `
List:
+ + +`, + `hi +hello google \( https://google.com \) + +test + +List: + +\* Foo \( foo \) +\* Barsoap \( http://www.microshwhat.com/bar/soapy \) +\* Baz`, + }, + // Malformed input html. + { + `hi + + hello google + + testList:
+ + + `, + `hi hello google \( https://google.com \) test + +List: + +\* Foo \( foo \) +\* Bar \( /\n[ \t]+bar/baz \) +\* Baz`, + }, + } + + for _, testCase := range testCases { + assertRegexp(t, testCase.input, testCase.expr) + } +} + +type StringMatcher interface { + MatchString(string) bool + String() string +} + +type RegexpStringMatcher string + +func (m RegexpStringMatcher) MatchString(str string) bool { + return regexp.MustCompile(string(m)).MatchString(str) +} +func (m RegexpStringMatcher) String() string { + return string(m) +} + +type ExactStringMatcher string + +func (m ExactStringMatcher) MatchString(str string) bool { + return string(m) == str +} +func (m ExactStringMatcher) String() string { + return string(m) +} + +func assertRegexp(t *testing.T, input string, outputRE string) { + assertPlaintext(t, input, RegexpStringMatcher(outputRE)) +} + +func assertString(t *testing.T, input string, output string) { + assertPlaintext(t, input, ExactStringMatcher(output)) +} + +func assertPlaintext(t *testing.T, input string, matcher StringMatcher) { + text, err := FromString(input) + if err != nil { + t.Error(err) + } + if !matcher.MatchString(text) { + t.Errorf("Input did not match expression\n"+ + "Input:\n>>>>\n%s\n<<<<\n\n"+ + "Output:\n>>>>\n%s\n<<<<\n\n"+ + "Expected output:\n>>>>\n%s\n<<<<\n\n", + input, text, matcher.String()) + } else { + t.Logf("input:\n\n%s\n\n\n\noutput:\n\n%s\n", input, text) + } +} + +func Example() { + inputHtml := ` + + ++ Here is some more information: + +