telphin

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2022 License: GPL-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Host points to the API
	Host = "https://altapi.telphin.ru"
	// Host points to the storage
	HostStorage = "https://storage.telphin.ru"
	// Websocket host
	WsHost = "sipproxy.telphin.ru"

	// RequestNewTokenBeforeExpiresIn is used by SendWithAuth and try to get new Token when it's about to expire
	RequestNewTokenBeforeExpiresIn = time.Duration(60) * time.Second
)
View Source
const (
	HangupDispositionCalleeBye      = "callee_bye"      // трубку положила принимающая сторона
	HangupDispositionCallerBye      = "caller_bye"      // трубку положила вызывающая сторона
	HangupDispositionCallerCancel   = "caller_cancel"   // вызывающая сторона отказалась ждать ответа
	HangupDispositionCalleeRefuse   = "callee_refuse"   // принимающая сторона отказалась отвечать (была занята, отсутствовала регистрация и т.п.)
	HangupDispositionInternalCancel = "internal_cancel" // вызов завершен сервером (обычно таймаут вызова или при пачке вызовов кто-то снял трубку)
)
View Source
const (
	CallResultBusy        = "busy"
	CallResultAnswered    = "answered"
	CallResultNotAnswered = "not answered"
	CallResultFailed      = "failed"
	CallResultRejected    = "rejected"
	CallResultBridged     = "bridged"

	CallCdrResultBusy              = "busy"
	CallCdrResultAnswered          = "answered"
	CallCdrResultNotAnswered       = "not answered"
	CallCdrResultAnsweredElsewhere = "answered elsewhere"
	CallCdrResultFailed            = "failed"
	CallCdrResultRejected          = "rejected"
	CallCdrResultVoicemail         = "voicemail"
)
View Source
const (
	EventStatusCalling     = "CALLING"     // поступил вызов
	EventStatusAnswer      = "ANSWER"      // вызов был отвечен
	EventStatusBusy        = "BUSY"        // вызов получил сигнал "занято"
	EventStatusNoAnswer    = "NOANSWER"    // звонок не отвечен (истек таймер ожидания на сервере)
	EventStatusCancel      = "CANCEL"      // звонящий отменил вызов до истечения таймера ожидания на сервере
	EventStatusCongestion  = "CONGESTION"  // произошла ошибка во время вызова
	EventStatusChanunavail = "CHANUNAVAIL" // у вызываемого абонента отсутствует регистрация
)
View Source
const (
	EventTypeDialIn  = "dial-in"
	EventTypeDialOut = "dial-out"
	EventTypeAnswer  = "answer"
	EventTypeHangup  = "hangup"
)
View Source
const (
	FlowIn       = "in"
	FlowOut      = "out"
	FlowTransfer = "transfer"
)
View Source
const (
	ExtensionTypePhone = "phone"
	ExtensionTypeIVR   = "ivr"
	ExtensionTypeQueue = "queue"
)
View Source
const (
	OrderDesc = "desc"
	OrderAsc  = "asc"
)

Variables

View Source
var TelphinStorageHostRegexp = regexp.MustCompile(`^` + HostStorage)

Functions

This section is empty.

Types

type Ani

type Ani struct {
	Default string `json:"default"` // Установленный ani, если не установлен - None
}

See: https://ringme-confluence.atlassian.net/wiki/spaces/RAL/pages/832602113/ani

type CallHistories

type CallHistories struct {
	Page        uint32        `json:"page"`
	PerPage     uint32        `json:"per_page"`
	Order       string        `json:"order"`
	CallHistory []CallHistory `json:"call_history"`
}

type CallHistory

type CallHistory struct {
	UUID              string    `json:"call_uuid"`
	Flow              string    `json:"flow"`
	InitTime          *JSONTime `json:"init_time_gmt"`
	StartTime         *JSONTime `json:"start_time_gmt"`
	BridgedTime       *JSONTime `json:"bridged_time_gmt"`
	HangupTime        *JSONTime `json:"hangup_time_gmt"`
	Duration          uint32    `json:"duration"`
	Bridged           bool      `json:"bridged"`
	BridgedDuration   uint32    `json:"bridged_duration"`
	ExtensionID       uint32    `json:"extension_id"`
	From              string    `json:"from_username"`
	To                string    `json:"to_username"`
	Result            string    `json:"result"`
	HangupCause       string    `json:"hangup_cause"`
	HangupDisposition *string   `json:"hangup_disposition,omitempty"`
	Cdr               *[]Cdr    `json:"cdr"`
}

func (*CallHistory) HasAnsweredExtensionPhoneTypeCdr

func (c *CallHistory) HasAnsweredExtensionPhoneTypeCdr() bool

func (*CallHistory) HasExtensionPhoneTypeCdr

