hoist

package module
v0.0.0-...-58a2248 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 19 Imported by: 0

README

NameCrane Hoist

NameCrane Hoist is a Go library for NameCrane's file storage API.

Features

  • File access via direct API calls
  • afero driver for "filesystem" mocking

Planned:

  • Cache implementation using SignalR events (Request full tree once, update as-needed)
  • Calendar, Task, etc API implementations?

Installation

go get github.com/namecrane/hoist

Example

// Define our API URL (note that you can use custom domains as well)
apiUrl := "https://us1.workspace.org"

// Create an auth manager
auth := hoist.NewAuthManager(apiUrl)

// Authenticate a user
if err := auth.Authenticate(context.Background(), "username", "password", ""); err != nil {
	log.Fatal(err)
}

// Create a client
client := hoist.NewClient(apiUrl, auth)

// Do things with the client, like get the root folder(s)
folders, err := client.GetFolders(context.Background())

if err != nil {
	log.Fatal(err)
}

// folders[0] will always be the root folder
log.Println(folders[0].Name)
Multi user mode

If you wish to use multi-user mode, all Client functions can be called with a value on the context named "username" which will specify which user to use. Users MUST be authenticated with auth.Authenticate first.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoToken             = errors.New("could not find access token")
	ErrUnexpectedType      = errors.New("expected context value to be string")
	ErrExpiredRefreshToken = errors.New("refresh token expired")
)
View Source
var (
	ErrUnknownType      = errors.New("unknown content type")
	ErrUnexpectedStatus = errors.New("unexpected status")
	ErrNoFolder         = errors.New("no folder found")
	ErrNoFile           = errors.New("no file found")
)
View Source
var ErrAuthFailed = errors.New("auth failed")

Functions

func ParsePath

func ParsePath(path string) (basePath, lastSegment string)

ParsePath parses the last segment off the specified path, representing either a file or directory

Types

type AuthManager

type AuthManager interface {
	Authenticate(ctx context.Context, username, password, twoFactorCode string) error
	RefreshToken(ctx context.Context) error
	GetToken(ctx context.Context) (string, error)
	ClientID() string
}

func NewAuthManager

func NewAuthManager(apiURL string, opts ...AuthManagerOption) AuthManager

NewAuthManager initializes the AuthManager.

type AuthManagerOption

type AuthManagerOption func(*authManager)

AuthManagerOption configures AuthManager for usage

func WithAuthClient

func WithAuthClient(client *http.Client) AuthManagerOption

WithAuthClient specifies the http client to use for authentication requests

func WithAuthStore

func WithAuthStore(store Store) AuthManagerOption

WithAuthStore sets the auth store for caching/storage of auth tokens

func WithClientID

func WithClientID(clientID string) AuthManagerOption

type AuthResponse

type AuthResponse struct {
	Username               string    `json:"username"`
	Token                  string    `json:"accessToken"`
	TokenExpiration        time.Time `json:"accessTokenExpiration"` // Token expiration datetime
	RefreshToken           string    `json:"refreshToken"`
	RefreshTokenExpiration time.Time `json:"refreshTokenExpiration"`
}

type Cache

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

Cache will be a caching implementation, populated on startup and then updated via SignalR events

type Client

type Client interface {
	FileClient
}

func NewClient

func NewClient(apiURL string, authManager AuthManager, opts ...ClientOption) Client

NewClient creates a new Hoist client with the specified URL and auth manager

type ClientOption

type ClientOption func(*client)

func WithHttpClient

func WithHttpClient(httpClient *http.Client) ClientOption

WithHttpClient defines the http client to use for http requests

type DiskUsage

type DiskUsage struct {
	Allowed          int64 `json:"allowed"`
	Used             int64 `json:"used"`
	Mailboxes        int64 `json:"mailboxes"`
	Appointments     int64 `json:"appointmentsUsed"`
	Contacts         int64 `json:"contactsUsed"`
	Notes            int64 `json:"notesUsed"`
	Tasks            int64 `json:"tasksUsed"`
	FileStorage      int64 `json:"fileStorageUsed"`
	MeetingWorkspace int64 `json:"meetingWorkspaceUsed"`
	ChatFiles        int64 `json:"chatFilesUsed"`
}

type EditFileParams

type EditFileParams struct {
	Password           string    `json:"password"`
	Published          bool      `json:"published"`
	PublishedUntil     time.Time `json:"publishedUntil"`
	ShortLink          string    `json:"shortLink"`
	PublicDownloadLink string    `json:"publicDownloadLink"`
}

