kwlib

package module
v0.0.0-...-8f46172 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2020 License: MIT Imports: 31 Imported by: 0

README

kwlib

-- import "github.com/cmcoffee/go-kwlib"

Usage

const (
	ERR_AUTH_UNAUTHORIZED = 1 << iota
	ERR_AUTH_PROFILE_CHANGED
	ERR_ACCESS_USER
	ERR_INVALID_GRANT
	ERR_ENTITY_DELETED_PERMANENTLY
	ERR_ENTITY_NOT_FOUND
	ERR_ENTITY_DELETED
	ERR_ENTITY_PARENT_FOLDER_DELETED
	ERR_REQUEST_METHOD_NOT_ALLOWED
	ERR_INTERNAL_SERVER_ERROR
	ERR_ENTITY_EXISTS
	ERR_ENTITY_ROLE_IS_ASSIGNED
	UNAVAILABLE
	SERVICE_UNAVAILABLE
	ERR_ENTITY_NOT_SCANNED
	ERR_ENTITY_PARENT_FOLDER_MEMBER_EXISTS
)
const (
	NONE  = ""
	SLASH = string(os.PathSeparator)
)
const TOKEN_ERR = ERR_AUTH_PROFILE_CHANGED | ERR_INVALID_GRANT | ERR_AUTH_UNAUTHORIZED

Auth token related errors.

var (
	Log             = nfo.Log
	Fatal           = nfo.Fatal
	Notice          = nfo.Notice
	Flash           = nfo.Flash
	Stdout          = nfo.Stdout
	Warn            = nfo.Warn
	Defer           = nfo.Defer
	Debug           = nfo.Debug
	Snoop           = nfo.Aux
	GetSecret       = nfo.GetSecret
	GetInput        = nfo.GetInput
	Exit            = nfo.Exit
	PleaseWait      = nfo.PleaseWait
	Stderr          = nfo.Stderr
	GetConfirm      = nfo.GetConfirm
	HideTS          = nfo.HideTS
	ShowTS          = nfo.ShowTS
	ProgressBar     = nfo.ProgressBar
	TransferMonitor = nfo.TransferMonitor
	Path            = filepath.Clean
	LeftToRight     = nfo.LeftToRight
	RightToLeft     = nfo.RightToLeft
	NoRate          = nfo.NoRate
	NeedAnswer      = nfo.NeedAnswer
	PressEnter      = nfo.PressEnter
)

Import from go-nfo.

var ErrNoUploadID = fmt.Errorf("Upload ID not found.")
var ErrUploadNoResp = fmt.Errorf("Unexpected empty resposne from server.")
var SetPath = fmt.Sprintf

SetPath shortcut.

func CompressFolder
func CompressFolder(input_folder, dest_file string) (err error)

Compresses Folder to File

func Critical
func Critical(err error)

Fatal Error Check

func DateString
func DateString(input time.Time) string

Create standard date YY-MM-DD out of time.Time.

func EnableDebug
func EnableDebug()

Enable Debug Logging Output

func Err
func Err(input ...interface{})
func ErrorCount
func ErrorCount() uint32

Returns amount of times Err has been triggered.

func HumanSize
func HumanSize(bytes int64) string

Provides human readable file sizes.

func IsKWError
func IsKWError(err error) bool

Return true if error was generated by REST call.

func KVLiteStore
func KVLiteStore(input *Database) *kvLiteStore

Wraps KVLite Databse as a auth token store.

func KWAPIError
func KWAPIError(err error, input int64) bool

Check for specific error code.

func MD5Sum
func MD5Sum(filename string) (sum string, err error)

MD5Sum function for checking files against appliance.

func MkDir
func MkDir(name ...string) (err error)

Creates folders.

func Quiet
func Quiet()

Disables Flash from being displayed.

func RandBytes
func RandBytes(sz int) []byte

Generates a random byte slice of length specified.

func ReadKWTime
func ReadKWTime(input string) (time.Time, error)

Parse Timestamps from kiteworks

func ResetErrorCount
func ResetErrorCount()
func SetParams
func SetParams(vars ...interface{}) (output []interface{})

Creates Param for KWAPI post

func Spanner
func Spanner(input interface{}) string

Prints arrays for string and int arrays, when submitted to Queries or Form post.

func SplitPath
func SplitPath(path string) (folder_path []string)

Splits path up

func WriteKWTime
func WriteKWTime(input time.Time) string

Write timestamps for kiteworks.

type APIRequest
type APIRequest struct {
	APIVer int
	Method string
	Path   string
	Params []interface{}
	Output interface{}
}

