smartling

package module
v0.0.0-...-fb0d776 Latest Latest
Warning

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

Go to latest
Published: May 12, 2022 License: MIT Imports: 11 Imported by: 0

README

Smartling SDK in Golang

Examples

Examples are located in the example_*_test.go files.

Examples suited for use with real user accounts, so to run examples you need at least obtain your User ID and Token Secret.

Then, obtained User ID, Token Secret and other parameters should be populated in the example_credentials_test.go file.

To run all examples, just run go test.

To run specific example it must be specified like go test -run Projects_List (will run example from examples_projects_list_test.go).

Documentation

Overview

Package smartling is a client implementation of the Smartling Translation API v2 as documented at https://help.smartling.com/v1.0/reference

Index

Constants

View Source
const (
	// WithAuthentication equal to use of authentication in request.
	WithAuthentication = AuthenticationOption(true)

	// WithoutAuthentication equal to not use of authentication in request.
	WithoutAuthentication = AuthenticationOption(false)
)
View Source
const (
	// RetrieveDefault specifies that Smartling will decide what type of
	// translation will be returned.
	RetrieveDefault RetrievalType = ""

	// RetrievePending specifies that Smartling returns any translations
	// (including non-published translations)
	RetrievePending = "pending"

	// RetrievePublished specifies that Smartling returns only
	// published/pre-published translations.
	RetrievePublished = "published"

	// RetrievePseudo specifies that Smartling returns a modified version of
	// the original text with certain characters transformed and the text
	// expanded.
	RetrievePseudo = "pseudo"

	// RetrieveChromeInstrumented specifies that Smartling returns a modified
	// version of the original file with strings wrapped in a specific set of
	// Unicode symbols that can later be recognized and matched by the Chrome
	// Context Capture Extension
	RetrieveChromeInstrumented = "contextMatchingInstrumented"
)
View Source
const (
	FileTypeUnknown        FileType = ""
	FileTypeAndroid                 = "android"
	FileTypeIOS                     = "ios"
	FileTypeGettext                 = "gettext"
	FileTypeHTML                    = "html"
	FileTypeJavaProperties          = "javaProperties"
	FileTypeYAML                    = "yaml"
	FileTypeXLIFF                   = "xliff"
	FileTypeXML                     = "xml"
	FileTypeJSON                    = "json"
	FileTypeDOCX                    = "docx"
	FileTypePPTX                    = "pptx"
	FileTypeXLSX                    = "xlsx"
	FileTypeIDML                    = "idml"
	FileTypeQt                      = "qt"
	FileTypeResx                    = "resx"
	FileTypePlaintext               = "plaintext"
	FileTypeCSV                     = "csv"
	FileTypeStringsdict             = "stringsdict"
)

Android and next are types that are supported by Smartling API.

Variables

View Source
var (
	// Version is a API SDK version, sent in User-Agent header.
	Version = "1.0"

	// DefaultBaseURL specifies base URL which will be used for calls unless
	// other is specified in the Client struct.
	DefaultBaseURL = "https://api.smartling.com"

	// DefaultHTTPClient specifies default HTTP client which will be used
	// for calls unless other is specified in the Client struct.
	DefaultHTTPClient = http.Client{Timeout: 120 * time.Second}

	// DefaultUserAgent is a string that will be sent in User-Agent header.
	DefaultUserAgent = "smartling-api-sdk-go"
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Cause    error
	Code     string
	URL      string
	Params   url.Values
	Payload  []byte
	Response []byte
	Headers  *http.Header
}

func (APIError) Error

func (err APIError) Error() string

func (APIError) Is

func (err APIError) Is(target error) bool

func (APIError) Unwrap

func (err APIError) Unwrap() error

type AuthenticationOption

type AuthenticationOption bool

AuthenticationOption specifies should request to API use authentication or not. See Post and Get methods.

type Client

type Client struct {
	BaseURL     string
	Credentials *Credentials

	HTTP *http.Client

	Logger struct {
		Infof  LogFunction
		Debugf LogFunction
	}

	UserAgent string
}

Client represents Smartling API client.

func NewClient

func NewClient(userID string, tokenSecret string) *Client

NewClient returns new Smartling API client with specified authentication data.

func (*Client) Authenticate

func (client *Client) Authenticate() error

Authenticate checks that access and refresh tokens are valid and refreshes them if needed.

func (*Client) DeleteFile

func (client *Client) DeleteFile(
	projectID string,
	uri string,
) error

DeleteFile removes specified files from project.

func (*Client) DownloadFile

func (client *Client) DownloadFile(
	projectID string,
	uri string,
) (io.Reader, error)

DownloadFile downloads original file from project.

func (*Client) DownloadTranslation

func (client *Client) DownloadTranslation(
	projectID string,
	localeID string,
	request FileDownloadRequest,
) (io.Reader, error)

