index.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package ami
  2. import (
  3. "pms-api-go/internal/app/ami/model"
  4. "pms-api-go/pkg/configs"
  5. "pms-api-go/pkg/lfshook"
  6. "strings"
  7. "pms-api-go/internal/app/redis"
  8. socketio "pms-api-go/internal/app/socket_io"
  9. "github.com/mitchellh/mapstructure"
  10. "github.com/sirupsen/logrus"
  11. "github.com/tqcenglish/amigo-go"
  12. "github.com/tqcenglish/amigo-go/pkg"
  13. )
  14. var AminInstance *amigo.Amigo
  15. // const VTIGER_URL = "https://zycoo1.od2.vtiger.com"
  16. // 认证信息添加到 ./config.yaml
  17. // const BasicAuthUser = "juncheng.du@zycoo.com"
  18. // const BasicAuthPWD = "8DJ3O28MCZ4sPAk5"
  19. // const ApiKey = "X-VTIGER-SECRET"
  20. // const ApiKeyValue = "174781790673da476e25cf"
  21. func StartAMI(connectOKCallBack func(), handleEvents []func(event map[string]string), apiType string) {
  22. lfshook.NewLogger().Info("Start AMI")
  23. settings := &amigo.Settings{
  24. Host: configs.ConfigGlobal.AsteriskAMIHost,
  25. Port: configs.ConfigGlobal.AsteriskAMIPort,
  26. Username: configs.ConfigGlobal.AsteriskAMIUser,
  27. Password: configs.ConfigGlobal.AsteriskAMISecret,
  28. LogLevel: logrus.InfoLevel}
  29. lfshook.NewLogger().Infof("ami setting: %+v", settings)
  30. AminInstance = amigo.New(settings, lfshook.NewLogger())
  31. AminInstance.EventOn(func(payload ...interface{}) {
  32. // lfshook.NewLogger().Infof("ami event on %+v", payload[0])
  33. event := payload[0].(map[string]string)
  34. handleAMIBridge(event)
  35. handleAMI(event)
  36. handleSocketIO(event)
  37. // /* 20241128 vtiger crm 对应 ============================================================
  38. if apiType == "CRM_vtiger" {
  39. phoneCalls(event)
  40. } else if apiType == "CRM_zoho" {
  41. callNotify(event)
  42. }
  43. // * ===================================================================================== */
  44. /* 20241128 vtiger crm 对应 ============================================================
  45. fmt.Println("=========================================== ")
  46. fmt.Println("event[] = ", event)
  47. fmt.Println("event = ", event["Event"])
  48. fmt.Println("AMIPushUrl = ", configs.PushConfigValue.AMIPushUrl)
  49. fmt.Println("Channel = ", event["Channel"])
  50. var callId string
  51. if event["Channel"] != "" {
  52. callId = strings.Split(strings.Split(event["Channel"], "/")[1], "-")[0]
  53. fmt.Println("callId = ", callId)
  54. }
  55. // if configs.PushConfigValue.AMIPushUrl != "" {
  56. // for _, eventName := range configs.PushConfigValue.AMIEvents {
  57. // if eventName == event["Event"] {
  58. // go httpclient.Post(event, configs.PushConfigValue.AMIPushUrl)
  59. // break
  60. // }
  61. // }
  62. // }
  63. callId = "10000007" // 测试用,每次测试 +1
  64. recordingUrl := "https%3A%2F%2Fs3.amazonaws.com%2Frecordings_2013%2F8e522852-72aa-11e5-ab5f-842b2b021118.mp3" // 测试用
  65. event["Exten"] = "123456789" // 测试用
  66. fmt.Println("Exten = ", event["Exten"])
  67. // 读取vtiger配置文件
  68. confPath := "/etc/asterisk/vtiger_api.conf"
  69. cfg, err := ini.Load(confPath)
  70. if err != nil {
  71. lfshook.NewLogger().Error(err)
  72. return
  73. }
  74. VTIGER_URL := cfg.Section("general").Key("vtigerUrl").String()
  75. if VTIGER_URL == "" {
  76. lfshook.NewLogger().Error("/etc/asterisk/vtiger_api.conf not set vtigerUrl")
  77. return
  78. }
  79. // 呼叫发起事件
  80. if event["Event"] == "DialBegin" { // "DialBegin" "Newchannel"
  81. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?from=147258369&to=12300001&event=call_initiated&call_id=12345678&direction=inbound
  82. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?from=86147258369&event=call_initiated&call_id=12345678 // 可以省去部分参数
  83. getURL := fmt.Sprintf("%s/modules/PhoneCalls/callbacks/Generic.php?from=%s&event=call_initiated&call_id=%s", VTIGER_URL, event["Exten"], callId)
  84. // fmt.Println("getURL = ", getURL)
  85. // go httpclient.Get(getURL)
  86. go httpclient.ApiKeyGet(getURL) // 后面要不要把用户密码给传过去
  87. // resp := httpclient.ApiKeyGet(getURL)
  88. // // 读取请求后的响应
  89. // data, err := ioutil.ReadAll(resp.Body)
  90. // if err != nil {
  91. // fmt.Println("读取请求后的响应时发生错误:", err)
  92. // return
  93. // }
  94. // // 打印请求后的响应
  95. // fmt.Printf("data = %+v\n", string(data))
  96. // 呼叫已连接事件
  97. } else if event["Event"] == "BridgeEnter" { // "Newstate" "BridgeEnter"
  98. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?from=86147258369&to=12300001&event=call_connected&call_id=12345678
  99. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?event=call_connected&call_id=12345678 // 可以省去部分参数
  100. getURL := fmt.Sprintf("%s/modules/PhoneCalls/callbacks/Generic.php?event=call_connected&call_id=%s", VTIGER_URL, callId)
  101. // fmt.Println("getURL = ", getURL)
  102. go httpclient.ApiKeyGet(getURL)
  103. // 通话录音事件
  104. } else if event["Event"] == "Cdr" {
  105. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?call_id=12345678&event=call_recording&recordingurl=https%3A%2F%2Fs3.amazonaws.com%2Frecordings_2013%2F8e522852-72aa-11e5-ab5f-842b2b021118.mp3
  106. getURL := fmt.Sprintf("%s/modules/PhoneCalls/callbacks/Generic.php?call_id=%s&event=call_recording&recordingurl=%s", VTIGER_URL, callId, recordingUrl)
  107. // fmt.Println("getURL = ", getURL)
  108. go httpclient.ApiKeyGet(getURL)
  109. // 呼叫转移事件
  110. // Command:SET VARIABLE FORWARD_TYPE "busy" Command:SET VARIABLE FORWARD_DEST "136"
  111. // Command:SET VARIABLE FORWARD_TYPE "always" Command:SET VARIABLE FORWARD_DEST "136"
  112. // Command:SET VARIABLE FORWARD_TYPE "noan_busy" Command:SET VARIABLE FORWARD_DEST "136"
  113. // Command:SET VARIABLE FORWARD_TYPE "noan_unav" Command:SET VARIABLE FORWARD_DEST "136"
  114. // Command:SET VARIABLE FORWARD_TYPE "unavailable" Command:SET VARIABLE FORWARD_DEST "136"
  115. } else if strings.Contains(event["Command"], "FORWARD_DEST") {
  116. // transferredNumber := strings.Split(event["Command"], "\"")[1] // 正式用
  117. transferredNumber := "147258369" // 测试用
  118. // fmt.Println("Command = ", event["Command"])
  119. // fmt.Println("transferredNumber = ", transferredNumber)
  120. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?call_id=12345678&event=call_transfer&transferred_number=147258369
  121. getURL := fmt.Sprintf("%s/modules/PhoneCalls/callbacks/Generic.php?call_id=%s&event=call_transfer&transferred_number=%s", VTIGER_URL, callId, transferredNumber)
  122. // fmt.Println("getURL = ", getURL)
  123. go httpclient.ApiKeyGet(getURL)
  124. // 呼叫挂断事件
  125. } else if event["Event"] == "HangupRequest" { // "HangupRequest" "Hangup"
  126. // https://zycoo1.od2.vtiger.com/modules/PhoneCalls/callbacks/Generic.php?call_id=12345678&event=call_hangup
  127. getURL := fmt.Sprintf("%s/modules/PhoneCalls/callbacks/Generic.php?call_id=%s&event=call_hangup", VTIGER_URL, callId)
  128. fmt.Println("getURL = ", getURL)
  129. go httpclient.ApiKeyGet(getURL)
  130. }
  131. // 按编号搜索API 暂时用的以下接口
  132. // group.GET("/vtiger/lookup", contactsInfo) // 按编号搜索
  133. // * ===================================================================================== */
  134. for _, handle := range handleEvents {
  135. go handle(event)
  136. }
  137. })
  138. AminInstance.ConnectOn(func(payload ...interface{}) {
  139. if payload[0] == pkg.Connect_OK {
  140. lfshook.NewLogger().Info("ami connect ok")
  141. ClearBridge()
  142. connectOKCallBack()
  143. } else {
  144. lfshook.NewLogger().Errorf("ami connect failure %+v", payload)
  145. }
  146. })
  147. AminInstance.Connect()
  148. }
  149. func handleAMI(event map[string]string) {
  150. switch event["Event"] {
  151. case "ContactStatus":
  152. endpointName := event["EndpointName"]
  153. contactStatus := event["ContactStatus"]
  154. // NonQualified
  155. round := event["RoundtripUsec"]
  156. if round == "" {
  157. round = "1000"
  158. }
  159. uri := event["URI"]
  160. data := strings.Split(uri, "@")
  161. if len(data) < 2 {
  162. lfshook.NewLogger().Debugf("split URI by @ error URI: %s event:%+v", uri, event)
  163. return
  164. }
  165. first := data[1]
  166. // 中继变化也会触发此事件, 需要忽略
  167. switch contactStatus {
  168. case "Removed":
  169. //remove contact
  170. redis.ExtensionDel(endpointName, event["URI"], strings.Split(first, ":")[0], round)
  171. case "Reachable":
  172. fallthrough
  173. default:
  174. redis.ExtensionSet(endpointName, event["URI"], strings.Split(first, ":")[0], round)
  175. }
  176. case "ExtensionStatus":
  177. status := &model.ExtensionStatus{
  178. Event: event["Event"],
  179. Exten: event["Exten"],
  180. Context: event["Context"],
  181. Hint: event["Hint"],
  182. Status: event["Status"],
  183. StatusText: event["StatusText"],
  184. }
  185. redis.ExtensionSetStatus(status)
  186. }
  187. }
  188. func handleSocketIO(event map[string]string) {
  189. var data interface{}
  190. switch event["Event"] {
  191. case "ExtensionStatus":
  192. lfshook.NewLogger().Tracef("ExtensionStatus %+v", event)
  193. status := &model.ExtensionStatus{}
  194. mapstructure.Decode(event, status)
  195. data = status
  196. case "QueueMemberStatus":
  197. lfshook.NewLogger().Tracef("QueueMemberStatus %+v", event)
  198. status := &model.QueueMember{}
  199. mapstructure.Decode(event, status)
  200. data = status
  201. case "QueueCallerJoin":
  202. status := &model.QueueCallerJoin{}
  203. lfshook.NewLogger().Infof("status %+v", event)
  204. mapstructure.Decode(event, status)
  205. data = status
  206. case "QueueCallerLeave":
  207. status := &model.QueueCallerLeave{}
  208. mapstructure.Decode(event, status)
  209. data = status
  210. case "QueueCallerAbandon":
  211. status := &model.QueueCallerAbandon{}
  212. mapstructure.Decode(event, status)
  213. data = status
  214. case "ParkedCall":
  215. status := &model.ParkedCall{}
  216. mapstructure.Decode(event, status)
  217. data = status
  218. case "ParkedCallTimeOut":
  219. status := &model.ParkedCallTimeOut{}
  220. mapstructure.Decode(event, status)
  221. data = status
  222. case "ParkedCallGiveUp":
  223. status := &model.ParkedCallGiveUp{}
  224. mapstructure.Decode(event, status)
  225. data = status
  226. case "UnParkedCall":
  227. status := &model.UnParkedCall{}
  228. mapstructure.Decode(event, status)
  229. data = status
  230. case "MeetmeEnd":
  231. status := &model.MeetmeEnd{}
  232. mapstructure.Decode(event, status)
  233. data = status
  234. case "MeetmeJoin":
  235. fallthrough
  236. case "MeetmeLeave":
  237. fallthrough
  238. case "MeetmeMute":
  239. fallthrough
  240. case "MeetmeTalking":
  241. fallthrough
  242. case "MeetmeTalkRequest":
  243. status := &model.Meetme{}
  244. mapstructure.Decode(event, status)
  245. data = status
  246. case "PresenceStateChange":
  247. status := &model.PresenceStateChange{}
  248. mapstructure.Decode(event, status)
  249. if status.Presentity != "" {
  250. data := strings.Split(status.Presentity, ":")
  251. if len(data) == 2 {
  252. status.Extension = data[1]
  253. }
  254. }
  255. if status.Status == "dnd" {
  256. status.DndStatus = "yes"
  257. } else {
  258. status.DndStatus = ""
  259. }
  260. data = status
  261. case "DialBegin":
  262. fallthrough
  263. case "DialEnd":
  264. fallthrough
  265. case "DialState":
  266. status := &model.Dial{}
  267. mapstructure.Decode(event, status)
  268. data = status
  269. case "Newstate":
  270. status := &model.Newstate{}
  271. mapstructure.Decode(event, status)
  272. data = status
  273. case "Hangup":
  274. status := &model.Hangup{}
  275. mapstructure.Decode(event, status)
  276. data = status
  277. case "UserEvent":
  278. switch event["UserEvent"] {
  279. case "SetDND":
  280. status := &model.SetDND{}
  281. mapstructure.Decode(event, status)
  282. data = status
  283. if status.DNDStatus == "1" {
  284. redis.ExtensionDNDSet(status.Exten, "yes")
  285. } else {
  286. redis.ExtensionDNDDel(status.Exten)
  287. }
  288. event["Event"] = event["UserEvent"]
  289. case "WakeUpStatus":
  290. status := &model.WakeUpStatus{}
  291. mapstructure.Decode(event, status)
  292. data = status
  293. event["Event"] = event["UserEvent"]
  294. default:
  295. data = event
  296. }
  297. case "SuccessfulAuth":
  298. // 获取上线 IP 地址
  299. // !TODO 通过代理服务器地址不正确
  300. status := &model.SuccessfulAuth{}
  301. mapstructure.Decode(event, status)
  302. status.GetAddress()
  303. data = status
  304. case "ContactStatus":
  305. status := &model.ContactStatus{}
  306. mapstructure.Decode(event, status)
  307. status.GetAddress()
  308. data = status
  309. case "MessageWaiting":
  310. status := &model.MessageWaiting{}
  311. mapstructure.Decode(event, status)
  312. status.GetExtension()
  313. data = status
  314. if status.Extension == "" {
  315. lfshook.NewLogger().Warnf("MessageWaiting error %+v", event)
  316. return
  317. }
  318. default:
  319. // if !strings.Contains(event["Event"], "RTP") &&
  320. // !strings.Contains(event["Event"], "RTCP") &&
  321. // !strings.Contains(event["Event"], "VarSet") &&
  322. // !strings.Contains(event["Event"], "Bridge") &&
  323. // !strings.Contains(event["Event"], "New") &&
  324. // !strings.Contains(event["Event"], "SuccessfulAuth") &&
  325. // !strings.Contains(event["Event"], "ChallengeSent") {
  326. // lfshook.NewLogger().Info(event)
  327. // }
  328. }
  329. if data != nil {
  330. // if configs.ConfigGlobal.FilterEventPushUrl != "" {
  331. // httpclient.Post(data, configs.ConfigGlobal.FilterEventPushUrl)
  332. // }
  333. socketio.SocketIOServer.BroadcastToNamespace("", event["Event"], data)
  334. }
  335. }
  336. func Connected() bool {
  337. if AminInstance != nil {
  338. return AminInstance.Connected()
  339. }
  340. return false
  341. }