anydesk

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2020 License: MIT Imports: 13 Imported by: 0

README

AnyDesk REST API client

Unoffical REST API client, written in Go.

license GoDoc go report card

Usage

package main

import (
	"fmt"
	"github.com/adrianrudnik/anydesk"
	"net/http"
	"os"
	"time"
)

func main() {
	api := anydesk.NewAPI(os.Getenv("LICENSE_ID"), os.Getenv("API_PASSWORD"))

	// Optional: Decrease timeouts
	api.HTTPClient = &http.Client{Timeout: 5 * time.Second}

	// Optional: Switch to Enterprise API
	api.APIEndpoint = "https://yourinstance:8081"

	request := anydesk.NewAuthenticationRequest()
	response, _ := request.Do(api)

	fmt.Printf("Status: %s, License: %s", response.Result, response.LicenseID)
}

Documentation

Overview

Package anydesk provides an API client towards the AnyDesk REST API that is available with professional and enterprise licenses.

Debugging

If you need to see specifics about the API requests made by this library you can enable the debug mode and request request and response information directly from results.

api := NewAPI("license", "password")
r := NewAuthenticationRequest()

SetDebug(true)
r.Do(api)

fmt.Printf(
    "Url: %s, Response body: %s",
    r.GetDebug().RequestURL,
    r.GetDebug().ResponseBody,
)

Pagination

There are several ways to use the paginated requests:

request := anydesk.NewSessionListRequest(nil)

// assign directly with
request.Limit = 10
request.Offset = 100

// assign everything at once with
request.PaginationOptions = &anydesk.PaginationOptions{
    Offset: 0,
    Limit:  0,
    Sort:   "",
    Order:  "",
}

Index

Examples

Constants

View Source
const (
	// Infinite is used by various calls to indicate unlimited results/items
	Infinite = int64(-1)
)

Variables

This section is empty.

Functions

func SetDebug

func SetDebug(enable bool)

SetDebug switches the API request / response debug information collection to the given value. After enabling the debug mode, raw details about requests and their response can be queried:

Example
api := NewAPI("license", "password")

SetDebug(true)

r := NewAuthenticationRequest()
r.Do(api)

fmt.Printf(
	"Url: %s, Response body: %s",
	r.GetDebug().RequestURL,
	r.GetDebug().ResponseBody,
)
Output:

Types

type API

type API struct {
	// API license ID as provided by AnyDesk support
	LicenseID string `json:"license_id"`

	// API password as provided by AnyDesk support
	APIPassword string `json:"api_password"`

	// API endpoint to be used
	APIEndpoint string `json:"api_endpoint"`

	// The http client used for API requests.
	// Can be used or overwritten for timeout and transport layer configuration.
	HTTPClient *http.Client
}

API contains all information about the AnyDesk API endpoint and configurable options.

func NewAPI

func NewAPI(licenseID string, apiPassword string) *API

NewAPI returns an initialized AnyDesk API configuration used with a Professional license.

func (*API) Do

func (api *API) Do(request APIRequest) (body []byte, err error)

Do will execute a given AnyDesk API request and return the plain json as string.

func (*API) DoPaginated

func (api *API) DoPaginated(request PaginatedAPIRequest) (body []byte, err error)

DoPaginated will execute a given AnyDesk API request and return the plain json as string. In addition to the simple API.Do it will engrave pagination options into the request.

func (*API) GetRequestToken

func (api *API) GetRequestToken(request *BaseRequest) string

GetRequestToken generates the request token used for the API request.

type APINotFoundError

type APINotFoundError struct {
}

APINotFoundError will be thrown when a API request could not find any specifc data

func (*APINotFoundError) Error

func (e *APINotFoundError) Error() string

type APIRequest

type APIRequest interface {
	// Returns debug information
	GetDebug() *DebugInfo

	// Returns base information about the http request. This information
	// is used to compose the API request signature.
	GetRequestDetails() *BaseRequest

	// Returns the http.Request that is composed, signed and ready to execute
	GetHTTPRequest(api *API) (req *http.Request, err error)
}

APIRequest is the basic interface used for all compatible API requests.

type AuthenticationRequest

type AuthenticationRequest struct {
	*BaseRequest
}