DownloadTranslation downloads specified translated file for specified locale. Check FileDownloadRequest for more options.

func (*Client) Get

func (client *Client) Get(
	url string,
	params url.Values,
	options ...interface{},
) (io.ReadCloser, int, error)

Get performs raw GET request to the Smartling API. You probably do not want to use it.

func (*Client) GetFileStatus

func (client *Client) GetFileStatus(
	projectID string,
	fileURI string,
) (*FileStatus, error)

GetFileStatus returns file status.

func (*Client) GetJSON

func (client *Client) GetJSON(
	url string,
	params url.Values,
	result interface{},
	options ...interface{},
) (json.RawMessage, int, error)

GetJSON performs GET request to the smartling API and tries to decode answer as JSON.

func (*Client) GetProjectDetails

func (client *Client) GetProjectDetails(
	projectID string,
) (*ProjectDetails, error)

GetProjectDetails returns project details for specified project.

func (*Client) Import

func (client *Client) Import(
	projectID string,
	localeID string,
	request ImportRequest,
) (*FileImportResult, error)

Import imports specified file as translation.

func (*Client) LastModified

func (client *Client) LastModified(
	projectID string,
	request FileLastModifiedRequest,
) (*FileLastModifiedLocales, error)

func (*Client) ListAllFiles

func (client *Client) ListAllFiles(
	projectID string,
	request FilesListRequest,
) ([]File, error)

ListAllFiles returns all files by request, even if it requires several API calls.

func (*Client) ListFileTypes

func (client *Client) ListFileTypes(
	projectID string,
) ([]FileType, error)

ListFileTypes returns returns file types list from specified project.

func (*Client) ListFiles

func (client *Client) ListFiles(
	projectID string,
	request FilesListRequest,
) (*FilesList, error)

ListFiles returns files list from specified project by specified request. Returned result is paginated, so check out TotalCount struct field in the reply. API can return only 500 files at once.

func (*Client) ListProjects

func (client *Client) ListProjects(
	accountID string,
	request ProjectsListRequest,
) (*ProjectsList, error)

ListProjects returns projects in specified account matching specified request.

func (*Client) Post

func (client *Client) Post(
	url string,
	payload []byte,
	result interface{},
	options ...interface{},
) (json.RawMessage, int, error)

Post performs POST request to the Smartling API. You probably do not want to use it.

func (*Client) RenameFile

func (client *Client) RenameFile(
	projectID string,
	oldURI string,
	newURI string,
) error

RenameFile renames file to new URI.

func (*Client) SetDebugLogger

func (client *Client) SetDebugLogger(logger LogFunction) *Client

SetDebugLogger sets logger function which will be called for logging internal information like HTTP requests and their responses.

func (*Client) SetInfoLogger

func (client *Client) SetInfoLogger(logger LogFunction) *Client

SetInfoLogger sets logger function which will be called for logging informational messages like progress of file download and so on.

func (*Client) UploadFile

func (client *Client) UploadFile(
	projectID string,
	request FileUploadRequest,
) (*FileUploadResult, error)

DownloadFile downloads original file from project.

type ClientInterface

type ClientInterface interface {
	Authenticate() error
	DeleteFile(projectID string, uri string) error
	DownloadFile(projectID string, uri string) (io.Reader, error)
	DownloadTranslation(projectID string, localeID string, request FileDownloadRequest) (io.Reader, error)
	GetFileStatus(projectID string, fileURI string) (*FileStatus, error)
	Get(url string, params url.Values, options ...interface{}) (io.ReadCloser, int, error)
	GetJSON(url string, params url.Values, result interface{}, options ...interface{}) (json.RawMessage, int, error)
	GetProjectDetails(projectID string) (*ProjectDetails, error)
	Import(projectID string, localeID string, request ImportRequest) (*FileImportResult, error)
	LastModified(projectID string, request FileLastModifiedRequest) (*FileLastModifiedLocales, error)
	ListAllFiles(projectID string, request FilesListRequest) ([]File, error)
	ListFiles(projectID string, request FilesListRequest) (*FilesList, error)
	ListFileTypes(projectID string) ([]FileType, error)
	ListProjects(accountID string, request ProjectsListRequest) (*ProjectsList, error)
	Post(url string, payload []byte, result interface{}, options ...interface{}) (json.RawMessage, int, error)
	RenameFile(projectID string, oldURI string, newURI string) error
	UploadFile(projectID string, request FileUploadRequest) (*FileUploadResult, error)
}

type ContentTypeOption

type ContentTypeOption string

ContentTypeOption specifies content type for making request to API.

type Credentials