func (c *CallHistory) HasExtensionPhoneTypeCdr() bool

func (*CallHistory) HasExtensionPhoneTypeWithRecords

func (c *CallHistory) HasExtensionPhoneTypeWithRecords() bool

func (*CallHistory) HasTransferredCdr

func (c *CallHistory) HasTransferredCdr() bool

type CallHistoryRequest

type CallHistoryRequest struct {
	StartDatetime *string `url:"start_datetime"`
	EndDatetime   *string `url:"end_datetime"`
	Flow          *string `url:"flow"`
	ExtensionID   *uint32 `url:"extension_id"`
	ToUsername    *string `url:"to_username"`
	PerPage       uint16  `url:"per_page"`
}

type Callback

type Callback struct {
	CallApiID string `json:"call_api_id"`
	CallID    string `json:"call_id"`
}

type CallbackRequest

type CallbackRequest struct {
	SrcNum                 []string `json:"src_num"`
	DstNum                 string   `json:"dst_num"`
	AllowPublicTransfer    bool     `json:"allow_public_transfer"`
	CallDuration           *int     `json:"call_duration"`
	AnnounceSoundID        *int     `json:"announce_sound_id"`
	DstAnnounceSoundID     *int     `json:"dst_announce_sound_id"`
	CallerIDName           *string  `json:"caller_id_name"`
	CallerIDNumber         *string  `json:"caller_id_number"`
	DstAni                 *string  `json:"dst_ani"`
	DstDtmf                *string  `json:"dst_dtmf"`
	SrcCallerIDName        *string  `json:"src_caller_id_name"`
	SrcCallerIDNumber      *string  `json:"src_caller_id_number"`
	TransferAfterDstHangup *string  `json:"transfer_after_dst_hangup"`
	TransferAfterSrcHangup *string  `json:"transfer_after_src_hangup"`
	WaitForPickup          *int     `json:"wait_for_pickup"`
}

type Cdr

type Cdr struct {
	ExtensionType     string    `json:"extension_type"`
	RecordUUID        *string   `json:"record_uuid"`
	Result            string    `json:"result"`
	HangupCause       string    `json:"hangup_cause"`
	HangupDisposition *string   `json:"hangup_disposition,omitempty"`
	Duration          int       `json:"duration"`
	InitTime          *JSONTime `json:"init_time_gmt"`
	StartTime         *JSONTime `json:"start_time_gmt"`
	HangupTime        *JSONTime `json:"hangup_time_gmt"`
	Flow              string    `json:"flow"`
	ExtensionID       uint32    `json:"extension_id"`
	From              string    `json:"from_username"`
	To                string    `json:"to_username"`
}

type Client

type Client struct {
	sync.Mutex
	Client   *http.Client
	ClientID string
	Secret   string
	Host     string
	Token    *TokenResponse

	Logger FieldLogger
	// contains filtered or unexported fields
}

func NewClient

func NewClient(clientID string, secret string, host string) (*Client, error)

NewClient returns new client struct

func (*Client) CreateCallback

func (c *Client) CreateCallback(extensionID uint32, callback CallbackRequest) (*Callback, error)

Endpoint: POST /api/ver1.0/extension/{extension_id}/callback/

func (*Client) CreateEvent

func (c *Client) CreateEvent(extensionId uint32, event CreateEventRequest) (*Event, error)

Endpoint: POST /extension/{extension_id}/event/

func (*Client) CreateExtension

func (c *Client) CreateExtension(clientID string, extensionCreateRequest ExtensionCreateRequest) (*Extension, error)

Endpoint: POST /client/{client_id}/extension

func (*Client) DeleteEvent

func (c *Client) DeleteEvent(extensionId uint32, eventId int) error

Endpoint: GET /extension/{extension_id}/event/{id}

func (*Client) DeleteExtension

func (c *Client) DeleteExtension(clientID string, extensionID uint32) error

Endpoint: DELETE /client/{client_id}/extension/{extension_id}

func (*Client) DeleteRecord added in v0.1.4

func (c *Client) DeleteRecord(clientID string, recordUUID string) error

Endpoint: DELETE /client/{client_id}/record/{record_uuid}

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() (*TokenResponse, error)

GetAccessToken returns struct of TokenResponse No need to call SetAccessToken to apply new access token for current Client Endpoint: POST /oauth/token

func (*Client) GetAllDID

func (c *Client) GetAllDID(clientID string) (*[]Did, error)

func (*Client) GetCallHistories

func (c *Client) GetCallHistories(clientID string, callHistoryRequest CallHistoryRequest) (*CallHistories, error)

Endpoint: GET /client/{client_id}/call_history/

func (*Client) GetCallHistory

func (c *Client) GetCallHistory(clientID string, callId string) (*CallHistory, error)

Endpoint: GET /client/{client_id}/call_history/{callId}