AuthenticationRequest is used to read the "/auth" API resource.

func NewAuthenticationRequest

func NewAuthenticationRequest() *AuthenticationRequest

NewAuthenticationRequest will a clean API request against "/auth".

Example
api := NewAPI(os.Getenv("LICENSE_ID"), os.Getenv("API_PASSWORD"))

request := NewAuthenticationRequest()
response, _ := request.Do(api)

fmt.Printf("Status: %s, License: %s", response.Result, response.LicenseID)
Output:

func (*AuthenticationRequest) Do

func (req *AuthenticationRequest) Do(api *API) (r *AuthenticationResponse, err error)

Do will execute the "/auth" query against the given API.

type AuthenticationResponse

type AuthenticationResponse struct {
	// Status result, should be "success".
	Result string `json:"result"`

	// The humen readable error message.
	Error string `json:"error"`

	// Specific error code as string, i.e. "invalid_token".
	Code string `json:"code"`

	// Echoing the failed request method.
	Method string `json:"method"`

	// Echoing the failed request resource.
	Resource string `json:"resource"`

	// Echoping the failed request timestamp.
	RequestTimestamp string `json:"request-time"`

	// Echoing the failed request content hash.
	ContentHash string `json:"content-hash"`

	// Echoing the API license ID on success.
	LicenseID string `json:"license-id"`
}

AuthenticationResponse contains all available fields returned by the `/auth` API call.

type BaseRequest

type BaseRequest struct {
	Method    string      `json:"-"`
	Resource  string      `json:"-"`
	Query     *url.Values `json:"-"`
	Timestamp int64       `json:"-"`
	Content   []byte      `json:"-"`
	// contains filtered or unexported fields
}

BaseRequest contains the base information required to work against the API.

func (*BaseRequest) GetContentHash

func (r *BaseRequest) GetContentHash() string

GetContentHash generates the content hash required for the API request string generated by GetRequestString().

func (*BaseRequest) GetDebug

func (r *BaseRequest) GetDebug() *DebugInfo

GetDebug returns the the collected information of the request. The debug mode must be enabled prior:

anydesk.SetDebug(true)

func (*BaseRequest) GetHTTPRequest

func (r *BaseRequest) GetHTTPRequest(api *API) (req *http.Request, err error)

GetHTTPRequest will return the prepared HTTP request that can be used by a http.Client

func (*BaseRequest) GetRequestDetails

func (r *BaseRequest) GetRequestDetails() *BaseRequest

GetRequestDetails will return the base request details. Required by the APIRequest interface.

func (*BaseRequest) GetRequestString

func (r *BaseRequest) GetRequestString() string

GetRequestString generates the request string required for the API token generated by GetRequestToken().

type ClientDetailRequest

type ClientDetailRequest struct {
	*BaseRequest
}

ClientDetailRequest is used to read details about a single client from the REST API.

func NewClientDetailRequest

func NewClientDetailRequest(clientID int64) *ClientDetailRequest

NewClientDetailRequest returns a clean API request to retrieve client details from the API.

Example
api := NewAPI(os.Getenv("LICENSE_ID"), os.Getenv("API_PASSWORD"))

request := NewClientDetailRequest(123456789)
response, _ := request.Do(api)

fmt.Printf(
	"Version: %s, Started %s (%d seconds)",
	response.ClientVersion,
	response.LastSessions[0].StartTime(),
	response.LastSessions[0].DurationInSeconds,
)
Output:

func (*ClientDetailRequest) Do

func (req *ClientDetailRequest) Do(api *API) (r *ClientDetailResponse, err error)

Do will execute the "/auth" query against the given API.

type ClientDetailResponse

type ClientDetailResponse struct {
	// ID of the client the response is about.
	ClientID int64 `json:"cid"`

	// Current version of the clients AnyDesk software.
	ClientVersion string `json:"client-version"`

	// Currently set alias of the client.
	Alias string `json:"alias"`

	// Indicates if the client is currently online.
	Online bool `json:"online"`

	// Comment for the given client, as defined in the address book.
	Comment string `json:"comment"`

	// Seconds since the client came online.
	// Will be -1 if client is Offline, but please use the .Online attribute for check.
	OnlineSinceSeconds int64 `json:"online-time"`

	// Last five sessions that this client was involved in.
	LastSessions []SessionNode `json:"last-sessions"`
}

