client

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2023 License: BSD-3-Clause Imports: 23 Imported by: 1

Documentation

Overview

Package client implements the REST API exposed by Paperless-ngx. Paperless-ngx is a document management system transforming physical documents into a searchable online archive.

Authentication

Paperless-ngx supports multiple authentication schemes. UsernamePasswordAuth implements HTTP basic authentication and TokenAuth authentication tokens.

Pagination

APIs returning lists of items support pagination (e.g. Client.ListDocuments). The ListOptions struct embedded in the API-specific options supports specifying the page to request. Pagination tokens are available via the Response struct.

Example (Filter)
cl := New(Options{ /* … */ })

var opt ListStoragePathsOptions

opt.Ordering.Field = "name"
opt.Name.ContainsIgnoringCase = String("sales")
opt.Path.StartsWithIgnoringCase = String("2019/")

for {
	got, resp, err := cl.ListStoragePaths(context.Background(), opt)
	if err != nil {
		log.Fatalf("Listing storage paths failed: %v", err)
	}

	for _, i := range got {
		log.Printf("%s (%d documents)", i.Name, i.DocumentCount)
	}

	if resp.NextPage == nil {
		break
	}

	opt.Page = resp.NextPage
}
Output:

Example (Pagination)
cl := New(Options{ /* … */ })

var opt ListDocumentsOptions
var all []Document

for {
	documents, resp, err := cl.ListDocuments(context.Background(), opt)
	if err != nil {
		log.Fatalf("Listing documents failed: %v", err)
	}

	all = append(all, documents...)

	if resp.NextPage == nil {
		break
	}

	opt.Page = resp.NextPage
}

log.Printf("Received %d documents in total.", len(all))
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool allocates a new bool value to store v and returns a pointer to it.

func DefaultWaitForTaskCondition

func DefaultWaitForTaskCondition(task *Task) error

DefaultWaitForTaskCondition waits for a terminal status (success, failure or revoked).

func Int

func Int(v int) *int

Int allocates a new int value to store v and returns a pointer to it.

func Int64

func Int64(v int64) *int64

Int64 allocates a new int64 value to store v and returns a pointer to it.

func String

func String(v string) *string

String allocates a new string value to store v and returns a pointer to it.

func Time

func Time(v time.Time) *time.Time

Time allocates a new time.Time value to store v and returns a pointer to it.

Types

type AuthMechanism

type AuthMechanism interface {
	// contains filtered or unexported methods
}

type CharFilterSpec

type CharFilterSpec struct {
	EqualsIgnoringCase     *string
	StartsWithIgnoringCase *string
	EndsWithIgnoringCase   *string
	ContainsIgnoringCase   *string
}

CharFilterSpec contains filters available on character/string fields. All comparison are case-insensitive.

func (CharFilterSpec) EncodeValues

func (s CharFilterSpec) EncodeValues(key string, v *url.Values) error

type Client

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

func New

func New(opts Options) *Client

New creates a new client instance.

func (*Client) CreateCorrespondent

func (c *Client) CreateCorrespondent(ctx context.Context, data *Correspondent) (*Correspondent, *Response, error)

func (*Client) CreateDocumentType

func (c *Client) CreateDocumentType(ctx context.Context, data *DocumentType) (*DocumentType, *Response, error)

func (*Client) CreateStoragePath

func (c *Client) CreateStoragePath(ctx context.Context, data *StoragePath) (*StoragePath, *Response, error)

func (*Client) CreateTag

func (c *Client) CreateTag(ctx context.Context, data *Tag) (*Tag, *Response, error)

func (*Client) DeleteCorrespondent

func (c *Client) DeleteCorrespondent(ctx context.Context, id int64) (*Response, error)

func (*Client) DeleteDocument

func (c *Client) DeleteDocument(ctx context.Context, id int64) (*Response, error)

func (*Client) DeleteDocumentType

func (c *Client) DeleteDocumentType(ctx context.Context, id int64) (*Response, error)

func (*Client) DeleteStoragePath

func (c *Client) DeleteStoragePath(ctx context.Context, id int64) (*Response, error)

func (*Client) DeleteTag