type Credentials struct {
	// UserID is a unique user ID for accessing Smartling API.
	UserID string

	// Secret is a secret token for accessing Smartling API.
	Secret string

	// AccessToken is a access token, which is obtained by UserID/Secret pair.
	AccessToken *Token

	// RefreshToken is a token for refreshing access token. It has longer
	// lifespan.
	RefreshToken *Token
}

Credentials represents represents user credentials used to authenticate user in the Smartling API.

type File

type File struct {
	// FileURI is a unique path to file in Smartling system.
	FileURI string

	// FileType is a file type identifier.
	FileType FileType

	// LastUploaded refers to time when file was uploaded.
	LastUploaded UTC

	// HasInstructions specifies does files have instructions or not.
	HasInstructions bool
}

FileStatus represents current file status in the Smartling system.

type FileDownloadRequest

type FileDownloadRequest struct {
	FileURIRequest

	Type            RetrievalType
	IncludeOriginal bool
}

FileDownloadRequest represents optional parameters for file download operation.

func (FileDownloadRequest) GetQuery

func (request FileDownloadRequest) GetQuery() url.Values

GetQuery returns URL values representation of download file query params.

type FileImportResult

type FileImportResult struct {
	WordCount               int
	StringCount             int
	TranslationImportErrors []string
}

type FileLastModified

type FileLastModified struct {
	LocaleID     string
	LastModified UTC
}

type FileLastModifiedLocales

type FileLastModifiedLocales struct {
	Items []FileLastModified
}

type FileLastModifiedRequest

type FileLastModifiedRequest struct {
	FileURIRequest

	LastModifiedAfter UTC
}

func (*FileLastModifiedRequest) GetForm

func (request *FileLastModifiedRequest) GetForm() (*Form, error)

type FileStatus

type FileStatus struct {
	File

	TotalStringCount int
	TotalWordCount   int
	TotalCount       int

	Items []FileStatusTranslation
}

FileStatus describes file translation status obtained by GetFileStatus method.

func (FileStatus) AwaitingAuthorizationStringCount

func (fs FileStatus) AwaitingAuthorizationStringCount() int

func (FileStatus) GetFileStatusTranslation

func (fs FileStatus) GetFileStatusTranslation(locale string) (*FileStatusTranslation, error)

type FileStatusTranslation

type FileStatusTranslation struct {
	LocaleID string

	AuthorizedStringCount int
	AuthorizedWordCount   int
	CompletedStringCount  int
	CompletedWordCount    int
	ExcludedStringCount   int
	ExcludedWordCount     int
}

func (FileStatusTranslation) AwaitingAuthorizationStringCount

func (fst FileStatusTranslation) AwaitingAuthorizationStringCount(totalStringCount int) int

type FileType

type FileType string

FileType represents file type format used in Smartling API.

func GetFileTypeByExtension

func GetFileTypeByExtension(ext string) FileType

type FileURIRequest

type FileURIRequest struct {
	FileURI string
}

FileURIRequest represents fileUri query parameter, commonly used in API.

func (*FileURIRequest) GetForm

func (request *FileURIRequest) GetForm() (*Form, error)

func (FileURIRequest) GetQuery

func (request FileURIRequest) GetQuery() url.Values

GetQuery returns URL value representation for file URI.

type FileUploadRequest

type FileUploadRequest struct {
	FileURIRequest

	File      []byte
	FileType  FileType
	Authorize bool

	LocalesToAuthorize []string

	CallbackURL string

	Smartling struct {
		Namespace   string
		FileCharset string
		Directives  map[string]string
	}
}

func (*FileUploadRequest) GetForm

func (request *FileUploadRequest) GetForm() (*Form, error)

type FileUploadResult

type FileUploadResult struct {
	Overwritten bool
	StringCount int
	WordCount   int
}

type FilesList

type FilesList struct {
	// TotalCount is a total files count.
	TotalCount int

	// Items contains all files matched by request.
	Items []File
}

FilesList represents file list reply from Smartling APIa.

type FilesListRequest

type FilesListRequest struct {
	// Cursor is a limit/offset pair, used to paginate reply.
	Cursor LimitOffsetRequest

	// URIMask instructs API to return only files with a URI containing the
	// given substring. Case is ignored.
	URIMask string

	// FileTypes instructs API to return only specified file types.
	FileTypes []FileType

	// LastUploadedAfter instructs API to return files uploaded after specified
	// date.
	LastUploadedAfter UTC

	// LastUploadedBefore instructs API to return files uploaded after
	// specified date.
	LastUploadedBefore UTC
}

FilesListRequest represents request used to filter files returned by list files API call.

func (*FilesListRequest) GetQuery

func (request *FilesListRequest) GetQuery() url.Values

GetQuery returns URL values representation of files list request.

type Form

type Form struct {
	Writer *multipart.Writer
	Body   *bytes.Buffer
}

func (*Form) Bytes

func (form *Form) Bytes() []byte

func (*Form) Close

