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 := ` + + + 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", + }, + { + "\n

Test text

\n\n\n\t

Test text

\n", + "Test text\n\nTest text", + }, + { + "\n

Test text
Test text

\n", + "Test text\nTest text", + }, + { + "\n

Test 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 + }{ + { + "
", + "", + }, + { + "
cell1cell2
", + "cell1 cell2", + }, + { + "
row1
row2
", + "row1\nrow2", + }, + { + ` + + +
cell1-1cell1-2
cell2-1cell2-2
`, + "cell1-1 cell1-2\ncell2-1 cell2-2", + }, + { + "_
cell
_", + "_\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 + }{ + { + ``, + ``, + }, + { + ``, + ``, + }, + { + `Example`, + ``, + }, + { + `Example`, + ``, + }, + // Images do matter if they are in a link + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `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----", + }, + { + "

    Test

    ", + "****************************\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", + }, + { + "\t
    Test
    ", + "Test", + }, + { + "
    Test line 1
    Test 2
    ", + "Test line 1\nTest 2", + }, + { + "Test 1
    Test 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 1
    level 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", + }, + { + "
    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 + }{ + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + `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 +

    + test

    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 + + test

    List:

    + + + `, + `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 +}