func (c *Client) DeleteTag(ctx context.Context, id int64) (*Response, error)

func (*Client) DownloadDocumentArchived

func (c *Client) DownloadDocumentArchived(ctx context.Context, w io.Writer, id int64) (*DownloadResult, *Response, error)

DownloadDocumentArchived retrieves an archived PDF/A file generated from the originally consumed file. The archived version may not be available and the API may return the original. [DownloadDocumentOriginal] for additional details.

func (*Client) DownloadDocumentOriginal

func (c *Client) DownloadDocumentOriginal(ctx context.Context, w io.Writer, id int64) (*DownloadResult, *Response, error)

DownloadDocumentOriginal retrieves the document in the format originally consumed by Paperless. The file format can be determined using [DownloadResult.ContentType].

The content of the document is written to the given writer. To verify that the document is complete (the HTTP request may have been terminated early) the size and/or checksum can be verified with [GetDocumentMetadata].

func (*Client) DownloadDocumentThumbnail

func (c *Client) DownloadDocumentThumbnail(ctx context.Context, w io.Writer, id int64) (*DownloadResult, *Response, error)

DownloadDocumentThumbnail retrieves a preview image of the document. See [DownloadDocumentOriginal] for additional details.

func (*Client) GetCorrespondent

func (c *Client) GetCorrespondent(ctx context.Context, id int64) (*Correspondent, *Response, error)

func (*Client) GetDocument

func (c *Client) GetDocument(ctx context.Context, id int64) (*Document, *Response, error)

func (*Client) GetDocumentMetadata

func (c *Client) GetDocumentMetadata(ctx context.Context, id int64) (*DocumentMetadata, *Response, error)

func (*Client) GetDocumentType

func (c *Client) GetDocumentType(ctx context.Context, id int64) (*DocumentType, *Response, error)

func (*Client) GetLog

func (c *Client) GetLog(ctx context.Context, name string) ([]LogEntry, *Response, error)

GetLog retrieves all entries of the named log file.

func (*Client) GetStoragePath

func (c *Client) GetStoragePath(ctx context.Context, id int64) (*StoragePath, *Response, error)

func (*Client) GetTag

func (c *Client) GetTag(ctx context.Context, id int64) (*Tag, *Response, error)

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, taskID string) (*Task, *Response, error)

func (*Client) ListAllCorrespondents added in v0.0.3

func (c *Client) ListAllCorrespondents(ctx context.Context, opts ListCorrespondentsOptions, handler func(context.Context, Correspondent) error) error

ListAllCorrespondents iterates over all correspondents matching the filters specified in opts, invoking handler for each.

func (*Client) ListAllDocumentTypes added in v0.0.3

func (c *Client) ListAllDocumentTypes(ctx context.Context, opts ListDocumentTypesOptions, handler func(context.Context, DocumentType) error) error

ListAllDocumentTypes iterates over all document types matching the filters specified in opts, invoking handler for each.

func (*Client) ListAllDocuments added in v0.0.3

func (c *Client) ListAllDocuments(ctx context.Context, opts ListDocumentsOptions, handler func(context.Context, Document) error) error

ListAllDocuments iterates over all documents matching the filters specified in opts, invoking handler for each.

func (*Client) ListAllStoragePaths added in v0.0.3

func (c *Client) ListAllStoragePaths(ctx context.Context, opts ListStoragePathsOptions, handler func(context.Context, StoragePath) error) error

ListAllStoragePaths iterates over all storage paths matching the filters specified in opts, invoking handler for each.

func (*Client) ListAllTags added in v0.0.3

func (c *Client) ListAllTags(ctx context.Context, opts ListTagsOptions, handler func(context.Context, Tag) error) error

ListAllTags iterates over all tags matching the filters specified in opts, invoking handler for each.

func (*Client) ListCorrespondents

func (c *Client) ListCorrespondents(ctx context.Context, opts ListCorrespondentsOptions) ([]Correspondent, *Response, error)

func (*Client) ListDocumentTypes

func (c *Client) ListDocumentTypes(ctx context.Context, opts ListDocumentTypesOptions) ([]DocumentType, *Response, error)