APIRequest model

type BitFlag
type BitFlag = bitflag.BitFlag
type Database
type Database struct {
}

Wrapper around go-kvlite.

func OpenCache
func OpenCache() *Database

Open a memory-only go-kvlite store.

func OpenDatabase
func OpenDatabase(file string, padlock ...byte) (*Database, error)

Opens go-kvlite sqlite database.

func SecureDatabase
func SecureDatabase(file string) (*Database, error)

Opens go-kvlite database using mac address for lock.

func (Database) Close
func (d Database) Close()

Closes go-kvlite database.

func (Database) CountKeys
func (d Database) CountKeys(table string) int

Count keys in table.

func (Database) CryptSet
func (d Database) CryptSet(table, key string, value interface{})

Encrypt value to go-kvlie, fatal on error.

func (Database) Drop
func (d Database) Drop(table string)

DB Wrappers to perform fatal error checks on each call.

func (Database) Get
func (d Database) Get(table, key string, output interface{}) bool

Retrieve value from go-kvlite.

func (Database) Keys
func (d Database) Keys(table string) []string

List keys in go-kvlite.

func (Database) Set
func (d Database) Set(table, key string, value interface{})

Save value to go-kvlite.

func (Database) Table
func (d Database) Table(table string) Table
func (Database) Tables
func (d Database) Tables() []string

List Tables in DB

func (Database) Unset
func (d Database) Unset(table, key string)

Delete value from go-kvlite.

type Error
type Error string

Error handler for const errors.

func (Error) Error
func (e Error) Error() string
type FileInfo
type FileInfo struct {
	Info os.FileInfo
}
func ScanPath
func ScanPath(parent_folder string) (folders []string, files []FileInfo)

Scans parent_folder for all subfolders and files.

type KWAPI
type KWAPI struct {
	Server         string        // kiteworks host name.
	ApplicationID  string        // Application ID set for kiteworks custom app.
	RedirectURI    string        // Redirect URI for kiteworks custom app.
	AgentString    string        // Agent-String header for calls to kiteworks.
	VerifySSL      bool          // Verify certificate for connections.
	ProxyURI       string        // Proxy for outgoing https requests.
	Snoop          bool          // Flag to snoop API calls
	RequestTimeout time.Duration // Timeout for request to be answered from kiteworks server.
	ConnectTimeout time.Duration // Timeout for TLS connection to kiteworks server.
	MaxChunkSize   int64         // Max Upload Chunksize in bytes, min = 1M, max = 68M
	Retries        uint          // Max retries on a failed call
	TokenStore     TokenStore    // TokenStore for reading and writing auth tokens securely.
}
func (*KWAPI) AuthLoop
func (K *KWAPI) AuthLoop(username string) (*KWSession, error)
func (*KWAPI) Authenticate
func (K *KWAPI) Authenticate(username string) (*KWSession, error)
func (*KWAPI) Chunks
func (K *KWAPI) Chunks(total_size int64) (total_chunks int64)

Returns chunk_size, total number of chunks and last chunk size.

func (*KWAPI) ClientSecret
func (K *KWAPI) ClientSecret(client_secret_key string)

Sets client secret key.

func (*KWAPI) Session
func (K *KWAPI) Session(username string) KWSession

Wraps a session for specfiied user.

func (*KWAPI) SetLimiter
func (K *KWAPI) SetLimiter(max_calls int)

Configures maximum number of simultaneous api calls.

func (*KWAPI) Signature
func (K *KWAPI) Signature(signature_key string)

Sets signature key.

type KWAPIClient
type KWAPIClient struct {
	*http.Client
}

KWAPI Client

func (*KWAPIClient) Do
func (c *KWAPIClient) Do(req *http.Request) (resp *http.Response, err error)
type KWAuth
type KWAuth struct {
	AccessToken  string `json:"access_token"`
	Scope        string `json:"scope"`
	RefreshToken string `json:"refresh_token"`
	Expires      int64  `json:"expires_in"`
}

kiteworks Auth token.

type KWError
type KWError struct {
}

Specific kiteworks error object.

func NewKWError
func NewKWError() *KWError

Create a new REST error.

func (*KWError) AddError
func (e *KWError) AddError(code, message string)

Add a kiteworks error to APIError

func (KWError) Error
func (e KWError) Error() string

Returns Error String.

type KWSession
type KWSession struct {
	Username string
	*KWAPI
}

kiteworks Session.

