Skip to content

Commit

Permalink
♻️ refactor: refactor codebase #14
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Jan 13, 2024
1 parent 13b8099 commit 12ea69a
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 65 deletions.
14 changes: 14 additions & 0 deletions example/ami_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,17 @@ func TestAmiClient(t *testing.T) {
}
ami.D().Info("Authenticated successfully")
}

func TestAllEventConsume(t *testing.T) {
c, err := createConn()
if err != nil {
ami.D().Error(err.Error())
return
}
event := ami.NewEventListener()
event.OpenFullEventsAsyncFunc(c)
}

func TestDialOut(t *testing.T) {
// adding logic here
}
49 changes: 24 additions & 25 deletions pkg/ami/ami_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package ami

import (
"fmt"
"log"
"strings"

"github.com/pnguyen215/voipkit/pkg/ami/config"
Expand All @@ -15,13 +14,13 @@ func NewAction() *AMIAction {

func NewRevokeAction(cmd string, timeout int) *AMIAction {
cli := NewAction()
cli.ActionCmd = cmd
cli.Name = cmd
cli.Timeout = timeout
return cli
}

func (a *AMIAction) SetActionCmd(action string) *AMIAction {
a.ActionCmd = action
func (a *AMIAction) SetName(action string) *AMIAction {
a.Name = action
return a
}

Expand All @@ -32,14 +31,14 @@ func (a *AMIAction) SetTimeout(timeout int) *AMIAction {
return a
}

// RevokeAction run cli on asterisk server
func (c *AMIAction) RevokeAction(a *AMI, d *AMIDictionary, e *AMIMessage, deadlock bool) (*AMIResponse, error) {
log.Printf(" [>] Ami revoke action (state mutex opened lock~unlock) >>> \n '%v' \n", e.String())
// Revoke run cli on asterisk server
func (c *AMIAction) Revoke(a *AMI, d *AMIDictionary, e *AMIMessage, deadlock bool) (*AMIResponse, error) {
D().Info("[>] Ami revoke action (state mutex opened lock~unlock) >>> '%v'", e.String())
var response AMIResponse
var _err error

if strings.EqualFold(c.ActionCmd, "") {
response.ErrorMessage = fmt.Sprintf(config.AmiErrorFieldRequired, "action_cmd")
if strings.EqualFold(c.Name, "") {
response.ErrorMessage = fmt.Sprintf(config.AmiErrorFieldRequired, "name")
response.IsSuccess = false
_err = fmt.Errorf(response.ErrorMessage)
return &response, _err
Expand Down Expand Up @@ -81,34 +80,34 @@ on_failed:
return &response, _err
}

// RunAction for run cli asterisk server
func (c *AMIAction) RunAction(a *AMI) (*AMIResponse, error) {
// Run for run cli asterisk server
func (c *AMIAction) Run(a *AMI) (*AMIResponse, error) {
action := NewActionWith(config.AmiActionCommand)
action.AddField(config.AmiActionCommand, c.ActionCmd)
return c.RevokeAction(a, NewDictionary(), action, false)
action.AddField(config.AmiActionCommand, c.Name)
return c.Revoke(a, NewDictionary(), action, false)
}

// RunActionDict
func (c *AMIAction) RunActionDict(a *AMI, dictionaries map[string]string) (*AMIResponse, error) {
// RunDictionary
func (c *AMIAction) RunDictionary(a *AMI, dictionaries map[string]string) (*AMIResponse, error) {
action := NewActionWith(config.AmiActionCommand)
action.AddField(config.AmiActionCommand, c.ActionCmd)
action.AddField(config.AmiActionCommand, c.Name)
d := NewDictionary()
d.AddKeysTranslator(dictionaries)
return c.RevokeAction(a, d, action, false)
return c.Revoke(a, d, action, false)
}

// RunActionScript with script action
func (c *AMIAction) RunActionScript(a *AMI, script map[string]string) (*AMIResponse, error) {
action := NewActionWith(c.ActionCmd)
// RunScript with script action
func (c *AMIAction) RunScript(a *AMI, script map[string]string) (*AMIResponse, error) {
action := NewActionWith(c.Name)
action.AddFields(script)
return c.RevokeAction(a, NewDictionary(), action, false)
return c.Revoke(a, NewDictionary(), action, false)
}

// RunActionScriptDict with script action
func (c *AMIAction) RunActionScriptDict(a *AMI, script, dictionaries map[string]string) (*AMIResponse, error) {
action := NewActionWith(c.ActionCmd)
// WithRun with script action
func (c *AMIAction) WithRun(a *AMI, script, dictionaries map[string]string) (*AMIResponse, error) {
action := NewActionWith(c.Name)
action.AddFields(script)
d := NewDictionary()
d.AddKeysTranslator(dictionaries)
return c.RevokeAction(a, d, action, false)
return c.Revoke(a, d, action, false)
}
4 changes: 2 additions & 2 deletions pkg/ami/ami_cdr.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,8 @@ func ParseCdr(e *AMIMessage, d *AMIDictionary) *AMICdr {
if d == nil {
d = NewDictionary()
}
if !d.AllowForceTranslate {
d.SetAllowForceTranslate(true)
if !d.EnabledForceTranslate {
d.SetEnabledForceTranslate(true)
}
r := NewAMICdr().
SetAccountCode(e.FieldDictionaryOrRefer(d, config.AmiJsonFieldAccountCode, "AccountCode")).
Expand Down
4 changes: 2 additions & 2 deletions pkg/ami/ami_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func (a *AMICommand) Read(ctx context.Context, socket AMISocket) (AmiReply, erro
if socket.MaxConcurrencyMillis > 0 {
if concurrency >= socket.MaxConcurrencyMillis {
if socket.DebugMode {
log.Printf("Read(). max over concurrency = %v (millis), the concurrency allowed = %v (millis)",
D().Warn("Read(). max over concurrency: %v (ms) and the concurrency allowed: %v (ms)",
concurrency, socket.MaxConcurrencyMillis)
}
break
Expand Down Expand Up @@ -177,7 +177,7 @@ func (a *AMICommand) ReadLevel(ctx context.Context, socket AMISocket) (AmiReplie
if socket.MaxConcurrencyMillis > 0 {
if concurrency >= socket.MaxConcurrencyMillis {
if socket.DebugMode {
log.Printf("ReadLevel(). max over concurrency = %v (millis), the concurrency allowed = %v (millis)",
D().Warn("ReadLevel(). max over concurrency: %v (ms) and the concurrency allowed: %v (ms)",
concurrency, socket.MaxConcurrencyMillis)
}
break
Expand Down
17 changes: 6 additions & 11 deletions pkg/ami/ami_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,37 +47,32 @@ func (c *AMICore) ResetUUID() *AMICore {
return c
}

// NewAmiCore
// WithCore
// Creating new instance asterisk server connection
// Firstly, create new instance AMISocket
// Secondly, create new request body to login
func NewAmiCore(ctx context.Context, socket *AMISocket, auth *AMIAuth) (*AMICore, error) {
func WithCore(ctx context.Context, socket *AMISocket, auth *AMIAuth) (*AMICore, error) {
uuid, err := GenUUID()

if err != nil {
return nil, err
}

socket.SetUUID(uuid)
err = Login(ctx, *socket, auth)

err = WithAuthenticate(ctx, *socket, auth)
if err != nil {
return nil, err
}

core := NewCore()
core.SetSocket(socket)
core.SetUUID(uuid)
core.SetDictionary(socket.Dictionary)

core.Wg.Add(1)
go core.Run(ctx)
go core.run(ctx)
return core, nil
}

// Run
// run
// Go-func to consume event from asterisk server response
func (c *AMICore) Run(ctx context.Context) {
func (c *AMICore) run(ctx context.Context) {
defer c.Wg.Done()
for {
select {
Expand Down
8 changes: 4 additions & 4 deletions pkg/ami/ami_dictionary.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ func NewDictionary() *AMIDictionary {
return d
}

func (d *AMIDictionary) SetAllowForceTranslate(allow bool) *AMIDictionary {
d.AllowForceTranslate = allow
func (d *AMIDictionary) SetEnabledForceTranslate(allow bool) *AMIDictionary {
d.EnabledForceTranslate = allow
return d
}

Expand Down Expand Up @@ -267,7 +267,7 @@ func (d *AMIDictionary) TranslateField(field string) string {
if ok {
return strings.ToLower(value)
} else {
if d.AllowForceTranslate {
if d.EnabledForceTranslate {
value = GetValByKey(dictionary.Dictionaries, field)
if len(value) > 0 {
return value
Expand All @@ -287,7 +287,7 @@ func (d *AMIDictionary) TranslateFieldWith(field string, dictionaries []AMIEvent
if v, ok := e.Dictionaries[field]; ok {
return strings.ToLower(v)
} else {
if d.AllowForceTranslate {
if d.EnabledForceTranslate {
value := GetValByKey(e.Dictionaries, field)
if len(value) > 0 {
return value
Expand Down
15 changes: 3 additions & 12 deletions pkg/ami/ami_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,19 @@ func (a *AMIAuth) SetEvents(events ...string) *AMIAuth {
return a
}

// Login
// Login provides the login manager.
func Login(ctx context.Context, s AMISocket, auth *AMIAuth) error {
// WithAuthenticate
// WithAuthenticate provides the login manager.
func WithAuthenticate(ctx context.Context, s AMISocket, auth *AMIAuth) error {
if len(auth.Username) <= 0 {
return fmt.Errorf(config.AmiErrorUsernameRequired)
}

if len(auth.Secret) <= 0 {
return fmt.Errorf(config.AmiErrorPasswordRequired)
}

if len(auth.Events) == 0 {
auth.SetEvent(config.AmiManagerPerm)
}

c := NewCommand()

if len(s.UUID) <= 0 {
uuid, err := GenUUID()
if err != nil {
Expand All @@ -67,24 +63,19 @@ func Login(ctx context.Context, s AMISocket, auth *AMIAuth) error {
} else {
c.SetId(s.UUID)
}

c.SetV(auth)
c.SetAction(config.AmiActionLogin)
callback := NewAmiCallbackService(ctx, s, c, []string{}, []string{})
response, err := callback.Send()

if len(response) == 0 {
return fmt.Errorf(config.AmiErrorLoginFailed)
}

if err != nil {
return fmt.Errorf(config.AmiErrorLoginFailedMessage, err.Error())
}

if IsFailure(response) {
return fmt.Errorf(config.AmiErrorLoginFailedMessage, response.Get(config.AmiFieldMessage))
}

return nil
}

Expand Down
8 changes: 4 additions & 4 deletions pkg/ami/ami_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ type AMIEvent struct {
}

type AMIDictionary struct {
AllowForceTranslate bool `json:"allow_force_translate"`
EnabledForceTranslate bool `json:"enabled_force_translate"`
}

type AMIEventDictionary struct {
Expand All @@ -68,8 +68,8 @@ type AMIGrouping struct {
}

type AMIAction struct {
ActionCmd string `json:"action_cmd"`
Timeout int `json:"timeout,omitempty"`
Name string `json:"name"`
Timeout int `json:"timeout,omitempty"`
}

type AMIResponse struct {
Expand Down Expand Up @@ -113,7 +113,7 @@ type AMICommand struct {

type AMIAuth struct {
Username string `ami:"Username" json:"username" binding:"required"`
Secret string `ami:"Secret" json:"secret" binding:"required"`
Secret string `ami:"Secret" json:"-" binding:"required"`
Events string `ami:"Events,omitempty" json:"events" binding:"required"`
}

Expand Down
8 changes: 3 additions & 5 deletions pkg/ami/ami_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ func NewAmiSocket() *AMISocket {
DebugMode: false,
}
d := NewDictionary()
d.SetAllowForceTranslate(true)
d.SetEnabledForceTranslate(true)

s.SetDictionary(d)
s.SetUsedDictionary(true)
s.SetRetry(true)
s.SetMaxRetries(3)
s.SetMaxConcurrencyMillis(config.AmiMaxConcurrencyMillis) // 1 minute = 60000 millis
s.SetMaxConcurrencyMillis(-1)
return s
}

Expand All @@ -42,9 +42,7 @@ func (s *AMISocket) SetMaxRetries(value int) *AMISocket {
}

func (s *AMISocket) SetMaxConcurrencyMillis(value int64) *AMISocket {
if value > 0 {
s.MaxConcurrencyMillis = value
}
s.MaxConcurrencyMillis = value
return s
}

Expand Down

0 comments on commit 12ea69a

Please sign in to comment.