func (*Client) ListDocuments

func (c *Client) ListDocuments(ctx context.Context, opts ListDocumentsOptions) ([]Document, *Response, error)

func (*Client) ListLogs

func (c *Client) ListLogs(ctx context.Context) ([]string, *Response, error)

ListLogs retrieves the names of available log files.

func (*Client) ListStoragePaths

func (c *Client) ListStoragePaths(ctx context.Context, opts ListStoragePathsOptions) ([]StoragePath, *Response, error)

func (*Client) ListTags

func (c *Client) ListTags(ctx context.Context, opts ListTagsOptions) ([]Tag, *Response, error)

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context) ([]Task, *Response, error)

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping tests whether the API is available.

func (*Client) UpdateCorrespondent

func (c *Client) UpdateCorrespondent(ctx context.Context, id int64, data *Correspondent) (*Correspondent, *Response, error)

func (*Client) UpdateDocument

func (c *Client) UpdateDocument(ctx context.Context, id int64, data *Document) (*Document, *Response, error)

func (*Client) UpdateDocumentType

func (c *Client) UpdateDocumentType(ctx context.Context, id int64, data *DocumentType) (*DocumentType, *Response, error)

func (*Client) UpdateStoragePath

func (c *Client) UpdateStoragePath(ctx context.Context, id int64, data *StoragePath) (*StoragePath, *Response, error)

func (*Client) UpdateTag

func (c *Client) UpdateTag(ctx context.Context, id int64, data *Tag) (*Tag, *Response, error)

func (*Client) UploadDocument

func (c *Client) UploadDocument(ctx context.Context, r io.Reader, opts DocumentUploadOptions) (*DocumentUpload, *Response, error)

Upload a file. Returns immediately and without error if the document consumption process was started successfully. No additional status information about the consumption process is available immediately. Poll the returned task ID to wait for the consumption.

func (*Client) WaitForTask

func (c *Client) WaitForTask(ctx context.Context, taskID string, opts WaitForTaskOptions) (*Task, error)

WaitForTask polls the status of a task until it reaches a terminal status (success, failure or revoked). Task failures are reported as an error of type TaskError.

type Color

type Color struct {
	R, G, B uint8
}

func NewColor

func NewColor(src color.Color) Color

NewColor converts any color implementing the color.Color interface.

func (Color) MarshalJSON

func (c Color) MarshalJSON() ([]byte, error)

func (Color) RGBA

func (c Color) RGBA() (r, g, b, a uint32)

RGBA implements color.Color.RGBA.

func (*Color) UnmarshalJSON

func (c *Color) UnmarshalJSON(data []byte) error

type Correspondent

type Correspondent struct {
	ID                 int64             `json:"id"`
	Slug               string            `json:"slug"`
	Name               string            `json:"name"`
	Match              string            `json:"match"`
	MatchingAlgorithm  MatchingAlgorithm `json:"matching_algorithm"`
	IsInsensitive      bool              `json:"is_insensitive"`
	DocumentCount      int64             `json:"document_count"`
	LastCorrespondence *time.Time        `json:"last_correspondence"`
}

type DateTimeFilterSpec

type DateTimeFilterSpec struct {
	// Set to a non-nil value to only include newer items.
	Gt *time.Time

	// Set to a non-nil value to only include older items.
	Lt *time.Time
}

func (DateTimeFilterSpec) EncodeValues

func (s DateTimeFilterSpec) EncodeValues(key string, v *url.Values) error

type Document

type Document struct {
	// ID of the document. Read-only.
	ID int64 `json:"id"`

	// Title of the document.
	Title string `json:"title"`

	// Plain-text content of the document.
	Content string `json:"content"`

	// List of tag IDs assigned to this document, or empty list.
	Tags []int64 `json:"tags"`

	// Document type of this document, or nil.
	DocumentType *int64 `json:"document_type"`

	// Correspondent of this document or nil.
	Correspondent *int64 `json:"correspondent"`

	// Storage path of this document or nil.
	StoragePath *int64 `json:"storage_path"`

	// The date time at which this document was created.
	Created time.Time `json:"created"`

	// The date at which this document was last edited in paperless. Read-only.
	Modified time.Time `json:"modified"`

	// The date at which this document was added to paperless. Read-only.
	Added time.Time `json:"added"`

	// The identifier of this document in a physical document archive.
	ArchiveSerialNumber *int64 `json:"archive_serial_number"`

	// Verbose filename of the original document. Read-only.
	OriginalFileName string `json:"original_file_name"`

	// Verbose filename of the archived document. Read-only. Nil if no archived document is available.
	ArchivedFileName *string `json:"archived_file_name"`
}