func (*Client) GetEvents

func (c *Client) GetEvents(extensionId uint32) (*[]Event, error)

Endpoint: GET /extension/{extension_id}/event/

func (*Client) GetExtension

func (c *Client) GetExtension(clientID string, extensionID uint16) (*Extension, error)

Endpoint: GET /client/{client_id}/extension/{extension_id}

func (*Client) GetExtensionAni

func (c *Client) GetExtensionAni(extensionID uint16) (*Ani, error)

Endpoint: GET /extension/{extension_id}/ani/

func (*Client) GetExtensions

func (c *Client) GetExtensions(clientID string, typeExtensions *string, page *int) (*[]Extension, error)

Endpoint: GET /client/{client_id}/extension/

func (*Client) GetQualityRate added in v0.0.4

func (c *Client) GetQualityRate(clientID string, request QualityRateRequest) (*[]QualityRate, error)

GET /api/ver1.0/client/{client_id}/quality_rate/

func (*Client) GetRecord

func (c *Client) GetRecord(clientID string, recordUUID string) (*mem.File, error)

Endpoint: GET /client/{client_id}/record/{record_uuid}

func (*Client) GetRecordStorageUrl

func (c *Client) GetRecordStorageUrl(clientID string, recordUUID string) (*RecordStorageUrl, error)

Endpoint: GET /client/{client_id}/record/{record_uuid}/storage_url/

func (*Client) GetRecords added in v0.1.4

func (c *Client) GetRecords(clientID string, recordsRequest RecordsRequest) (*[]RecordInfo, error)

Endpoint: GET /client/{client_id}/record/

func (*Client) GetSounds added in v0.1.6

func (c *Client) GetSounds(clientID string, request SoundsRequest) (*[]Sound, error)

Endpoint: GET /client/{client_id}/sound/

func (*Client) GetWsSipUri

func (c *Client) GetWsSipUri(user string) string

func (*Client) NewRequest

func (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error)

NewRequest constructs a request Convert payload to a JSON

func (*Client) ResetAccessToken

func (c *Client) ResetAccessToken() error

TODO

func (*Client) Send

func (c *Client) Send(req *http.Request, v interface{}) error

Send makes a request to the API, the response body will be unmarshaled into v, or if v is an io.Writer, the response will be written to it without decoding

func (*Client) SendWithAuth

func (c *Client) SendWithAuth(req *http.Request, v interface{}) error

SendWithAuth makes a request to the API and apply OAuth2 header automatically.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(token string, expiresIn expirationTime)

SetAccessToken sets saved token to current client

func (*Client) SetExtensionAni

func (c *Client) SetExtensionAni(extensionID uint32, aniNumber string) (*Ani, error)

Endpoint: PUT /extension/{extension_id}/ani/

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client *http.Client)

SetHTTPClient sets *http.Client to current client

func (*Client) SetLogger

func (c *Client) SetLogger(logger FieldLogger)

TODO

func (*Client) UpdatePhone

func (c *Client) UpdatePhone(extensionID uint32, phoneProps PhoneProperties) error

Endpoint: PUT /extension/{extension_id}/phone

func (*Client) WsHost

func (c *Client) WsHost() string

func (*Client) WsServers

func (c *Client) WsServers() []string

WsServers is WebSocket URIs to connect to.

type CreateEventRequest

type CreateEventRequest struct {
	URL       string `json:"url"`
	Method    string `json:"method"`
	EventType string `json:"event_type"`
}

type Did

type Did struct {
	ID          uint32 `json:"id"`           // Идентификатор внешнего номера
	Name        string `json:"name"`         // Имя внешнего номера, то есть сам номер
	Domain      string `json:"domain"`       // Домен внешнего номера
	ClientID    uint32 `json:"client_id"`    // Идентификатор клиента, которому назначен внешний номер
	ExtensionID uint32 `json:"extension_id"` // Идентификатор добавочного, которому назначен внешний номер
}

See: https://ringme-confluence.atlassian.net/wiki/spaces/RAL/pages/20414492/did

type ErrorResponse

type ErrorResponse struct {
	Code    int
	Cause   string `json:"message"`
	Details string
}

ErrorResponse a typed error returned by http Handlers and used for choosing error handlers

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

type Event

type Event struct {
	ID        int    `json:"id"`
	URL       string `json:"url"`
	Method    string `json:"method"`
	EventType string `json:"event_type"`
}

type Extension

type Extension struct {
	ID     uint32 `json:"id"`     // Уникальный идентификатор добавочного
	Status string `json:"status"` // Статус добавочного: 'active' - активен, 'blocked' - заблокирован
	Name   string `json:"name"`   // префикс_клиента*имя_добавочного или просто имя_добавочного(в этом случчае префикс будет дописан автоматически)
	Type   string `json:"type"`   // Тип добавочного: 'phone', 'queue', 'ivr', 'fax'
	Label  string `json:"label"`  // Display Name добавочного. Отображается на вызываемом терминале при исходящих вызовах (если поддерживается)
}

