siegfried.go 2.05 KB
Newer Older
Jürgen Enge's avatar
Jürgen Enge committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
package memocrawler

import (
	"encoding/json"
	"github.com/goph/emperror"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type SFIdentifier struct {
	Name    string `json:"name,omitempty"`
	Details string `json:"details,omitempty"`
}

type SFMatches struct {
	Ns      string `json:"ns,omitempty"`
	Id      string `json:"id,omitempty"`
	Format  string `json:"format,omitempty"`
	Version string `json:"version,omitempty"`
	Mime    string `json:"mime,omitempty"`
	Basis   string `json:"basis,omitempty"`
	Warning string `json:"warning,omitempty"`
}

type SFFiles struct {
	Filename string      `json:"filename,omitempty"`
	Filesize int64       `json:"filesize,omitempty"`
	Modified string      `json:"modified,omitempty"`
	Errors   string      `json:"errors,omitempty"`
	Matches  []SFMatches `json:"matches,omitempty"`
}

type SF struct {
	Siegfried   string         `json:"siegfried,omitempty"`
	Scandate    string         `json:"scandate,omitempty"`
	Signature   string         `json:"signature,omitempty"`
	Created     string         `json:"created,omitempty"`
	Identifiers []SFIdentifier `json:"identfiers,omitempty"`
	Files       []SFFiles      `json:"files,omitempty"`
}

type Siegfried struct {
	surl string
}

func (sf *Siegfried) Get( filename string ) ([]SFMatches, error) {
	urlstring := strings.Replace(sf.surl, "[[PATH]]", url.QueryEscape(filename), -1)

	resp, err := http.Get(urlstring)
	if err != nil {
		return nil, emperror.Wrapf(err, "cannot query siegfried - %v", urlstring)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, emperror.Wrapf(err, "status not ok - %v -> %v", urlstring, resp.Status)
	}
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, emperror.Wrapf(err, "error reading body - %v", urlstring)
	}

	result := SF{}
	err = json.Unmarshal(bodyBytes, &result)
	if err != nil {
		return nil, emperror.Wrapf(err, "error decoding json - %v", string(bodyBytes))
	}
	if len(result.Files) == 0 {
		return nil, emperror.Wrapf(err, "no file in sf result - %v", string(bodyBytes))
	}
	return result.Files[0].Matches, nil
}