type DocumentMetadata

type DocumentMetadata struct {
	OriginalFilename      string                    `json:"original_filename"`
	OriginalMediaFilename string                    `json:"media_filename"`
	OriginalChecksum      string                    `json:"original_checksum"`
	OriginalSize          int64                     `json:"original_size"`
	OriginalMimeType      string                    `json:"original_mime_type"`
	OriginalMetadata      []DocumentVersionMetadata `json:"original_metadata"`

	HasArchiveVersion    bool                      `json:"has_archive_version"`
	ArchiveMediaFilename string                    `json:"archive_media_filename"`
	ArchiveChecksum      string                    `json:"archive_checksum"`
	ArchiveSize          int64                     `json:"archive_size"`
	ArchiveMetadata      []DocumentVersionMetadata `json:"archive_metadata"`

	Language string `json:"lang"`
}

type DocumentType

type DocumentType struct {
	ID                int64             `json:"id"`
	Slug              string            `json:"slug"`
	Name              string            `json:"name"`
	Match             string            `json:"match"`
	MatchingAlgorithm MatchingAlgorithm `json:"matching_algorithm"`
	IsInsensitive     bool              `json:"is_insensitive"`
	DocumentCount     int64             `json:"document_count"`
}

type DocumentUpload

type DocumentUpload struct {
	TaskID string
}

type DocumentUploadOptions

type DocumentUploadOptions struct {
	Filename string `url:"-"`

	// Title for the document.
	Title string `url:"title,omitempty"`

	// Datetime at which the document was created.
	Created time.Time `url:"created,omitempty"`

	// ID of a correspondent for the document.
	Correspondent *int64 `url:"correspondent,omitempty"`

	// ID of a document type for the document.
	DocumentType *int64 `url:"document_type,omitempty"`

	// Tag IDs for the document.
	Tags []int64 `url:"tags,omitempty"`

	// Archive serial number to set on the document.
	ArchiveSerialNumber *int64 `url:"archive_serial_number,omitempty"`
}

type DocumentVersionMetadata

type DocumentVersionMetadata struct {
	Namespace string `json:"namespace"`
	Prefix    string `json:"prefix"`
	Key       string `json:"key"`
	Value     string `json:"value"`
}

type DownloadResult

type DownloadResult struct {
	// MIME content type (e.g. "application/pdf").
	ContentType string

	// Parameters for body content type (e.g. "charset").
	ContentTypeParams map[string]string

	// The preferred filename as reported by the server (if any).
	Filename string

	// Length of the downloaded body in bytes.
	Length int64
}

type Flags

type Flags struct {
	// Whether to enable verbose log messages.
	DebugMode bool

	// HTTP(S) URL for Paperless.
	BaseURL string

	// Authenticate via token.
	AuthToken string

	// Read the authentication token from a file.
	AuthTokenFile string

	// Authenticate via HTTP basic authentication (username and password).
	AuthUsername string
	AuthPassword string

	// Read the password from a file.
	AuthPasswordFile string

	// HTTP headers to set on all requests.
	Header http.Header

	// Timezone for parsing timestamps without offset.
	ServerTimezone string
}

Flags contains attributes to construct a Paperless client instance. The separate "kpflag" package implements bindings for github.com/alecthomas/kingpin/v2.

func (*Flags) Build

func (f *Flags) Build() (*Client, error)

Build returns a fully configured Paperless client derived from flags.

func (*Flags) BuildOptions

func (f *Flags) BuildOptions() (*Options, error)

BuildOptions returns the client options derived from flags.

type ForeignKeyFilterSpec