func (KWSession) Call
func (s KWSession) Call(api_req APIRequest) (err error)

kiteworks API Call Wrapper

func (KWSession) DataCall
func (s KWSession) DataCall(req APIRequest, offset, limit int) (err error)

Call handler which allows for easier getting of multiple-object arrays. An offset of -1 will provide all results, any positive offset will only return the requested results.

func (*KWSession) Download
func (S *KWSession) Download(req *http.Request) ReadSeekCloser

Perform External Download from a remote request.

func (KWSession) NewClient
func (s KWSession) NewClient() *KWAPIClient

kiteworks Client

func (KWSession) NewRequest
func (s KWSession) NewRequest(method, path string, api_ver int) (req *http.Request, err error)

New kiteworks Request.

func (*KWSession) NewUpload
func (S *KWSession) NewUpload(folder_id int, filename string, file_size int64) (int, error)

Creates a new upload for a folder.

func (*KWSession) NewVersion
func (S *KWSession) NewVersion(file_id int, filename string, file_size int64) (int, error)

Create a new file version for an existing file.

func (KWSession) Upload
func (s KWSession) Upload(filename string, upload_id int, source_reader ReadSeekCloser) (int, error)

Uploads file from specific local path, uploads in chunks, allows resume.

type PostForm
type PostForm map[string]interface{}

Form POST to KWAPI.

type PostJSON
type PostJSON map[string]interface{}

Post JSON to KWAPI.

type Query
type Query map[string]interface{}

Add Query params to KWAPI request.

type ReadSeekCloser
type ReadSeekCloser = nfo.ReadSeekCloser
type Table
type Table struct {
}
func (Table) CountKeys
func (t Table) CountKeys() int
func (Table) CryptSet
func (t Table) CryptSet(key string, value interface{})
func (Table) Keys
func (t Table) Keys() []string
func (Table) Set
func (t Table) Set(key string, value interface{})
func (Table) Unset
func (t Table) Unset(key string)
type TokenStore
type TokenStore interface {
	Save(username string, auth *KWAuth) error
	Load(username string) (*KWAuth, error)
	Delete(username string) error
}

TokenStore interface for saving and retrieving auth tokens. Errors should only be underlying issues reading/writing to the store itself.

Documentation

Index

Constants

View Source
const (
	ERR_AUTH_UNAUTHORIZED = 1 << iota
	ERR_AUTH_PROFILE_CHANGED
	ERR_ACCESS_USER
	ERR_INVALID_GRANT
	ERR_ENTITY_DELETED_PERMANENTLY
	ERR_ENTITY_NOT_FOUND
	ERR_ENTITY_DELETED
	ERR_ENTITY_PARENT_FOLDER_DELETED
	ERR_REQUEST_METHOD_NOT_ALLOWED
	ERR_INTERNAL_SERVER_ERROR
	ERR_ENTITY_EXISTS
	ERR_ENTITY_ROLE_IS_ASSIGNED
	UNAVAILABLE
	SERVICE_UNAVAILABLE
	ERR_ENTITY_NOT_SCANNED
	ERR_ENTITY_PARENT_FOLDER_MEMBER_EXISTS
)
View Source
const (
	NONE  = ""
	SLASH = string(os.PathSeparator)
)

Auth token related errors.

Variables

View Source
var (
	Log             = nfo.Log
	Fatal           = nfo.Fatal
	Notice          = nfo.Notice
	Flash           = nfo.Flash
	Stdout          = nfo.Stdout
	Warn            = nfo.Warn
	Defer           = nfo.Defer
	Debug           = nfo.Debug
	Snoop           = nfo.Aux
	GetSecret       = nfo.GetSecret
	GetInput        = nfo.GetInput
	Exit            = nfo.Exit
	PleaseWait      = nfo.PleaseWait
	Stderr          = nfo.Stderr
	GetConfirm      = nfo.GetConfirm
	HideTS          = nfo.HideTS
	ShowTS          = nfo.ShowTS
	ProgressBar     = nfo.ProgressBar
	TransferMonitor = nfo.TransferMonitor
	Path            = filepath.Clean
	LeftToRight     = nfo.LeftToRight
	RightToLeft     = nfo.RightToLeft
	NoRate          = nfo.NoRate
	NeedAnswer      = nfo.NeedAnswer
	PressEnter      = nfo.PressEnter
)

Import from go-nfo.

View Source
var ErrNoUploadID = fmt.Errorf("Upload ID not found.")
View Source
var ErrUploadNoResp = fmt.Errorf("Unexpected empty resposne from server.")
View Source
var SetPath = fmt.Sprintf