func (form *Form) Close() error

func (*Form) GetContentType

func (form *Form) GetContentType() string

type ImportRequest

type ImportRequest struct {
	FileURIRequest

	File             []byte
	FileType         FileType
	TranslationState TranslationState
	Overwrite        bool
}

func (*ImportRequest) GetForm

func (request *ImportRequest) GetForm() (*Form, error)

type JSONError

type JSONError struct {
	Cause    error
	Response []byte
}

func (JSONError) Error

func (err JSONError) Error() string

type LimitOffsetRequest

type LimitOffsetRequest struct {
	Offset int
	Limit  int
}

LimitOffsetRequest is a base request for all other requests to set pagination options, e.g. limit and offset.

func (LimitOffsetRequest) GetQuery

func (request LimitOffsetRequest) GetQuery() url.Values

GetQuery returns URL-encoded representation of current request.

type Locale

type Locale struct {
	// LocaleID is a unique locale ID.
	LocaleID string

	// Description describes locale.
	Description string

	// Enabled is a flag that represents is locale enabled or not.
	Enabled bool
}

Locale represents locale for translation.

type LogFunction

type LogFunction func(format string, args ...interface{})

LogFunction represents abstract logger function interface which can be used for setting up logging of library actions.

type NotAuthorizedError

type NotAuthorizedError struct{}

func (NotAuthorizedError) Error

func (err NotAuthorizedError) Error() string

type NotFoundError

type NotFoundError struct{}

func (NotFoundError) Error

func (err NotFoundError) Error() string

type Project

type Project struct {
	// ProjectID is a unique project ID.
	ProjectID string

	// ProjectName is a human-friendly project name.
	ProjectName string

	// AccountUID is undocumented by Smartling API.
	AccountUID string

	// SourceLocaleID represents source locale ID for project.
	SourceLocaleID string

	// SourceLocaleDescription describes project's locale.
	SourceLocaleDescription string

	// Archived will be true if project is archived.
	Archived bool
}

Project represents detailed project information.

type ProjectDetails

type ProjectDetails struct {
	Project

	// TargetLocales represents target locales list.
	TargetLocales []Locale
}

ProjectDetails extends Project type to contain target locales list.

type ProjectsList

type ProjectsList struct {
	// TotalCount represents total count of projects.
	TotalCount int64

	// Items contains projects list by specified request.
	Items []Project
}

ProjectsList represents projects list under specified account.

type ProjectsListRequest

type ProjectsListRequest struct {
	// Cursor specifies limit/offset pagination pair.
	Cursor LimitOffsetRequest

	// ProjectNameFilter specifies filter for project name.
	ProjectNameFilter string

	// IncludeArchived specifies should archived items be included or not.
	IncludeArchived bool
}

ProjectsListRequest is a request used in GetProjectsList method.

func (ProjectsListRequest) GetQuery

func (request ProjectsListRequest) GetQuery() url.Values

GetQuery returns URL-encoded representation of current request.

type RenameFileRequest

type RenameFileRequest struct {
	FileURIRequest

	NewFileURI string
}

RenameFileRequest represents fileUri query parameter, commonly used in API.

func (*RenameFileRequest) GetForm

func (request *RenameFileRequest) GetForm() (*Form, error)

type RetrievalType

type RetrievalType string

RetrievalType describes type of file download. https://help.smartling.com/v1.0/reference#get_projects-projectid-locales-localeid-file

type Token

type Token struct {
	// Value is a string representation of token.
	Value string

	// ExpirationTime is a expiration time for token when it becomes invalid.
	ExpirationTime time.Time
}

Token represents authentication token, either access or refresh.

func (*Token) IsSafe

func (token *Token) IsSafe() bool

IsSafe returns true if token still can be used and it's expiration time is in safe bounds.

func (*Token) IsValid

func (token *Token) IsValid() bool

IsValid returns true if token still can be used.

func (*Token) String

func (token *Token) String() string

String returns token representation for logging purposes only.

type TranslationState

type TranslationState string
const (
	TranslationStatePublished       TranslationState = "PUBLISHED"
	TranslationStatePostTranslation                  = "POST_TRANSLATION"
)

type UTC

type UTC struct {
	time.Time
}

UTC represents time in UTC format (zero timezone).

func (UTC) MarshalJSON

func (utc UTC) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON representation of UTC.

func (UTC) String

func (utc UTC) String() string

String returns string reprenation of UTC.

func (*UTC) UnmarshalJSON

func (utc *UTC) UnmarshalJSON(data []byte) error

UnmarshalJSON parses JSON representation of UTC.

type ValidationError

type ValidationError struct {
	Errors []struct {
		Key     string
		Message string
	}
}

func (ValidationError) Error

func (err ValidationError) Error() string

Jump to

Keyboard shortcuts

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