From 5f1130608b5b0b9883131f19c39542022ea78774 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Mon, 20 Feb 2017 22:35:15 +0000
Subject: [PATCH 1/9] Wikipedia config sample
---
config.sample.yaml | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/config.sample.yaml b/config.sample.yaml
index 04579ac..24798e6 100644
--- a/config.sample.yaml
+++ b/config.sample.yaml
@@ -81,6 +81,11 @@ services:
api_key: "AIzaSyA4FD39m9"
cx: "AIASDFWSRRtrtr"
+ - ID: "wikipedia_service"
+ Type: "wikipedia"
+ UserID: "@goneb:localhost" # requires a Syncing client
+ Config:
+
- ID: "rss_service"
Type: "rssbot"
UserID: "@another_goneb:localhost"
From e8597f40a8db103e86303e205c82093a5877c8f7 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Mon, 20 Feb 2017 23:05:33 +0000
Subject: [PATCH 2/9] Added wikipedia bot integration
---
src/github.com/matrix-org/go-neb/goneb.go | 1 +
.../go-neb/services/wikipedia/wikipedia.go | 150 ++++++++++++++++++
.../services/wikipedia/wikipedia_test.go | 111 +++++++++++++
3 files changed, 262 insertions(+)
create mode 100644 src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
create mode 100644 src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia_test.go
diff --git a/src/github.com/matrix-org/go-neb/goneb.go b/src/github.com/matrix-org/go-neb/goneb.go
index 8fa3599..3757d12 100644
--- a/src/github.com/matrix-org/go-neb/goneb.go
+++ b/src/github.com/matrix-org/go-neb/goneb.go
@@ -28,6 +28,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/wikipedia/wikipedia.go b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
new file mode 100644
index 0000000..a0ecd38
--- /dev/null
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -0,0 +1,150 @@
+// 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/matrix-org/go-neb/types"
+ "github.com/matrix-org/gomatrix"
+)
+
+// ServiceType of the Wikipedia service
+const ServiceType = "wikipedia"
+
+var httpClient = &http.Client{}
+
+type wikipediaSearchResults struct {
+ Query struct {
+ Pages map[string]wikipediaPage `json:"pages"`
+ } `json:"query"`
+}
+
+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) {
+
+ if len(args) < 1 {
+ return usageMessage(), nil
+ }
+
+ // Get the query text to search for.
+ querySentence := strings.Join(args, " ")
+
+ searchResultPage, err := s.text2Wikipedia(querySentence)
+
+ if err != nil {
+ return nil, err
+ }
+
+ if searchResultPage.Extract == "" {
+ return gomatrix.TextMessage{
+ MsgType: "m.notice",
+ Body: "No results found!",
+ }, nil
+ }
+
+ return gomatrix.TextMessage{
+ MsgType: "m.notice",
+ Body: searchResultPage.Extract,
+ }, 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("exintro", "")
+ q.Set("titles", query) // Text to search for
+
+ u.RawQuery = q.Encode()
+ // log.Info("Request URL: ", u)
+
+ 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))
+ }
+ 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.Pages) < 1 {
+ return nil, fmt.Errorf("No articles found")
+ }
+
+ // Return only the first search result
+ return &searchResults.Pages[0], nil
+}
+
+// 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..3de53aa
--- /dev/null
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia_test.go
@@ -0,0 +1,111 @@
+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{})
+ apiKey := "secret"
+ wikipediaImageURL := "https://www.wikipediaapis.com/customsearch/v1"
+
+ // Mock the response from Wikipedia
+ wikipediaTrans := testutils.NewRoundTripper(func(req *http.Request) (*http.Response, error) {
+ wikipediaURL := "https://www.wikipediaapis.com/customsearch/v1"
+ query := req.URL.Query()
+
+ // Check the base API URL
+ if !strings.HasPrefix(req.URL.String(), wikipediaURL) {
+ t.Fatalf("Bad URL: got %s want prefix %s", req.URL.String(), wikipediaURL)
+ }
+ // Check the request method
+ if req.Method != "GET" {
+ t.Fatalf("Bad method: got %s want GET", req.Method)
+ }
+ // Check the API key
+ if query.Get("key") != apiKey {
+ t.Fatalf("Bad apiKey: got %s want %s", query.Get("key"), apiKey)
+ }
+ // Check the search query
+ var searchString = query.Get("q")
+ var searchStringLength = len(searchString)
+ if searchStringLength > 0 && !strings.HasPrefix(searchString, "image") {
+ t.Fatalf("Bad search string: got \"%s\" (%d characters) ", searchString, searchStringLength)
+ }
+
+ resImage := wikipediaImage{
+ Width: 64,
+ Height: 64,
+ }
+
+ res := wikipediaSearchResult{
+ Title: "A Cat",
+ Link: "http://cat.com/cat.jpg",
+ Mime: "image/jpeg",
+ Image: resImage,
+ }
+
+ 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(
+ `{"api_key":"`+apiKey+`"}`,
+ ))
+ 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) {
+ if req.URL.String() == wikipediaImageURL { // getting the Wikipedia image
+ return &http.Response{
+ StatusCode: 200,
+ Body: ioutil.NopCloser(bytes.NewBufferString("some image data")),
+ }, nil
+ } else if strings.Contains(req.URL.String(), "_matrix/media/r0/upload") { // uploading the image to matrix
+ return &http.Response{
+ StatusCode: 200,
+ Body: ioutil.NopCloser(bytes.NewBufferString(`{"content_uri":"mxc://foo/bar"}`)),
+ }, nil
+ }
+ 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) != 3 {
+ t.Fatalf("Unexpected number of commands: %d", len(cmds))
+ }
+ // cmd := cmds[0]
+ // _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{"image", "Czechoslovakian bananna"})
+ // if err != nil {
+ // t.Fatalf("Failed to process command: %s", err.Error())
+ // }
+}
From 47060231d1f64efa808ea67db9d6783f293565fe Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Mon, 20 Feb 2017 23:59:21 +0000
Subject: [PATCH 3/9] Add HTML2text library. Fix extract formatting
---
.../go-neb/services/wikipedia/wikipedia.go | 33 +-
vendor/manifest | 6 +
.../github.com/jaytaylor/html2text/LICENSE | 22 +
.../github.com/jaytaylor/html2text/README.md | 116 ++++
.../jaytaylor/html2text/html2text.go | 304 +++++++++
.../jaytaylor/html2text/html2text_test.go | 630 ++++++++++++++++++
6 files changed, 1107 insertions(+), 4 deletions(-)
create mode 100644 vendor/src/github.com/jaytaylor/html2text/LICENSE
create mode 100644 vendor/src/github.com/jaytaylor/html2text/README.md
create mode 100644 vendor/src/github.com/jaytaylor/html2text/html2text.go
create mode 100644 vendor/src/github.com/jaytaylor/html2text/html2text_test.go
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
index a0ecd38..3c540bf 100644
--- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -7,15 +7,18 @@ import (
"io/ioutil"
"net/http"
"net/url"
+ "strconv"
"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{}
@@ -81,9 +84,25 @@ func (s *Service) cmdWikipediaSearch(client *gomatrix.Client, roomID, userID str
}, nil
}
+ 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 += "\n" + "http://en.wikipedia.org/?curid=" + strconv.FormatInt(searchResultPage.PageID, 10)
+
return gomatrix.TextMessage{
MsgType: "m.notice",
- Body: searchResultPage.Extract,
+ Body: extractText,
}, nil
}
@@ -122,12 +141,18 @@ func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) {
// 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.Pages) < 1 {
+ } else if len(searchResults.Query.Pages) < 1 {
return nil, fmt.Errorf("No articles found")
}
- // Return only the first search result
- return &searchResults.Pages[0], nil
+ // 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
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 := `
+
+
+ My Mega Service
+
+
+
+
+
+
+
+
+
+ Welcome to your new account on my service!
+
+
+ Here is some more information:
+
+
+
+
+
+ `
+
+ text, err := html2text.FromString(inputHtml)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(text)
+}
+```
+
+Output:
+```
+Mega Service ( http://mymegaservice.com/ )
+
+******************************************
+Welcome to your new account on my service!
+******************************************
+
+Here is some more information:
+
+* Link 1: Example.com ( https://example.com )
+* Link 2: Example2.com ( https://example2.com )
+* Something else
+```
+
+
+## Unit-tests
+
+Running the unit-tests is straightforward and standard:
+
+```bash
+go test
+```
+
+
+# License
+
+Permissive MIT license.
+
+
+## Contact
+
+You are more than welcome to open issues and send pull requests if you find a bug or want a new feature.
+
+If you appreciate this library please feel free to drop me a line and tell me! It's always nice to hear from people who have benefitted from my work.
+
+Email: jay at (my github username).com
+
+Twitter: [@jtaylor](https://twitter.com/jtaylor)
+
diff --git a/vendor/src/github.com/jaytaylor/html2text/html2text.go b/vendor/src/github.com/jaytaylor/html2text/html2text.go
new file mode 100644
index 0000000..8933fbe
--- /dev/null
+++ b/vendor/src/github.com/jaytaylor/html2text/html2text.go
@@ -0,0 +1,304 @@
+package html2text
+
+import (
+ "bytes"
+ "io"
+ "regexp"
+ "strings"
+ "unicode"
+
+ "golang.org/x/net/html"
+ "golang.org/x/net/html/atom"
+)
+
+var (
+ spacingRe = regexp.MustCompile(`[ \r\n\t]+`)
+ newlineRe = regexp.MustCompile(`\n\n+`)
+)
+
+type textifyTraverseCtx struct {
+ Buf bytes.Buffer
+
+ prefix string
+ blockquoteLevel int
+ lineLength int
+ endsWithSpace bool
+ endsWithNewline bool
+ justClosedDiv bool
+}
+
+func (ctx *textifyTraverseCtx) traverse(node *html.Node) error {
+ switch node.Type {
+
+ default:
+ return ctx.traverseChildren(node)
+
+ case html.TextNode:
+ data := strings.Trim(spacingRe.ReplaceAllString(node.Data, " "), " ")
+ return ctx.emit(data)
+
+ case html.ElementNode:
+
+ ctx.justClosedDiv = false
+ switch node.DataAtom {
+ case atom.Br:
+ return ctx.emit("\n")
+
+ case atom.H1, atom.H2, atom.H3:
+ subCtx := textifyTraverseCtx{}
+ if err := subCtx.traverseChildren(node); err != nil {
+ return err
+ }
+
+ str := subCtx.Buf.String()
+ dividerLen := 0
+ for _, line := range strings.Split(str, "\n") {
+ if lineLen := len([]rune(line)); lineLen-1 > dividerLen {
+ dividerLen = lineLen - 1
+ }
+ }
+ divider := ""
+ if node.DataAtom == atom.H1 {
+ divider = strings.Repeat("*", dividerLen)
+ } else {
+ divider = strings.Repeat("-", dividerLen)
+ }
+
+ if node.DataAtom == atom.H3 {
+ return ctx.emit("\n\n" + str + "\n" + divider + "\n\n")
+ }
+ return ctx.emit("\n\n" + divider + "\n" + str + "\n" + divider + "\n\n")
+
+ case atom.Blockquote:
+ ctx.blockquoteLevel++
+ ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel) + " "
+ if err := ctx.emit("\n"); err != nil {
+ return err
+ }
+ if ctx.blockquoteLevel == 1 {
+ if err := ctx.emit("\n"); err != nil {
+ return err
+ }
+ }
+ if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+ ctx.blockquoteLevel--
+ ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel)
+ if ctx.blockquoteLevel > 0 {
+ ctx.prefix += " "
+ }
+ return ctx.emit("\n\n")
+
+ case atom.Div:
+ if ctx.lineLength > 0 {
+ if err := ctx.emit("\n"); err != nil {
+ return err
+ }
+ }
+ if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+ var err error
+ if ctx.justClosedDiv == false {
+ err = ctx.emit("\n")
+ }
+ ctx.justClosedDiv = true
+ return err
+
+ case atom.Li:
+ if err := ctx.emit("* "); err != nil {
+ return err
+ }
+
+ if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+
+ return ctx.emit("\n")
+
+ case atom.B, atom.Strong:
+ subCtx := textifyTraverseCtx{}
+ subCtx.endsWithSpace = true
+ if err := subCtx.traverseChildren(node); err != nil {
+ return err
+ }
+ str := subCtx.Buf.String()
+ return ctx.emit("*" + str + "*")
+
+ case atom.A:
+ // If image is the only child, take its alt text as the link text
+ if img := node.FirstChild; img != nil && node.LastChild == img && img.DataAtom == atom.Img {
+ if altText := getAttrVal(img, "alt"); altText != "" {
+ ctx.emit(altText)
+ }
+ } else if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+
+ hrefLink := ""
+ if attrVal := getAttrVal(node, "href"); attrVal != "" {
+ attrVal = ctx.normalizeHrefLink(attrVal)
+ if attrVal != "" {
+ hrefLink = "( " + attrVal + " )"
+ }
+ }
+
+ return ctx.emit(hrefLink)
+
+ case atom.P, atom.Ul, atom.Table:
+ if err := ctx.emit("\n\n"); err != nil {
+ return err
+ }
+
+ if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+
+ return ctx.emit("\n\n")
+
+ case atom.Tr:
+ if err := ctx.traverseChildren(node); err != nil {
+ return err
+ }
+
+ return ctx.emit("\n")
+
+ case atom.Style, atom.Script, atom.Head:
+ // Ignore the subtree
+ return nil
+
+ default:
+ return ctx.traverseChildren(node)
+ }
+ }
+}
+
+func (ctx *textifyTraverseCtx) traverseChildren(node *html.Node) error {
+ for c := node.FirstChild; c != nil; c = c.NextSibling {
+ if err := ctx.traverse(c); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (ctx *textifyTraverseCtx) emit(data string) error {
+ if len(data) == 0 {
+ return nil
+ }
+ lines := ctx.breakLongLines(data)
+ var err error
+ for _, line := range lines {
+ runes := []rune(line)
+ startsWithSpace := unicode.IsSpace(runes[0])
+ if !startsWithSpace && !ctx.endsWithSpace {
+ ctx.Buf.WriteByte(' ')
+ ctx.lineLength++
+ }
+ ctx.endsWithSpace = unicode.IsSpace(runes[len(runes)-1])
+ for _, c := range line {
+ _, err = ctx.Buf.WriteString(string(c))
+ if err != nil {
+ return err
+ }
+ ctx.lineLength++
+ if c == '\n' {
+ ctx.lineLength = 0
+ if ctx.prefix != "" {
+ _, err = ctx.Buf.WriteString(ctx.prefix)
+ if err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (ctx *textifyTraverseCtx) breakLongLines(data string) []string {
+ // only break lines when we are in blockquotes
+ if ctx.blockquoteLevel == 0 {
+ return []string{data}
+ }
+ var ret []string
+ runes := []rune(data)
+ l := len(runes)
+ existing := ctx.lineLength
+ if existing >= 74 {
+ ret = append(ret, "\n")
+ existing = 0
+ }
+ for l+existing > 74 {
+ i := 74 - existing
+ for i >= 0 && !unicode.IsSpace(runes[i]) {
+ i--
+ }
+ if i == -1 {
+ // no spaces, so go the other way
+ i = 74 - existing
+ for i < l && !unicode.IsSpace(runes[i]) {
+ i++
+ }
+ }
+ ret = append(ret, string(runes[:i])+"\n")
+ for i < l && unicode.IsSpace(runes[i]) {
+ i++
+ }
+ runes = runes[i:]
+ l = len(runes)
+ existing = 0
+ }
+ if len(runes) > 0 {
+ ret = append(ret, string(runes))
+ }
+ return ret
+}
+
+func (ctx *textifyTraverseCtx) normalizeHrefLink(link string) string {
+ link = strings.TrimSpace(link)
+ link = strings.TrimPrefix(link, "mailto:")
+ return link
+}
+
+func getAttrVal(node *html.Node, attrName string) string {
+ for _, attr := range node.Attr {
+ if attr.Key == attrName {
+ return attr.Val
+ }
+ }
+
+ return ""
+}
+
+func FromHtmlNode(doc *html.Node) (string, error) {
+ ctx := textifyTraverseCtx{
+ Buf: bytes.Buffer{},
+ }
+ if err := ctx.traverse(doc); err != nil {
+ return "", err
+ }
+
+ text := strings.TrimSpace(newlineRe.ReplaceAllString(
+ strings.Replace(ctx.Buf.String(), "\n ", "\n", -1), "\n\n"))
+ return text, nil
+
+}
+
+func FromReader(reader io.Reader) (string, error) {
+ doc, err := html.Parse(reader)
+ if err != nil {
+ return "", err
+ }
+ return FromHtmlNode(doc)
+}
+
+func FromString(input string) (string, error) {
+ text, err := FromReader(strings.NewReader(input))
+ if err != nil {
+ return "", err
+ }
+ return text, nil
+}
diff --git a/vendor/src/github.com/jaytaylor/html2text/html2text_test.go b/vendor/src/github.com/jaytaylor/html2text/html2text_test.go
new file mode 100644
index 0000000..c55aa3e
--- /dev/null
+++ b/vendor/src/github.com/jaytaylor/html2text/html2text_test.go
@@ -0,0 +1,630 @@
+package html2text
+
+import (
+ "fmt"
+ "regexp"
+ "testing"
+)
+
+func TestStrippingWhitespace(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "test text",
+ "test text",
+ },
+ {
+ " \ttext\ntext\n",
+ "text text",
+ },
+ {
+ " \na \n\t \n \n a \t",
+ "a a",
+ },
+ {
+ "test text",
+ "test text",
+ },
+ {
+ "test text ",
+ "test text",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+}
+
+func TestParagraphsAndBreaks(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "Test text",
+ "Test text",
+ },
+ {
+ "Test text ",
+ "Test text",
+ },
+ {
+ "Test text Test",
+ "Test text\nTest",
+ },
+ {
+ "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
\n",
+ "Test text\nTest text",
+ },
+ {
+ "\nTest text \tTest text
\n",
+ "Test text\nTest text",
+ },
+ {
+ "Test text Test text",
+ "Test text\n\nTest text",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+}
+
+func TestTables(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "cell1 cell2",
+ },
+ {
+ "",
+ "row1\nrow2",
+ },
+ {
+ `
+ cell1-1 cell1-2
+ cell2-1 cell2-2
+
`,
+ "cell1-1 cell1-2\ncell2-1 cell2-2",
+ },
+ {
+ "__",
+ "_\n\ncell\n\n_",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+}
+
+func TestStrippingLists(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "",
+ "",
+ },
+ {
+ "_",
+ "* item\n\n_",
+ },
+ {
+ "item 1 item 2 \n_",
+ "* item 1\n* item 2\n_",
+ },
+ {
+ "item 1 \t\n item 2 item 3 \n_",
+ "* item 1\n* item 2\n* item 3\n_",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+}
+
+func TestLinks(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ ` `,
+ ``,
+ },
+ {
+ ` `,
+ ``,
+ },
+ {
+ ` `,
+ `( http://example.com/ )`,
+ },
+ {
+ `Link `,
+ `Link`,
+ },
+ {
+ `Link `,
+ `Link ( http://example.com/ )`,
+ },
+ {
+ `Link `,
+ `Link ( http://example.com/ )`,
+ },
+ {
+ "\n\tLink \n\t ",
+ `Link ( http://example.com/ )`,
+ },
+ {
+ "Contact Us ",
+ `Contact Us ( contact@example.org )`,
+ },
+ {
+ "Link ",
+ `Link ( http://example.com:80/~user?aaa=bb&c=d,e,f#foo )`,
+ },
+ {
+ "Link ",
+ `Link ( http://example.com/ )`,
+ },
+ {
+ " Link ",
+ `Link ( http://example.com/ )`,
+ },
+ {
+ "Link A Link B ",
+ `Link A ( http://example.com/a/ ) Link B ( http://example.com/b/ )`,
+ },
+ {
+ "Link ",
+ `Link ( %%LINK%% )`,
+ },
+ {
+ "Link ",
+ `Link ( [LINK] )`,
+ },
+ {
+ "Link ",
+ `Link ( {LINK} )`,
+ },
+ {
+ "Link ",
+ `Link ( [[!unsubscribe]] )`,
+ },
+ {
+ "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
+ }{
+ {
+ "Test ",
+ "****\nTest\n****",
+ },
+ {
+ "\t\nTest ",
+ "****\nTest\n****",
+ },
+ {
+ "\t\nTest line 1 Test 2 ",
+ "***********\nTest line 1\nTest 2\n***********",
+ },
+ {
+ "Test Test ",
+ "****\nTest\n****\n\n****\nTest\n****",
+ },
+ {
+ "Test ",
+ "----\nTest\n----",
+ },
+ {
+ "",
+ "****************************\nTest ( http://example.com/ )\n****************************",
+ },
+ {
+ " Test ",
+ "Test\n----",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+
+}
+
+func TestBold(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "Test ",
+ "*Test*",
+ },
+ {
+ "\tTest ",
+ "*Test*",
+ },
+ {
+ "\tTest line 1 Test 2 ",
+ "*Test line 1\nTest 2*",
+ },
+ {
+ "Test Test ",
+ "*Test* *Test*",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+
+}
+
+func TestDiv(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "Test
",
+ "Test",
+ },
+ {
+ "\tTest
",
+ "Test",
+ },
+ {
+ "",
+ "Test line 1\nTest 2",
+ },
+ {
+ "Test 1Test 2
Test 3
Test 4",
+ "Test 1\nTest 2\nTest 3\nTest 4",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+
+}
+
+func TestBlockquotes(t *testing.T) {
+ testCases := []struct {
+ input string
+ output string
+ }{
+ {
+ "level 0
level 1level 2 level 1 level 0
",
+ "level 0\n> \n> level 1\n> \n>> level 2\n> \n> level 1\n\nlevel 0",
+ },
+ {
+ "Test Test",
+ "> \n> Test\n\nTest",
+ },
+ {
+ "\t \nTest ",
+ "> \n> Test\n>",
+ },
+ {
+ "\t \nTest line 1 Test 2 ",
+ "> \n> Test line 1\n> Test 2",
+ },
+ {
+ "Test Test Other 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",
+ },
+ {
+ "Loremipsum 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*\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
+ }{
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ " ",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ "",
+ "",
+ },
+ {
+ `Title `,
+ "",
+ },
+ }
+
+ for _, testCase := range testCases {
+ assertString(t, testCase.input, testCase.output)
+ }
+}
+
+func TestText(t *testing.T) {
+ testCases := []struct {
+ input string
+ expr string
+ }{
+ {
+ `
+ New repository
+ `,
+ `\* New repository \( /new \)`,
+ },
+ {
+ `hi
+
+
+
+ hello google
+
+ testList:
+
+
+`,
+ `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 := `
+
+
+ My Mega Service
+
+
+
+
+
+
+
+
+
+ Welcome to your new account on my service!
+
+
+ Here is some more information:
+
+
+
+
+
+ `
+
+ text, err := FromString(inputHtml)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(text)
+
+ // Output:
+ // Mega Service ( http://mymegaservice.com/ )
+ //
+ // ******************************************
+ // Welcome to your new account on my service!
+ // ******************************************
+ //
+ // Here is some more information:
+ //
+ // * Link 1: Example.com ( https://example.com )
+ // * Link 2: Example2.com ( https://example2.com )
+ // * Something else
+}
From 34c4874acdccecee0bb1573bf07c71dfce0c2b37 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Tue, 21 Feb 2017 21:25:10 +0000
Subject: [PATCH 4/9] Name wikipedia query struct, message formatting, fix
tests
---
.../go-neb/services/wikipedia/wikipedia.go | 11 ++++----
.../services/wikipedia/wikipedia_test.go | 25 +++++++++++--------
2 files changed, 21 insertions(+), 15 deletions(-)
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
index 3c540bf..c7b95c6 100644
--- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -7,7 +7,6 @@ import (
"io/ioutil"
"net/http"
"net/url"
- "strconv"
"strings"
log "github.com/Sirupsen/logrus"
@@ -23,9 +22,11 @@ const maxExtractLength = 1024 // Max length of extract string in bytes
var httpClient = &http.Client{}
type wikipediaSearchResults struct {
- Query struct {
- Pages map[string]wikipediaPage `json:"pages"`
- } `json:"query"`
+ Query wikipediaQuery `json:"query"`
+}
+
+type wikipediaQuery struct {
+ Pages map[string]wikipediaPage `json:"pages"`
}
type wikipediaPage struct {
@@ -98,7 +99,7 @@ func (s *Service) cmdWikipediaSearch(client *gomatrix.Client, roomID, userID str
}
// Add a link to the bottom of the extract
- extractText += "\n" + "http://en.wikipedia.org/?curid=" + strconv.FormatInt(searchResultPage.PageID, 10)
+ extractText += fmt.Sprintf("\nhttp://en.wikipedia.org/?curid=%d", searchResultPage.PageID)
return gomatrix.TextMessage{
MsgType: "m.notice",
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
index 3de53aa..6440cb9 100644
--- 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
@@ -46,16 +46,21 @@ func TestCommand(t *testing.T) {
t.Fatalf("Bad search string: got \"%s\" (%d characters) ", searchString, searchStringLength)
}
- resImage := wikipediaImage{
- Width: 64,
- Height: 64,
+ page := wikipediaPage{
+ PageID: 1,
+ NS: 1,
+ Title: "Test page",
+ Touched: "2017-02-21 00:00:00",
+ LastRevID: 1,
+ Extract: "Some extract text",
}
-
- res := wikipediaSearchResult{
- Title: "A Cat",
- Link: "http://cat.com/cat.jpg",
- Mime: "image/jpeg",
- Image: resImage,
+ pages := map[string]wikipediaPage{
+ "1": page,
+ }
+ res := wikipediaSearchResults{
+ Query: wikipediaQuery{
+ Pages: pages,
+ },
}
b, err := json.Marshal(res)
@@ -100,7 +105,7 @@ func TestCommand(t *testing.T) {
// Execute the matrix !command
cmds := wikipedia.Commands(matrixCli)
- if len(cmds) != 3 {
+ if len(cmds) != 1 {
t.Fatalf("Unexpected number of commands: %d", len(cmds))
}
// cmd := cmds[0]
From fb523544613f9463b14ce03a9a68e49d766a49dd Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Tue, 21 Feb 2017 21:35:44 +0000
Subject: [PATCH 5/9] Cleaned up string formatting
---
.../matrix-org/go-neb/services/wikipedia/wikipedia_test.go | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
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
index 6440cb9..924ba99 100644
--- 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
@@ -76,9 +76,7 @@ func TestCommand(t *testing.T) {
httpClient = &http.Client{Transport: wikipediaTrans}
// Create the Wikipedia service
- srv, err := types.CreateService("id", ServiceType, "@wikipediabot:hyrule", []byte(
- `{"api_key":"`+apiKey+`"}`,
- ))
+ srv, err := types.CreateService("id", ServiceType, "@wikipediabot:hyrule", []byte(fmt.Sprintf(`{"api_key":"%s"}`, apiKey)))
if err != nil {
t.Fatal("Failed to create Wikipedia service: ", err)
}
From 37b234c9d2d42e52723e5b3ffadf5e15e3309af3 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Tue, 21 Feb 2017 21:54:45 +0000
Subject: [PATCH 6/9] Fix tests
---
.../services/wikipedia/wikipedia_test.go | 41 ++++++-------------
1 file changed, 13 insertions(+), 28 deletions(-)
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
index 924ba99..d60b8da 100644
--- 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
@@ -19,30 +19,26 @@ import (
// sure all cases are handled, rather than just the general case as is here.
func TestCommand(t *testing.T) {
database.SetServiceDB(&database.NopStorage{})
- apiKey := "secret"
- wikipediaImageURL := "https://www.wikipediaapis.com/customsearch/v1"
+ 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) {
- wikipediaURL := "https://www.wikipediaapis.com/customsearch/v1"
query := req.URL.Query()
// Check the base API URL
- if !strings.HasPrefix(req.URL.String(), wikipediaURL) {
- t.Fatalf("Bad URL: got %s want prefix %s", req.URL.String(), wikipediaURL)
+ 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 API key
- if query.Get("key") != apiKey {
- t.Fatalf("Bad apiKey: got %s want %s", query.Get("key"), apiKey)
- }
// Check the search query
- var searchString = query.Get("q")
+ // 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 && !strings.HasPrefix(searchString, "image") {
+ if searchStringLength > 0 && searchString != searchText {
t.Fatalf("Bad search string: got \"%s\" (%d characters) ", searchString, searchStringLength)
}
@@ -76,7 +72,7 @@ func TestCommand(t *testing.T) {
httpClient = &http.Client{Transport: wikipediaTrans}
// Create the Wikipedia service
- srv, err := types.CreateService("id", ServiceType, "@wikipediabot:hyrule", []byte(fmt.Sprintf(`{"api_key":"%s"}`, apiKey)))
+ srv, err := types.CreateService("id", ServiceType, "@wikipediabot:hyrule", []byte(`{}`))
if err != nil {
t.Fatal("Failed to create Wikipedia service: ", err)
}
@@ -85,17 +81,6 @@ func TestCommand(t *testing.T) {
// Mock the response from Matrix
matrixTrans := struct{ testutils.MockTransport }{}
matrixTrans.RT = func(req *http.Request) (*http.Response, error) {
- if req.URL.String() == wikipediaImageURL { // getting the Wikipedia image
- return &http.Response{
- StatusCode: 200,
- Body: ioutil.NopCloser(bytes.NewBufferString("some image data")),
- }, nil
- } else if strings.Contains(req.URL.String(), "_matrix/media/r0/upload") { // uploading the image to matrix
- return &http.Response{
- StatusCode: 200,
- Body: ioutil.NopCloser(bytes.NewBufferString(`{"content_uri":"mxc://foo/bar"}`)),
- }, nil
- }
return nil, fmt.Errorf("Unknown URL: %s", req.URL.String())
}
matrixCli, _ := gomatrix.NewClient("https://hyrule", "@wikipediabot:hyrule", "its_a_secret")
@@ -106,9 +91,9 @@ func TestCommand(t *testing.T) {
if len(cmds) != 1 {
t.Fatalf("Unexpected number of commands: %d", len(cmds))
}
- // cmd := cmds[0]
- // _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{"image", "Czechoslovakian bananna"})
- // if err != nil {
- // t.Fatalf("Failed to process command: %s", err.Error())
- // }
+ cmd := cmds[0]
+ _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{searchText})
+ if err != nil {
+ t.Fatalf("Failed to process command: %s", err.Error())
+ }
}
From 7551e730db40294be14657ed9593f8ad266515e1 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Tue, 21 Feb 2017 22:02:00 +0000
Subject: [PATCH 7/9] Improve code readability & general cleanup
---
.../go-neb/services/wikipedia/wikipedia.go | 17 ++++++++++-------
1 file changed, 10 insertions(+), 7 deletions(-)
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
index c7b95c6..a599a2e 100644
--- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -64,27 +64,27 @@ func usageMessage() *gomatrix.TextMessage {
}
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 to search for.
+ // Get the query text and per,form search
querySentence := strings.Join(args, " ")
-
searchResultPage, err := s.text2Wikipedia(querySentence)
-
if err != nil {
return nil, err
}
- if searchResultPage.Extract == "" {
+ // No article extracts
+ if searchResultPage == nil || searchResultPage.Extract == "" {
return gomatrix.TextMessage{
MsgType: "m.notice",
- Body: "No results found!",
+ Body: "No results",
}, nil
}
+ // Convert article HTML to text
extractText, err := html2text.FromString(searchResultPage.Extract)
if err != nil {
return gomatrix.TextMessage{
@@ -101,6 +101,7 @@ func (s *Service) cmdWikipediaSearch(client *gomatrix.Client, roomID, userID str
// 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,
@@ -127,6 +128,7 @@ func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) {
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()
@@ -137,8 +139,9 @@ func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) {
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("Request error: %d, %s", res.StatusCode, response2String(res))
}
- var searchResults wikipediaSearchResults
+ // 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())
From 7cb153d0d02ce8084cc8a6c88c9f7cae1b471da2 Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Tue, 21 Feb 2017 23:25:39 +0000
Subject: [PATCH 8/9] Automatically follow redirects
---
src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go | 1 +
1 file changed, 1 insertion(+)
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
index a599a2e..dfb59e5 100644
--- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -122,6 +122,7 @@ func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) {
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
From ec97260b181a80088d7ca922870b8df99758ae4d Mon Sep 17 00:00:00 2001
From: Richard Lewis
Date: Wed, 22 Feb 2017 14:38:01 +0000
Subject: [PATCH 9/9] Comments to show intended structure use
---
src/github.com/matrix-org/go-neb/services/google/google.go | 2 +-
.../matrix-org/go-neb/services/wikipedia/wikipedia.go | 3 +++
2 files changed, 4 insertions(+), 1 deletion(-)
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
index dfb59e5..39d9fab 100644
--- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
+++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go
@@ -21,14 +21,17 @@ 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"`