ClientDetailResponse contains all fields available to the client details API resource.

func (*ClientDetailResponse) OnlineSince

func (r *ClientDetailResponse) OnlineSince() time.Time

OnlineSince returns the original time when the client came online.

type ClientNode

type ClientNode struct {
	// The unique client ID of the client AnyDesk software installation.
	ClientID int64 `json:"cid"`

	// The unique client alias of the AnyDesk software installation.
	Alias string `json:"alias"`
}

ClientNode is the common structure of the API for AnyDesk clients.

type DebugInfo

type DebugInfo struct {
	// Is "true" when debug info was populated, "false" when no info was collected.
	Available bool

	// The full request URL sent by the http request.
	RequestURL *url.URL

	// The http.Request used for the request.
	Request *http.Request

	// The plain request body sent to the API.
	RequestBody []byte

	// The http.Response received by the http request.
	Response *http.Response

	// The plain response body received by the API.
	ResponseBody []byte
}

DebugInfo contains a set of raw details about the http transaction as sent and received by the AnyDesk API. If unsure, take a look at DebugInfo.Available, which indicates if any debug information was collected.

type PaginatedAPIRequest

type PaginatedAPIRequest interface {
	APIRequest

	// Returns the pagination options for the current request
	GetPaginationOptions() *PaginationOptions
}

PaginatedAPIRequest is the base interface for all api requests that support pagination.

type PaginationOptions

type PaginationOptions struct {
	// Result offset, starting at 0
	Offset int64 `json:"-"`

	// Result limit, use anydesk.Infinite for unlimited results
	Limit int64 `json:"-"`

	// Result sort by property name
	Sort string `json:"-"`

	// Result sort order, use anydesk.OrderAsc or anydesk.OrderDesc
	Order SortOrder `json:"-"`
}

PaginationOptions contain all configurable settings for the pagination of API requests.

func NewPaginationOptions

func NewPaginationOptions() *PaginationOptions

NewPaginationOptions returns the default pagination options used by the AnyDesk API.

Example
api := NewAPI("license", "password")
request := NewSessionListRequest(nil)

// change default values
request.Offset = 100
request.Limit = 10

// change by clean default values
options := NewPaginationOptions()
options.Offset = 20
options.Order = OrderAsc
request.PaginationOptions = options

// change by struct
request.PaginationOptions = &PaginationOptions{
	Offset: 0,
	Limit:  0,
	Sort:   "",
	Order:  "",
}

request.Do(api)
Output:

func (*PaginationOptions) GetPaginationOptions

func (po *PaginationOptions) GetPaginationOptions() *PaginationOptions

GetPaginationOptions returns the currently configured pagination settings.

type SessionCommentChangeRequest

type SessionCommentChangeRequest struct {
	*BaseRequest
	Comment *string `json:"comment"`
}

SessionCommentChangeRequest is used to patch the /session/{id} API resource.

func NewSessionCommentChangeRequest

func NewSessionCommentChangeRequest(session string, comment string) *SessionCommentChangeRequest

NewSessionCommentChangeRequest will create an API request that will set the given comment to the given session ID. Giving an empty comment string will remove the currently set comment.

func (*SessionCommentChangeRequest) Do

func (req *SessionCommentChangeRequest) Do(api *API) (err error)

Do will execute the "/auth" query against the given API.

type SessionDirection

type SessionDirection string

SessionDirection defines the that connection direction on a paginated API request.

const (
	// DirectionIn will filter by incoming sessions only.
	DirectionIn SessionDirection = "in"

	// DirectionInOut will show all sessions, regardsless of their direction.
	DirectionInOut SessionDirection = "inout"

	// DirectionOut will filter by outgoing sessions only.
	DirectionOut SessionDirection = "out"
)

type SessionListRequest

type SessionListRequest struct {
	*BaseRequest
	*PaginationOptions
}

SessionListRequest is used to retrieve a list of stored sessions from the /sessions API resource.

func NewSessionListRequest

