index.go 13 KB

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