type Events

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

Events is a helper for managing SignalR events from the server

func NewEventsClient

func NewEventsClient(apiUrl string, authManager AuthManager) *Events

NewEventsClient creates a new event client, with apiUrl and authManager similar to client. Note that you must call Events.Connect yourself.

func (*Events) Authenticate

func (c *Events) Authenticate() error

Authenticate will send a `connect` method with the bearer token to the server

func (*Events) Connect

func (c *Events) Connect() error

Connect opens a SignalR client and authenticates via Authenticate call

type File

type File struct {
	ID         string    `json:"id"`
	Name       string    `json:"fileName"`
	Type       string    `json:"type"`
	Size       int64     `json:"size"`
	DateAdded  time.Time `json:"dateAdded"`
	FolderPath string    `json:"folderPath"`
}

File represents a file object on the remote server, identified by `ID`

type FileClient

type FileClient interface {
	DiskUsageSummary(ctx context.Context) (*DiskUsage, error)
	ChunkedUpload(ctx context.Context, in io.Reader, filePath string, fileSize int64) (*File, error)
	ParsePath(path string) (basePath, lastSegment string)
	GetFolders(ctx context.Context) ([]Folder, error)
	GetFolder(ctx context.Context, folder string, opts ...FolderOpt) (*Folder, error)
	GetFiles(ctx context.Context, ids ...string) ([]File, error)
	DeleteFiles(ctx context.Context, ids ...string) error
	DownloadFile(ctx context.Context, id string, opts ...RequestOpt) (io.ReadCloser, error)
	GetFileID(ctx context.Context, dir, fileName string) (string, error)
	Find(ctx context.Context, file string) (*Folder, *File, error)
	CreateFolder(ctx context.Context, folder string) (*Folder, error)
	DeleteFolder(ctx context.Context, folder string) error
	MoveFiles(ctx context.Context, folder string, fileIDs ...string) error
	RenameFile(ctx context.Context, fileID string, name string) error
	EditFile(ctx context.Context, fileID string, params EditFileParams) error
	GetLink(ctx context.Context, fileID string) (string, string, error)
	MoveFolder(ctx context.Context, folder, newParentFolder, newName string) error
}

type Folder

type Folder struct {
	Name       string   `json:"name"`
	Path       string   `json:"path"`
	Size       int64    `json:"size"`
	Version    string   `json:"version"`
	Count      int      `json:"count"`
	Subfolders []Folder `json:"subfolders"`
	Files      []File   `json:"files"`
}

Folder represents a folder object on the remote server

func (Folder) Flatten

func (f Folder) Flatten() []Folder

Flatten takes all folders and subfolders, returning them as a single slice

func (Folder) Subfolder

func (f Folder) Subfolder(name string) *Folder

type FolderOpt

type FolderOpt func(f *folderRequest)

FolderOpt allows defining folder request options

func WithCount

func WithCount(count int) FolderOpt

WithCount specifies the number of items to return in a folder request

func WithStartIndex

func WithStartIndex(index int) FolderOpt

WithStartIndex sets the start index of a folder request

type FolderResponse

type FolderResponse struct {
	Folder Folder `json:"folder"`
	// contains filtered or unexported fields
}

type ListResponse

type ListResponse struct {
	Files []File `json:"files"`
}

type RequestOpt

type RequestOpt func(r *http.Request)

RequestOpt is a quick helper for changing request options

func WithContentType

func WithContentType(contentType string) RequestOpt

WithContentType overrides specified content types

func WithHeader

func WithHeader(key, value string) RequestOpt

WithHeader sets header values on the request

func WithURLParameter

func WithURLParameter(key string, value any) RequestOpt

WithURLParameter replaces a URL parameter encased in {} with the value

type Response

type Response struct {
	*http.Response
}

Response wraps an *http.Response and provides extra functionality

func (*Response) Close

func (r *Response) Close() error

Close is a redirect to r.Body.Close for shorthand

func (*Response) Data

func (r *Response) Data() []byte

Data is a quick and dirty "read this data" for debugging

func (*Response) Decode

func (r *Response) Decode(data any) error

Decode only supports JSON. The API is weird and returns text/plain for JSON sometimes, but it's almost always JSON.

type Store

type Store interface {
	// Set stores an authenticated user's access and refresh tokens
	Set(username string, auth AuthResponse)

	// Get retrieves an authenticated user's access and refresh token
	// This MUST return nil, nil if a stored auth does not exist
	Get(username string) (*AuthResponse, error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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