type ForeignKeyFilterSpec struct {
	IsNull *bool
	ID     *int64
	Name   CharFilterSpec
}

func (ForeignKeyFilterSpec) EncodeValues

func (s ForeignKeyFilterSpec) EncodeValues(key string, v *url.Values) error

type IntFilterSpec

type IntFilterSpec struct {
	Equals *int64
	Gt     *int64
	Gte    *int64
	Lt     *int64
	Lte    *int64
	IsNull *bool
}

IntFilterSpec contains filters available on numeric fields.

func (IntFilterSpec) EncodeValues

func (s IntFilterSpec) EncodeValues(key string, v *url.Values) error

type ListCorrespondentsOptions

type ListCorrespondentsOptions struct {
	ListOptions

	Ordering OrderingSpec   `url:"ordering"`
	Name     CharFilterSpec `url:"name"`
}

type ListDocumentTypesOptions

type ListDocumentTypesOptions struct {
	ListOptions

	Ordering OrderingSpec   `url:"ordering"`
	Name     CharFilterSpec `url:"name"`
}

type ListDocumentsOptions

type ListDocumentsOptions struct {
	ListOptions

	Ordering            OrderingSpec         `url:"ordering"`
	Title               CharFilterSpec       `url:"title"`
	Content             CharFilterSpec       `url:"content"`
	ArchiveSerialNumber IntFilterSpec        `url:"archive_serial_number"`
	Created             DateTimeFilterSpec   `url:"created"`
	Added               DateTimeFilterSpec   `url:"added"`
	Modified            DateTimeFilterSpec   `url:"modified"`
	Correspondent       ForeignKeyFilterSpec `url:"correspondent"`
	Tags                ForeignKeyFilterSpec `url:"tags"`
	DocumentType        ForeignKeyFilterSpec `url:"document_type"`
	StoragePath         ForeignKeyFilterSpec `url:"storage_path"`
}

type ListOptions

type ListOptions struct {
	Page *PageToken
}

type ListStoragePathsOptions

type ListStoragePathsOptions struct {
	ListOptions

	Ordering OrderingSpec   `url:"ordering"`
	Name     CharFilterSpec `url:"name"`
	Path     CharFilterSpec `url:"path"`
}

type ListTagsOptions

type ListTagsOptions struct {
	ListOptions

	Ordering OrderingSpec   `url:"ordering"`
	Name     CharFilterSpec `url:"name"`
}

type LogEntry

type LogEntry struct {
	Time    time.Time
	Level   string
	Module  string
	Message string
}

type Logger

type Logger interface {
	Errorf(format string, v ...any)
	Warnf(format string, v ...any)
	Debugf(format string, v ...any)
}

type MatchingAlgorithm

type MatchingAlgorithm int
const (
	MatchUnspecified MatchingAlgorithm = iota

	// Any word.
	MatchAny

	// All words.
	MatchAll

	// Exact match.
	MatchLiteral

	// Regular expression.
	MatchRegex

	// Fuzzy word.
	MatchFuzzy

	// Automatic using a document classification model.
	MatchAuto
)

func (MatchingAlgorithm) String

func (i MatchingAlgorithm) String() string

type Options

type Options struct {
	// Paperless URL. May include a path.
	BaseURL string

	// API authentication.
	Auth AuthMechanism

	// Enable debug mode with many details logged.
	DebugMode bool

	// Logger for writing log messages. If debug mode is enabled and no logger
	// is configured all messages are written to standard library's default
	// logger (log.Default()).
	Logger Logger

	// HTTP headers to set on all requests.
	Header http.Header

	// Server's timezone for parsing timestamps without explicit offset.
	// Defaults to [time.Local].
	ServerLocation *time.Location
	// contains filtered or unexported fields
}

Options for constructing a Paperless client.

type OrderingSpec

type OrderingSpec struct {
	// Field name, e.g. "created".
	Field string

	// Set to true for descending order. Ascending is the default.
	Desc bool
}

OrderingSpec controls the sorting order for lists.

func (OrderingSpec) EncodeValues

func (o OrderingSpec) EncodeValues(key string, v *url.Values) error

