push.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package zoho
  2. import (
  3. "crm-api/pkg/configs"
  4. "crm-api/pkg/httpclient"
  5. "crm-api/pkg/lfshook"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "strconv"
  11. "time"
  12. "gopkg.in/ini.v1"
  13. )
  14. var TimestampList = make(map[string]string)
  15. var StartTimeList = make(map[string]time.Time) // 事件中 Timestamp 转 StartTime 有问题,重新记录时间
  16. // var CallTypeList = make(map[string]string) // 临时记录 incoming 和 outgoing
  17. var DialStatusList = make(map[string]string) // 临时记录 DialStatus:ANSWER NOANSWER
  18. // func addOneToStringNumber(s string) string {
  19. // num, err := strconv.Atoi(s)
  20. // if err != nil {
  21. // fmt.Println("xxxxxxxxxxxxx = ", err)
  22. // }
  23. // num++
  24. // return strconv.Itoa(num)
  25. // }
  26. func CallNotify(event map[string]string) {
  27. // fmt.Println("=========================================== ")
  28. fmt.Println("event111111111111111111111111111111111[] = ", event)
  29. fmt.Println("Cause111111111111111111111111111111111 = ", event["Cause"])
  30. fmt.Println("AMIPushUrl1111111111111111111111111111 = ", configs.PushConfigValue.AMIPushUrl)
  31. fmt.Println("Channel1111111111111111111111111111111 = ", event["Uniqueid"])
  32. /* ===================不这样取callDest,删除 ====================
  33. var callDest string
  34. if event["Channel"] != "" {
  35. callDest = strings.Split(strings.Split(event["Channel"], "/")[1], "-")[0]
  36. fmt.Println("callDest = ", callDest)
  37. }
  38. // * ========================================================= */
  39. // var callId string
  40. // timestamp := time.Now().Unix()
  41. // rand.Seed(time.Now().UnixNano())
  42. // // 字符串
  43. // charset := "abcdefghijklmnopqrstuvwxyz"
  44. // // 获取随机字符
  45. // c := charset[rand.Intn(len(charset))]
  46. // callId = "callid" + strconv.Itoa(int(timestamp))
  47. // if callId == " " {
  48. // input := "callid100000"
  49. // num, err := strconv.Atoi(input)
  50. // if err != nil {
  51. // fmt.Println("x11111111111 = ", err)
  52. // }
  53. // num++
  54. // callId = strconv.Itoa(num)
  55. // fmt.Println("callId111111111 = ", callId)
  56. // } else {
  57. // num, err := strconv.Atoi(callId)
  58. // if err != nil {
  59. // fmt.Println("x22222222222222 = ", err)
  60. // }
  61. // num++
  62. // callId = strconv.Itoa(num)
  63. // fmt.Println("callId2222222222 = ", callId)
  64. // }
  65. // var callId = "callid100014" // 测试用,每次测试 +1
  66. // event["Exten"] = "123456789" // 测试用
  67. // fmt.Println("callId = ", callId)
  68. // var zohoUser = "872297346" // 测试用 872297346 873447071 // 后面看是否从数据库中取 t_zoho_user
  69. // var info TabZohouser
  70. // if _, err := mysql.DBOrmInstance.Insert(&info); err != nil {
  71. // lfshook.NewLogger().Error(err)
  72. // return
  73. // }
  74. // var zohoUser = info.UserId
  75. // 读取vtiger配置文件
  76. confPath := "/etc/asterisk/crm_api.conf"
  77. cfg, err := ini.Load(confPath)
  78. if err != nil {
  79. lfshook.NewLogger().Error(err)
  80. return
  81. }
  82. ZOHO_URL := cfg.Section("general").Key("zohoUrl").String()
  83. if ZOHO_URL == "" {
  84. lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoUrl")
  85. return
  86. }
  87. // var getURL string
  88. fmt.Println("Context = ", event["Context"])
  89. // 呼叫发起事件
  90. // if event["Event"] == "DialBegin" && event["Context"] == "macro-stdexten" {
  91. // if event["Event"] == "DialBegin" && strings.Compare(event["Context"], "macro-stdexten") == 0 {
  92. if event["Event"] == "DialBegin" {
  93. /* ===================先放这里测试用 ============================================================
  94. // 记录开始时间
  95. TimestampList[event["Uniqueid"]] = event["Timestamp"]
  96. // StartTimeList[event["Uniqueid"]] = time.Now().Format("2006-01-02 15:04:09")
  97. StartTimeList[event["Uniqueid"]] = time.Now()
  98. /* ===================先放这里测试用 ============================================================
  99. fmt.Printf("Uniqueid=%s\n", event["Uniqueid"])
  100. fmt.Printf("Timestamp=%s\n", event["Timestamp"])
  101. TimestampTmp, err := strconv.Atoi(event["Timestamp"]) // 不要
  102. if err != nil {
  103. fmt.Printf("转换出错: %v\n", err)
  104. return
  105. }
  106. fmt.Printf("TimestampAtoi=%d\n", TimestampTmp)
  107. TimestampTmp002, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
  108. if err != nil {
  109. fmt.Printf("转换出错: %v\n", err)
  110. return
  111. }
  112. fmt.Printf("TimestampParseFloat=%f\n", TimestampTmp002)
  113. // * ===================================================================================== */
  114. // Outgoing Call - Ringing
  115. if event["Context"] == "macro-trunkdial-failover" {
  116. lfshook.NewLogger().Info("Outgoing Call - Ringing")
  117. fmt.Println("event[] = ", event)
  118. fmt.Println("event = ", event["Event"])
  119. fmt.Println("Linkedid = ", event["Timestamp"])
  120. StartTimeList[event["Linkedid"]] = time.Now().Add(-8 * time.Hour)
  121. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=ringing&id=10031&from=123456789&to=12300000001
  122. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"])
  123. // if zohoUser != "" {
  124. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  125. // }
  126. fmt.Println("getURL = ", getURL)
  127. go httpclient.ZohoGet(getURL)
  128. // Incoming Call - Ringing
  129. // if event["Context"] == "macro-stdexten" {
  130. } else if event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  131. lfshook.NewLogger().Error("Incoming Call - Ringing")
  132. fmt.Println("event[] = ", event)
  133. fmt.Println("event = ", event["Event"])
  134. StartTimeList[event["Linkedid"]] = time.Now().Add(-8 * time.Hour)
  135. fmt.Println("Linkedid = ", event["Timestamp"])
  136. // if strings.Compare(event["Context"], "macro-stdexten") == 0 { // OK
  137. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ringing&id=10033&from=12300000001&to=123456789
  138. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["Exten"], callDest) // 取得from to 可能不准
  139. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"])
  140. // if zohoUser != "" {
  141. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  142. // }
  143. fmt.Println("getURL = ", getURL)
  144. go httpclient.ZohoGet(getURL)
  145. }
  146. // 呼叫结束事件
  147. } else if event["Event"] == "DialEnd" {
  148. // 记录呼叫状态
  149. DialStatusList[event["Linkedid"]] = event["DialStatus"]
  150. fmt.Println("DialEnd[] = ", event)
  151. fmt.Println("DialEnd = ", event["Event"])
  152. // Outgoing Call - Unattended
  153. if event["Context"] == "macro-trunkdial-failover" && event["DialStatus"] == "CANCEL" {
  154. lfshook.NewLogger().Info("Outgoing Call - CANCEL")
  155. fmt.Println("event[] = ", event)
  156. fmt.Println("event = ", event["Event"])
  157. fmt.Println("Linkedid = ", event["Timestamp"])
  158. // startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  159. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  160. startTime := startTimeutc.Format(time.RFC3339)
  161. fmt.Println("startTime: ", startTime)
  162. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=busy&id=10025&from=123456789&to=12300000001&start_time=2024-12-04 15:09:10
  163. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=busy&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  164. // if zohoUser != "" {
  165. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  166. // }
  167. fmt.Println("getURL = ", getURL)
  168. go httpclient.ZohoGet(getURL)
  169. // Incoming Call - Missed
  170. // if event["Context"] == "macro-stdexten" && event["DialStatus"] != "ANSWER" {
  171. } else if event["Context"] == "macro-trunkdial-failover" && event["DialStatus"] == "NOANSWER" {
  172. lfshook.NewLogger().Info("Outgoing Call - NOANSWER")
  173. fmt.Println("event[] = ", event)
  174. fmt.Println("event = ", event["Event"])
  175. fmt.Println("Linkedid = ", event["Timestamp"])
  176. // startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  177. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  178. startTime := startTimeutc.Format(time.RFC3339)
  179. fmt.Println("startTime: ", startTime)
  180. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=busy&id=10025&from=123456789&to=12300000001&start_time=2024-12-04 15:09:10
  181. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=noanswer&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  182. // if zohoUser != "" {
  183. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  184. // }
  185. fmt.Println("getURL = ", getURL)
  186. go httpclient.ZohoGet(getURL)
  187. // Incoming Call - Missed
  188. // if event["Context"] == "macro-stdexten" && event["DialStatus"] != "ANSWER" {
  189. } else if event["Context"] == "macro-trunkdial-failover" && event["DialStatus"] == "BUSY" {
  190. lfshook.NewLogger().Info("Outgoing Call - BUSY")
  191. fmt.Println("event[] = ", event)
  192. fmt.Println("event = ", event["Event"])
  193. fmt.Println("Linkedid = ", event["Timestamp"])
  194. // startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  195. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  196. startTime := startTimeutc.Format(time.RFC3339)
  197. fmt.Println("startTime: ", startTime)
  198. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=busy&id=10025&from=123456789&to=12300000001&start_time=2024-12-04 15:09:10
  199. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=rejected&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  200. // if zohoUser != "" {
  201. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  202. // }
  203. fmt.Println("getURL = ", getURL)
  204. go httpclient.ZohoGet(getURL)
  205. // Incoming Call - Missed
  206. // if event["Context"] == "macro-stdexten" && event["DialStatus"] != "ANSWER" {
  207. } else if (event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm") && event["DialStatus"] != "ANSWER" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  208. lfshook.NewLogger().Error("Incoming Call - Missed")
  209. fmt.Println("event[] = ", event)
  210. fmt.Println("event = ", event["Event"])
  211. // startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  212. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  213. startTime := startTimeutc.Format(time.RFC3339)
  214. fmt.Println("startTime: ", startTime)
  215. fmt.Println("Linkedid = ", event["Timestamp"])
  216. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=missed&id=10005&from=12300000001&to=123456789&start_time=2024-12-04 15:09:10
  217. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=missed&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  218. // if zohoUser != "" {
  219. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  220. // }
  221. fmt.Println("getURL = ", getURL)
  222. go httpclient.ZohoGet(getURL)
  223. }
  224. // 呼叫已连接事件
  225. } else if event["Event"] == "BridgeEnter" {
  226. // Outgoing Call - Answered
  227. if event["Context"] == "macro-trunkdial-failover" && event["Priority"] == "1" { // 注意这里选择 Priority:1 的,便于确认 CallerIDNum,ConnectedLineNum
  228. // 记录开始时间
  229. // TimestampList[event["Uniqueid"]] = event["Timestamp"] // error 需要把 Uniqueid 改为 Linkedid
  230. // StartTimeList[event["Uniqueid"]] = time.Now() // error 需要把 Uniqueid 改为 Linkedid
  231. lfshook.NewLogger().Info("Outgoing Call - Answered")
  232. fmt.Println("event[] = ", event)
  233. fmt.Println("event = ", event["Event"])
  234. fmt.Println("Linkedid = ", event["Timestamp"])
  235. TimestampList[event["Linkedid"]] = event["Timestamp"]
  236. StartTimeList[event["Linkedid"]] = time.Now().Add(-8 * time.Hour)
  237. // https: //www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=answered&id=10003&from=123456789&to=12300000001
  238. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"])
  239. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, event["Linkedid"], event["ConnectedLineNum"], event["CallerIDNum"])
  240. // if zohoUser != "" {
  241. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  242. // }
  243. fmt.Println("getURL = ", getURL)
  244. go httpclient.ZohoGet(getURL)
  245. // Incoming Call - Answered
  246. // if event["Context"] == "macro-stdexten" {
  247. } else if event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  248. // 记录开始时间
  249. // TimestampList[event["Uniqueid"]] = event["Timestamp"] // Uniqueid 有时通话也不合适 NG // 都改为 Linkedid
  250. // StartTimeList[event["Uniqueid"]] = time.Now() // Uniqueid 有时通话也不合适 NG // 都改为 Linkedid
  251. lfshook.NewLogger().Error("Incoming Call - Answered")
  252. fmt.Println("event[] = ", event)
  253. fmt.Println("event = ", event["Event"])
  254. fmt.Println("Linkedid = ", event["Timestamp"])
  255. TimestampList[event["Linkedid"]] = event["Timestamp"] // 呼入时设置 Uniqueid 不是 Linkedid
  256. StartTimeList[event["Linkedid"]] = time.Now().Add(-8 * time.Hour) // 呼入时设置 Uniqueid 不是 Linkedid
  257. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=answered&id=10023&from=12300000001&to=123456789
  258. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["ConnectedLineNum"])
  259. // if zohoUser != "" {
  260. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  261. // }
  262. fmt.Println("getURL = ", getURL)
  263. go httpclient.ZohoGet(getURL)
  264. }
  265. // 呼叫挂断事件
  266. } else if event["Event"] == "HangupRequest" {
  267. /* ===================先放这里测试用 ============================================================
  268. // 记录结束时间
  269. // TimestampList[event["Uniqueid"]] = event["Timestamp"]
  270. // startTimeStamp := int64(TimestampList[event["Uniqueid"]])
  271. fmt.Println("startTimeStamp Str: ", TimestampList[event["Uniqueid"]])
  272. // keyTmp := event["Uniqueid"]
  273. // fmt.Println("keyTmp: ", keyTmp)
  274. // fmt.Println("startTimeStamp Str: ", TimestampList[keyTmp])
  275. startTimeStamp, err := strconv.ParseFloat(TimestampList[event["Uniqueid"]], 64) // OK
  276. if err != nil {
  277. fmt.Printf("startTimeStamp转换出错: %v\n", err)
  278. return
  279. }
  280. fmt.Printf("startTimeStamp=%f\n", startTimeStamp)
  281. endTimeStamp, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
  282. if err != nil {
  283. fmt.Printf("endTimeStamp转换出错: %v\n", err)
  284. return
  285. }
  286. fmt.Printf("endTimeStamp=%f\n", endTimeStamp)
  287. durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
  288. fmt.Println("durationTime=", durationTime)
  289. // 删除记录时间
  290. // delete(TimestampList, event["Uniqueid"])
  291. // * ===================================================================================== */
  292. // 判断呼叫状态,为 ANSWER 时才推送,否则见以上推送 Outgoing Call - Unattended 或 Incoming Call - Missed
  293. fmt.Println("event[] = ", event)
  294. fmt.Println("event = ", event["Event"])
  295. lfshook.NewLogger().Errorf("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa %+v", event["Context"])
  296. fmt.Println("ChannelHangupRequest1 = ", DialStatusList[event["Linkedid"]])
  297. fmt.Println("ChannelHangupRequest1 = ", event["DialStatus"])
  298. if DialStatusList[event["Linkedid"]] == "ANSWER" {
  299. lfshook.NewLogger().Errorf("ChannelHangupRequest = %+v", event["Uniqueid"])
  300. fmt.Println("event[] = ", event)
  301. fmt.Println("event = ", event["Event"])
  302. lfshook.NewLogger().Errorf("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa %+v", event["Context"])
  303. lfshook.NewLogger().Errorf("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb %+v", event["Linkedid"])
  304. lfshook.NewLogger().Errorf("ccccccccccccccccccccccccccccccc %+v", event["DialStatus"])
  305. // Outgoing Call - Ended
  306. if event["Context"] == "macro-trunkdial-failover" {
  307. fmt.Println("Linkedid = ", event["Timestamp"])
  308. // 获取时间
  309. // durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
  310. durationTime := getDuration(event["Linkedid"], event["Timestamp"])
  311. // /* ===================测试用 ============================================================
  312. // startTime, _ := time.Parse("2006-01-02 15:04:05", TimestampList[event["Uniqueid"]]) // error 1734328213.774410 => 0001-01-01 00:00:00 +0000 UTC
  313. // startTime := StartTimeList[event["Uniqueid"]]
  314. // startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  315. // startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  316. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  317. startTime := startTimeutc.Format(time.RFC3339)
  318. fmt.Println("startTime: ", startTime)
  319. // durationTime002 := getDuration002(startTime)
  320. // durationTime002 := time.Now().Sub(StartTimeList[event["Uniqueid"]]) // ok durationTime002: 7.78408849s // should use time.Since instead of time.Now().Sub (S1012)
  321. // durationTime002 := time.Since(StartTimeList[event["Uniqueid"]]) // ok durationTime002: 11.611233458s
  322. // fmt.Println("durationTime002: ", durationTime002)
  323. // * ===================================================================================== */
  324. // 删除记录时间
  325. delete(StartTimeList, event["Linkedid"])
  326. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dailed&state=ended&id=10030&from=123456789&to=12300000001&start_time=2024-12-04 11:32:15&duration=325
  327. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
  328. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, event["Linkedid"], event["ConnectedLineNum"], event["CallerIDNum"], startTime, durationTime)
  329. // if zohoUser != "" {
  330. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  331. // }
  332. fmt.Println("getURL = ", getURL)
  333. go httpclient.ZohoGet(getURL)
  334. // Incoming Call - Ended
  335. // // if event["Context"] == "macro-stdexten" { // Context:DialPlan1
  336. } else { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  337. // if event["Context"] != "macro-trunkdial-failover" {
  338. fmt.Println("Linkedid = ", event["Timestamp"])
  339. // 还需优化判断,开启语音留言时,主叫挂断才是 macro-stdexten , 被叫挂断是 DialPlan1
  340. // 关闭语音留言时,主叫挂断才是 macro-stdexten-withoutvm , 被叫挂断是 DialPlan1
  341. // 如果 Outgoing Call 只会是 macro-trunkdial-failover 的话,那么和以下判断换一下,else 不判断,都为 Incoming Call 处理
  342. // 获取时间
  343. // durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
  344. // startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  345. durationTime := getDuration(event["Linkedid"], event["Timestamp"])
  346. startTimeutc := StartTimeList[event["Linkedid"]].In(time.UTC) // 存储从string 改为 time.Time
  347. startTime := startTimeutc.Format(time.RFC3339)
  348. fmt.Println("startTime: ", startTime)
  349. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ended&id=100&from=12300000001&to=123456789&start_time=2024-12-04 10:32:10&duration=223
  350. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, event["Linkedid"], event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
  351. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDName"], startTime, durationTime)
  352. // if zohoUser != "" {
  353. // getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  354. // }
  355. fmt.Println("getURL = ", getURL)
  356. go httpclient.ZohoGet(getURL)
  357. }
  358. }
  359. }
  360. // fmt.Println("getURL = ", getURL)
  361. // 测试验证下上面有没有删除,以防TimestampList越来越大
  362. // for k, v := range TimestampList {
  363. // fmt.Printf("===Linkedid:%s Timestamp:%s===\n", k, v)
  364. // }
  365. }
  366. // 使用事件中event["Timestamp"]的值计算时间间隔
  367. // func getDuration(uniqueid string, timeStamp string) int {
  368. func getDuration(linkedid string, timeStamp string) int { // 都改为 Linkedid
  369. fmt.Println("startTimeStamp Str: ", TimestampList[linkedid])
  370. if TimestampList[linkedid] == "" || timeStamp == "" {
  371. fmt.Printf("linkedid 或 timeStamp 为空\n")
  372. return 9999
  373. }
  374. startTimeStamp, err := strconv.ParseFloat(TimestampList[linkedid], 64)
  375. if err != nil {
  376. fmt.Printf("startTimeStamp转换出错: %v\n", err)
  377. return 9999
  378. }
  379. fmt.Printf("startTimeStamp=%f\n", startTimeStamp)
  380. endTimeStamp, err := strconv.ParseFloat(timeStamp, 64)
  381. if err != nil {
  382. fmt.Printf("endTimeStamp转换出错: %v\n", err)
  383. return 9999
  384. }
  385. fmt.Printf("endTimeStamp=%f\n", endTimeStamp)
  386. durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
  387. // fmt.Println("durationTime=", durationTime) // durationTime= 35s
  388. // fmt.Printf("durationTime=%d\n", durationTime) // durationTime=35000000000
  389. // fmt.Printf("durationTime=%d\n", durationTime.Seconds()) // durationTime=%!d(float64=35)
  390. // fmt.Printf("durationTime=%f\n", durationTime.Seconds()) // durationTime=35.000000
  391. fmt.Printf("durationTime=%d\n", int(durationTime.Seconds())) // durationTime=35
  392. // durationTime001 := time.Duration(endTimeStamp - startTimeStamp)
  393. // fmt.Println("durationTime001=", durationTime001) // durationTime001= 35ns
  394. // durationTime003 := time.Duration(endTimeStamp - startTimeStamp).Seconds()
  395. // fmt.Println("durationTime003=", durationTime003) // durationTime003= 3.5e-08
  396. // 删除记录时间
  397. delete(TimestampList, linkedid)
  398. // return durationTime
  399. return int(durationTime.Seconds())
  400. }
  401. // // 程序中取时间计算间隔多少秒
  402. // func getDuration002(startTime string) time.Duration {
  403. // // durationTime := endTime.Sub(startTime)
  404. // startTime002, err := time.Parse("2006-01-02 15:04:05", startTime)
  405. // if err != nil {
  406. // fmt.Println("Error parsing time:", err)
  407. // return 0
  408. // }
  409. // durationTime := time.Now().Sub(startTime002)
  410. // return durationTime
  411. // }
  412. // @tags PBX-zoho
  413. // @Summary 刷新token
  414. // @Description 刷新token
  415. // @Security ZohoToken
  416. // @Accept json
  417. // @Produce json
  418. // @Router /api/zoho/refresh-token [post]
  419. func RefreshToken() {
  420. fmt.Printf("RefreshToken ............\n")
  421. // 获取配置文件信息
  422. // confPath := "/etc/asterisk/vtiger_api.conf"
  423. confPath := "/etc/asterisk/crm_api.conf"
  424. cfg, err := ini.Load(confPath)
  425. if err != nil {
  426. lfshook.NewLogger().Error(err)
  427. return
  428. }
  429. ZohoAuthUrl := cfg.Section("general").Key("zohoAuthUrl").String()
  430. ZohoRefreshToken := cfg.Section("general").Key("zohoRefreshToken").String()
  431. ZohoClientId := cfg.Section("general").Key("zohoClientId").String()
  432. ZohoClientSecret := cfg.Section("general").Key("zohoClientSecret").String()
  433. if ZohoAuthUrl == "" || ZohoRefreshToken == "" || ZohoClientId == "" || ZohoClientSecret == "" {
  434. lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoAuthUrl or zohoRefreshToken or zohoClientId or zohoClientSecret")
  435. return
  436. }
  437. // 创建请求
  438. // https://accounts.zoho.com/oauth/v2/token?refresh_token=1004.86c8c0e3db7bfe9133598825bef28eb9.17a82a3bf3e675c504f478c1b0b5c456
  439. // &client_id=1004.LWJCJZD5O9DB6SZLL5YJEWHT7LH0BV&client_secret=fc3aef43dc58af8a49d3ed597710924200b03f74d0&grant_type=refresh_token
  440. getURL := fmt.Sprintf("%s/oauth/v2/token?refresh_token=%s&client_id=%s&client_secret=%s&grant_type=refresh_token", ZohoAuthUrl, ZohoRefreshToken, ZohoClientId, ZohoClientSecret)
  441. fmt.Printf("getURL = %s\n", getURL)
  442. // data := httpRequest(ctx, "POST", getURL)
  443. // /* =====================================================================================
  444. req, err := http.NewRequest("POST", getURL, nil)
  445. if err != nil {
  446. fmt.Println("创建请求时发生错误:", err)
  447. return
  448. }
  449. // 创建HTTP客户端
  450. client := &http.Client{}
  451. // req.Header.Set("Authorization", "Bearer "+accessToken) // 刷新token时不需要
  452. // 发送请求
  453. resp, err := client.Do(req)
  454. if err != nil {
  455. fmt.Println("发送请求时发生错误:", err)
  456. return
  457. }
  458. defer resp.Body.Close()
  459. // 读取请求后的响应
  460. data, err := ioutil.ReadAll(resp.Body)
  461. if err != nil {
  462. // 读取数据错误
  463. lfshook.NewLogger().Warn("ioutil ReadAll failed :", err.Error())
  464. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  465. return
  466. }
  467. lfshook.NewLogger().Infof("data %+v", string(data))
  468. // * ===================================================================================== */
  469. refreshTokenData := RefreshTokenResp{}
  470. err = json.Unmarshal([]byte(data), &refreshTokenData)
  471. if err != nil {
  472. // 转换数据错误
  473. lfshook.NewLogger().Warn("json unmarshal failed :", err.Error())
  474. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  475. return
  476. }
  477. // 将获取的 access_token 写入文件 crm_api.conf
  478. cfg.Section("general").Key("zohoAccessToken").SetValue(refreshTokenData.AccessToken)
  479. err = cfg.SaveTo(confPath)
  480. if err != nil {
  481. lfshook.NewLogger().Error(err)
  482. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  483. return
  484. }
  485. // 打印请求后的响应
  486. fmt.Printf("data = %+v\n", string(data))
  487. // api.Success(ctx, string(data))
  488. // api.Success(ctx, refreshTokenData)
  489. // return
  490. }
  491. // 每隔55分钟刷新token
  492. func RefreshTokenTicker() {
  493. fmt.Printf("RefreshTokenTicker ............\n")
  494. ticker := time.NewTicker(55 * time.Minute)
  495. defer ticker.Stop()
  496. done := make(chan bool)
  497. // go func() { // 注释掉OK
  498. for {
  499. select {
  500. case <-done:
  501. return
  502. case t := <-ticker.C:
  503. fmt.Println("Tick at", t)
  504. RefreshToken()
  505. }
  506. }
  507. // }()
  508. }