SetPath shortcut.

Functions

func CompressFolder

func CompressFolder(input_folder, dest_file string) (err error)

Compresses Folder to File

func Critical

func Critical(err error)

Fatal Error Check

func DateString

func DateString(input time.Time) string

Create standard date YY-MM-DD out of time.Time.

func EnableDebug

func EnableDebug()

Enable Debug Logging Output

func Err

func Err(input ...interface{})

func ErrorCount

func ErrorCount() uint32

Returns amount of times Err has been triggered.

func HumanSize

func HumanSize(bytes int64) string

Provides human readable file sizes.

func IsKWError

func IsKWError(err error) bool

Return true if error was generated by REST call.

func KVLiteStore

func KVLiteStore(input *Database) *kvLiteStore

Wraps KVLite Databse as a auth token store.

func KWAPIError

func KWAPIError(err error, input int64) bool

Check for specific error code.

func MD5Sum

func MD5Sum(filename string) (sum string, err error)

MD5Sum function for checking files against appliance.

func MkDir

func MkDir(name ...string) (err error)

Creates folders.

func Quiet

func Quiet()

Disables Flash from being displayed.

func RandBytes

func RandBytes(sz int) []byte

Generates a random byte slice of length specified.

func ReadKWTime

func ReadKWTime(input string) (time.Time, error)

Parse Timestamps from kiteworks

func ResetErrorCount

func ResetErrorCount()

func SetParams

func SetParams(vars ...interface{}) (output []interface{})

Creates Param for KWAPI post

func Spanner

func Spanner(input interface{}) string

Prints arrays for string and int arrays, when submitted to Queries or Form post.

func SplitPath

func SplitPath(path string) (folder_path []string)

Splits path up

func WriteKWTime

func WriteKWTime(input time.Time) string

Write timestamps for kiteworks.

Types

type APIRequest

type APIRequest struct {
	APIVer int
	Method string
	Path   string
	Params []interface{}
	Output interface{}
}

APIRequest model

type BitFlag

type BitFlag = bitflag.BitFlag

type Database

type Database struct {
	// contains filtered or unexported fields
}

Wrapper around go-kvlite.

func OpenCache

func OpenCache() *Database

Open a memory-only go-kvlite store.

func OpenDatabase

func OpenDatabase(file string, padlock ...byte) (*Database, error)

Opens go-kvlite sqlite database.

func SecureDatabase

func SecureDatabase(file string) (*Database, error)

Opens go-kvlite database using mac address for lock.

func (Database) Close

func (d Database) Close()

Closes go-kvlite database.

func (Database) CountKeys

func (d Database) CountKeys(table string) int

Count keys in table.

func (Database) CryptSet

func (d Database) CryptSet(table, key string, value interface{})

Encrypt value to go-kvlie, fatal on error.

func (Database) Drop

func (d Database) Drop(table string)

DB Wrappers to perform fatal error checks on each call.

func (Database) Get

func (d Database) Get(table, key string, output interface{}) bool

Retrieve value from go-kvlite.

func (Database) Keys

func (d Database) Keys(table string) []string

List keys in go-kvlite.

func (Database) Set

func (d Database) Set(table, key string, value interface{})

Save value to go-kvlite.

func (Database) Table

func (d Database) Table(table string) Table

func (Database) Tables

func (d Database) Tables() []string

List Tables in DB

func (Database) Unset

func (d Database) Unset(table, key string)

Delete value from go-kvlite.

type Error

type Error string

Error handler for const errors.

func (Error) Error

func (e Error) Error() string

type FileInfo

type FileInfo struct {
	Info os.FileInfo
	// contains filtered or unexported fields
}

func ScanPath

func ScanPath(parent_folder string) (folders []string, files []FileInfo)

Scans parent_folder for all subfolders and files.

type KWAPI

type KWAPI struct {
	Server         string        // kiteworks host name.
	ApplicationID  string        // Application ID set for kiteworks custom app.
	RedirectURI    string        // Redirect URI for kiteworks custom app.
	AgentString    string        // Agent-String header for calls to kiteworks.
	VerifySSL      bool          // Verify certificate for connections.
	ProxyURI       string        // Proxy for outgoing https requests.
	Snoop          bool          // Flag to snoop API calls
	RequestTimeout time.Duration // Timeout for request to be answered from kiteworks server.
	ConnectTimeout time.Duration // Timeout for TLS connection to kiteworks server.
	MaxChunkSize   int64         // Max Upload Chunksize in bytes, min = 1M, max = 68M
	Retries        uint          // Max retries on a failed call
	TokenStore     TokenStore    // TokenStore for reading and writing auth tokens securely.
	// contains filtered or unexported fields
}