type PageToken

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

func (*PageToken) EncodeValues

func (t *PageToken) EncodeValues(_ string, v *url.Values) error

type RequestError

type RequestError struct {
	StatusCode int
	Message    string
}

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) Is

func (e *RequestError) Is(other error) bool

type Response

type Response struct {
	*http.Response

	// Token for fetching next page in paginated result sets.
	NextPage *PageToken

	// Token for fetching previous page in paginated result sets.
	PrevPage *PageToken
}

type StoragePath

type StoragePath struct {
	ID                int64             `json:"id"`
	Slug              string            `json:"slug"`
	Name              string            `json:"name"`
	Match             string            `json:"match"`
	MatchingAlgorithm MatchingAlgorithm `json:"matching_algorithm"`
	IsInsensitive     bool              `json:"is_insensitive"`
	DocumentCount     int64             `json:"document_count"`
}

type Tag

type Tag struct {
	ID                int64             `json:"id"`
	Slug              string            `json:"slug"`
	Name              string            `json:"name"`
	Color             Color             `json:"color"`
	TextColor         Color             `json:"text_color"`
	Match             string            `json:"match"`
	MatchingAlgorithm MatchingAlgorithm `json:"matching_algorithm"`
	IsInsensitive     bool              `json:"is_insensitive"`
	IsInboxTag        bool              `json:"is_inbox_tag"`
	DocumentCount     int64             `json:"document_count"`
}

type Task

type Task struct {
	ID           int64      `json:"id"`
	TaskID       string     `json:"task_id"`
	TaskFileName *string    `json:"task_file_name"`
	Created      *time.Time `json:"date_created"`
	Done         *time.Time `json:"date_done"`
	Type         string     `json:"type"`
	Status       TaskStatus `json:"status"`
	Result       *string    `json:"result"`
	Acknowledged bool       `json:"acknowledged"`
}

type TaskError

type TaskError struct {
	TaskID  string
	Status  TaskStatus
	Message string
}

func (*TaskError) Error

func (e *TaskError) Error() string

func (*TaskError) Is

func (e *TaskError) Is(other error) bool

type TaskStatus

type TaskStatus int
const (
	TaskStatusUnspecified TaskStatus = iota

	// Task is waiting for execution.
	TaskPending

	// Task has been started.
	TaskStarted

	// Task has been successfully executed.
	TaskSuccess

	// Task execution resulted in failure.
	TaskFailure

	// Task is being retried.
	TaskRetry

	// Task has been revoked.
	TaskRevoked
)

Celery task states (https://docs.celeryq.dev/en/latest/userguide/tasks.html#built-in-states).

func (TaskStatus) MarshalJSON

func (s TaskStatus) MarshalJSON() ([]byte, error)

func (TaskStatus) String

func (i TaskStatus) String() string

func (TaskStatus) Terminal

func (s TaskStatus) Terminal() bool

Terminal returns whether a task with the receiving status is finished permanently.

func (*TaskStatus) UnmarshalJSON

func (s *TaskStatus) UnmarshalJSON(data []byte) error

type TokenAuth

type TokenAuth struct {
	Token string
}

Paperless authentication token.

Example
ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer ts.Close()

cl := New(Options{
	BaseURL: ts.URL,
	Auth:    &TokenAuth{"mytoken1234"},
})

if err := cl.Ping(context.Background()); err != nil {
	fmt.Printf("Pinging server failed: %v\n", err)
} else {
	fmt.Println("Success!")
}
Output:

Success!

type UsernamePasswordAuth

type UsernamePasswordAuth struct {
	Username string
	Password string
}

HTTP basic authentication with a username and password.

type WaitForTaskConditionFunc

type WaitForTaskConditionFunc func(*Task) error

type WaitForTaskOptions

type WaitForTaskOptions struct {
	// Condition returns nil when the task is considered finished.
	// [DefaultWaitForTaskCondition] is the default implementation.
	Condition WaitForTaskConditionFunc

	// Maximum amount of time to wait. Defaults to one hour.
	MaxElapsedTime time.Duration
}

Jump to

Keyboard shortcuts

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