func NewSessionListRequest(search *SessionListSearch) *SessionListRequest

NewSessionListRequest returns a new session list query.

func (*SessionListRequest) Do

func (req *SessionListRequest) Do(api *API) (err error)

Do will execute the "/sessions" query against the given API.

type SessionListSearch

type SessionListSearch struct {
	// Limit search to client ID
	ClientID int64

	// Limit search to given sessiond direction, [in, out, inout]
	Direction SessionDirection

	// Limit search to sessions after the given time
	TimeFrom time.Time

	// Limit search to sessions up to the given time
	TimeTo time.Time
}

SessionListSearch defines all configurable search parameters for NewSessionListRequest()

type SessionNode

type SessionNode struct {
	// Indicatges of the session is currently active.
	Active bool `json:"active"`

	// The unique sesson ID for this connection.
	SessionID string `json:"sid"`

	// The source client responsible for this session.
	Source *ClientNode `json:"from"`

	// The connected client of the session.
	Target *ClientNode `json:"to"`

	// Connection start as unix-timestamp.
	StartTimestamp int64 `json:"start-time"`

	// Connection end as unix-timestamp.
	EndTimestamp int64 `json:"end-time"`

	// Total duration of the session in seconds.
	DurationInSeconds int64 `json:"duration"`

	// The comment left by the source client.
	Comment string `json:"comment"`
}

SessionNode is the common structure of session information produced by AnyDesk clients.

func (*SessionNode) Duration

func (n *SessionNode) Duration() time.Duration

Duration returns the total duration of the session.

func (*SessionNode) EndTime

func (n *SessionNode) EndTime() time.Time

EndTime returns the connection end time.

func (*SessionNode) StartTime

func (n *SessionNode) StartTime() time.Time

StartTime returns the connection start time.

type SortOrder

type SortOrder string

SortOrder defines that ordering you want on a paginated API request.

const (
	// OrderAsc indicates that you want to receive the results ascending order.
	OrderAsc SortOrder = "asc"

	// OrderDesc indicates that you want to receive the results in descencing order.
	OrderDesc SortOrder = "desc"
)

type SysinfoRequest

type SysinfoRequest struct {
	*BaseRequest
}

SysinfoRequest is used to read the "/sysinfo" API resource.

func NewSysinfoRequest

func NewSysinfoRequest() *SysinfoRequest

NewSysinfoRequest will a clean API request against "/sysinfo".

Example
api := NewAPI(os.Getenv("LICENSE_ID"), os.Getenv("API_PASSWORD"))

request := NewSysinfoRequest()
response, _ := request.Do(api)

fmt.Printf("API: %s, Max Session: %d, Active Sessions: %d",
	response.APIVersion,
	response.License.MaxSessions,
	response.Sessions.Active,
)
Output:

func (*SysinfoRequest) Do

func (req *SysinfoRequest) Do(api *API) (resp *SysinfoResponse, err error)

Do will execute the "/sysinfo" query against the given API.

type SysinfoResponse

type SysinfoResponse struct {
	Name       string `json:"name"`
	APIVersion string `json:"api-ver"`
	License    struct {
		Name             string `json:"name"`
		ExpiresTimestamp int64  `json:"expires"`
		HasExpired       bool   `json:"has-expired"` // undocumented or deprecated
		MaxClients       int    `json:"max-clients"`
		MaxSessions      int    `json:"max-sessions"`
		MaxSessionTime   int    `json:"max-session-time"`
		Namespaces       []struct {
			Name string `json:"name"`
			Size int    `json:"size"`
		} `json:"namespaces"`
		ID          string `json:"license-id"`
		Key         string `json:"license-key"`
		APIPassword string `json:"api-password"`
		PowerUser   bool   `json:"power-user"` // undocumented or deprecated
	} `json:"license"`
	Clients struct {
		Total  int `json:"total"`
		Online int `json:"online"`
	} `json:"clients"`
	Sessions struct {
		Total  int `json:"total"`
		Active int `json:"active"`
	} `json:"sessions"`
	Standalone bool `json:"standalone"`
}

SysinfoResponse contains all available fields returned by the `/sysinfo` API call.

Jump to

Keyboard shortcuts

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