func (*KWAPI) AuthLoop

func (K *KWAPI) AuthLoop(username string) (*KWSession, error)

func (*KWAPI) Authenticate

func (K *KWAPI) Authenticate(username string) (*KWSession, error)

func (*KWAPI) Chunks

func (K *KWAPI) Chunks(total_size int64) (total_chunks int64)

Returns chunk_size, total number of chunks and last chunk size.

func (*KWAPI) ClientSecret

func (K *KWAPI) ClientSecret(client_secret_key string)

Sets client secret key.

func (*KWAPI) Session

func (K *KWAPI) Session(username string) KWSession

Wraps a session for specfiied user.

func (*KWAPI) SetLimiter

func (K *KWAPI) SetLimiter(max_calls int)

Configures maximum number of simultaneous api calls.

func (*KWAPI) SetTransferLimiter

func (K *KWAPI) SetTransferLimiter(max_transfers int)

Configures maximum number of simultaneous file transfers.

func (*KWAPI) Signature

func (K *KWAPI) Signature(signature_key string)

Sets signature key.

type KWAPIClient

type KWAPIClient struct {
	*http.Client
	// contains filtered or unexported fields
}

KWAPI Client

func (*KWAPIClient) Do

func (c *KWAPIClient) Do(req *http.Request) (resp *http.Response, err error)

type KWAuth

type KWAuth struct {
	AccessToken  string `json:"access_token"`
	Scope        string `json:"scope"`
	RefreshToken string `json:"refresh_token"`
	Expires      int64  `json:"expires_in"`
}

kiteworks Auth token.

type KWError

type KWError struct {
	// contains filtered or unexported fields
}

Specific kiteworks error object.

func NewKWError

func NewKWError() *KWError

Create a new REST error.

func (*KWError) AddError

func (e *KWError) AddError(code, message string)

Add a kiteworks error to APIError

func (KWError) Error

func (e KWError) Error() string

Returns Error String.

type KWSession

type KWSession struct {
	Username string
	*KWAPI
}

kiteworks Session.

func (KWSession) Call

func (s KWSession) Call(api_req APIRequest) (err error)

kiteworks API Call Wrapper

func (KWSession) DataCall

func (s KWSession) DataCall(req APIRequest, offset, limit int) (err error)

Call handler which allows for easier getting of multiple-object arrays. An offset of -1 will provide all results, any positive offset will only return the requested results.

func (*KWSession) Download

func (S *KWSession) Download(req *http.Request) ReadSeekCloser

Perform External Download from a remote request.

func (KWSession) NewClient

func (s KWSession) NewClient() *KWAPIClient

kiteworks Client

func (KWSession) NewRequest

func (s KWSession) NewRequest(method, path string, api_ver int) (req *http.Request, err error)

New kiteworks Request.

func (*KWSession) NewUpload

func (S *KWSession) NewUpload(folder_id int, filename string, file_size int64) (int, error)

Creates a new upload for a folder.

func (*KWSession) NewVersion

func (S *KWSession) NewVersion(file_id int, filename string, file_size int64) (int, error)

Create a new file version for an existing file.

func (KWSession) Upload

func (s KWSession) Upload(filename string, upload_id int, source_reader ReadSeekCloser) (int, error)

Uploads file from specific local path, uploads in chunks, allows resume.

type PostForm

type PostForm map[string]interface{}

Form POST to KWAPI.

type PostJSON

type PostJSON map[string]interface{}

Post JSON to KWAPI.

type Query

type Query map[string]interface{}

Add Query params to KWAPI request.

type ReadSeekCloser

type ReadSeekCloser = nfo.ReadSeekCloser

type Table

type Table struct {
	// contains filtered or unexported fields
}

func (Table) CountKeys

func (t Table) CountKeys() int

func (Table) CryptSet

func (t Table) CryptSet(key string, value interface{})

func (Table) Keys

func (t Table) Keys() []string

func (Table) Set

func (t Table) Set(key string, value interface{})

func (Table) Unset

func (t Table) Unset(key string)

type TokenStore

type TokenStore interface {
	Save(username string, auth *KWAuth) error
	Load(username string) (*KWAuth, error)
	Delete(username string) error
}

TokenStore interface for saving and retrieving auth tokens. Errors should only be underlying issues reading/writing to the store itself.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL