2016-10-25 15:56:08 -07:00
|
|
|
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
|
|
|
|
//
|
|
|
|
// This software (Documize Community Edition) is licensed under
|
|
|
|
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
|
|
|
|
//
|
|
|
|
// You can operate outside the AGPL restrictions by purchasing
|
|
|
|
// Documize Enterprise Edition and obtaining a commercial license
|
|
|
|
// by contacting <sales@documize.com>.
|
|
|
|
//
|
|
|
|
// https://documize.com
|
|
|
|
|
2017-07-18 21:55:17 +01:00
|
|
|
package link
|
2016-10-25 15:56:08 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
2017-07-26 20:03:23 +01:00
|
|
|
"github.com/documize/community/model/link"
|
2017-07-18 21:55:17 +01:00
|
|
|
"golang.org/x/net/html"
|
2016-10-25 15:56:08 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// GetContentLinks returns Documize generated <a> links.
|
|
|
|
// such links have an identifying attribute e.g. <a data-documize='true'...
|
2017-07-26 20:03:23 +01:00
|
|
|
func GetContentLinks(body string) (links []link.Link) {
|
2016-10-25 15:56:08 -07:00
|
|
|
z := html.NewTokenizer(strings.NewReader(body))
|
|
|
|
|
|
|
|
for {
|
|
|
|
tt := z.Next()
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case tt == html.ErrorToken:
|
|
|
|
// End of the document, we're done
|
|
|
|
return
|
|
|
|
case tt == html.StartTagToken:
|
|
|
|
t := z.Token()
|
|
|
|
|
|
|
|
// Check if the token is an <a> tag
|
|
|
|
isAnchor := t.Data == "a"
|
|
|
|
if !isAnchor {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract the content link
|
|
|
|
ok, link := getLink(t)
|
|
|
|
if ok {
|
|
|
|
links = append(links, link)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper function to pull the href attribute from a Token
|
2017-07-26 20:03:23 +01:00
|
|
|
func getLink(t html.Token) (ok bool, link link.Link) {
|
2016-10-25 15:56:08 -07:00
|
|
|
ok = false
|
|
|
|
|
|
|
|
// Iterate over all of the Token's attributes until we find an "href"
|
|
|
|
for _, a := range t.Attr {
|
|
|
|
switch a.Key {
|
|
|
|
case "data-documize":
|
|
|
|
ok = true
|
|
|
|
case "data-link-id":
|
|
|
|
link.RefID = strings.TrimSpace(a.Val)
|
2016-10-26 17:31:05 -07:00
|
|
|
case "data-link-space-id":
|
|
|
|
link.FolderID = strings.TrimSpace(a.Val)
|
2016-10-27 15:44:40 -07:00
|
|
|
case "data-link-target-document-id":
|
|
|
|
link.TargetDocumentID = strings.TrimSpace(a.Val)
|
2016-10-25 15:56:08 -07:00
|
|
|
case "data-link-target-id":
|
2016-10-27 16:53:36 -07:00
|
|
|
link.TargetID = strings.TrimSpace(a.Val)
|
2016-10-25 15:56:08 -07:00
|
|
|
case "data-link-type":
|
|
|
|
link.LinkType = strings.TrimSpace(a.Val)
|
2018-07-09 14:41:55 -04:00
|
|
|
case "data-external-id":
|
|
|
|
link.ExternalID = strings.TrimSpace(a.Val)
|
2016-10-25 15:56:08 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|