index.go 13 KB

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