See: https://ringme-confluence.atlassian.net/wiki/spaces/RAL/pages/17367181/extension

func (Extension) Number

func (e Extension) Number() (*int, error)

type ExtensionCreateRequest

type ExtensionCreateRequest struct {
	Status string `json:"status"`          // Статус добавочного: 'active' - активен, 'blocked' - заблокирован
	Name   string `json:"name"`            // префикс_клиента*имя_добавочного или просто имя_добавочного(в этом случчае префикс будет дописан автоматически)
	Type   string `json:"type"`            // Тип добавочного: 'phone', 'queue', 'ivr', 'fax'
	Label  string `json:"label,omitempty"` // Display Name добавочного. Отображается на вызываемом терминале при исходящих вызовах (если поддерживается)
}

type FieldLogger

type FieldLogger interface {
	Logger
	WithField(string, interface{}) FieldLogger
	WithFields(map[string]interface{}) FieldLogger
}

FieldLogger interface

type JSONTime

type JSONTime time.Time

func (JSONTime) Format

func (j JSONTime) Format(s string) string

func (JSONTime) MarshalJSON

func (j JSONTime) MarshalJSON() ([]byte, error)

func (*JSONTime) UnmarshalJSON

func (j *JSONTime) UnmarshalJSON(b []byte) error

imeplement Marshaler und Unmarshalere interface

type Logger

type Logger interface {
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Error(args ...interface{})
}

Logger interface TODO: remove logrus

type LogrusLogger

type LogrusLogger struct {
	logrus.FieldLogger
}

func WrapLogrus

func WrapLogrus(logger logrus.FieldLogger) *LogrusLogger

func (LogrusLogger) WithField

func (l LogrusLogger) WithField(s string, i interface{}) FieldLogger

WithField returns a new Logger with the field added

func (LogrusLogger) WithFields

func (l LogrusLogger) WithFields(m map[string]interface{}) FieldLogger

WithFields returns a new Logger with the fields added

type PhoneProperties

type PhoneProperties struct {
	Password       string `json:"password"`        // Задает пароль для авторизации на sip-сервере
	AllowWebrtc    bool   `json:"allow_webrtc"`    // Если установлено значение "true", то позволяет добавочному работать через WebRTC
	RecordEnabled  bool   `json:"record_enabled"`  // Включить запись разговоров
	RecordTransfer bool   `json:"record_transfer"` // Включить запись в том числе и переадресованных вызовов
}

type QualityRate added in v0.0.4

type QualityRate struct {
	CallUUID    string   `json:"call_uuid"`
	Datetime    JSONTime `json:"datetime"`
	ExtensionID uint32   `json:"extension_id"`
	ClientID    uint32   `json:"client_id"`
	ID          uint32   `json:"id"`
	MaxRate     uint16   `json:"max_rate"`
	Rate        uint16   `json:"rate"`
}

type QualityRateRequest added in v0.0.4

type QualityRateRequest struct {
	StartDatetime *time.Time `url:"start_datetime"`
	EndDatetime   *time.Time `url:"end_datetime"`
	ExtensionID   *uint32    `url:"extension_id"`
}

type RecordInfo added in v0.1.4

type RecordInfo struct {
	CallUUID   string `json:"call_uuid"`
	RecordUUID string `json:"record_uuid"`
}

type RecordStorageUrl

type RecordStorageUrl struct {
	RecordUrl string `json:"record_url"`
}

type RecordsRequest added in v0.1.4

type RecordsRequest struct {
	StartDatetime string  `url:"start_datetime"`
	EndDatetime   string  `url:"end_datetime"`
	PerPage       uint32  `url:"per_page"`
	Page          uint32  `url:"page"`
	Order         *string `url:"order"`
}

type Sound added in v0.1.6

type Sound struct {
	DealerID uint32 `json:"dealer_id"`
	ID       uint32 `json:"id"`
	ClientID uint32 `json:"client_id"`
	Title    string `json:"title"`
	Filename string `json:"filename"`
}

type SoundsRequest added in v0.1.6

type SoundsRequest struct {
	Id      []uint32 `url:"id"`
	OwnOnly *bool    `url:"own_only"`
	Title   []string `url:"title"`
}

type TokenResponse

type TokenResponse struct {
	// RefreshToken string         `json:"refresh_token"`
	Token     string         `json:"access_token"`
	Type      string         `json:"token_type"`
	ExpiresIn expirationTime `json:"expires_in"`
}

TokenResponse is for API response for the /oauth2/token endpoint

Jump to

Keyboard shortcuts

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