aodun.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "encoding/json"
  7. "fmt"
  8. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  9. "github.com/spf13/viper"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. )
  16. type AoDunService interface {
  17. DomainWhiteList(ctx context.Context, domain string, ip string, apiType string) error
  18. AddWhiteStaticList(ctx context.Context, req []v1.IpInfo) error
  19. DelWhiteStaticList(ctx context.Context, req v1.DeleteIp) error
  20. }
  21. func NewAoDunService(
  22. service *Service,
  23. conf *viper.Viper,
  24. ) AoDunService {
  25. return &aoDunService{
  26. Service: service,
  27. Url: conf.GetString("aodun.Url"),
  28. clientID: conf.GetString("aodun.clientID"),
  29. username: conf.GetString("aodun.username"),
  30. password: conf.GetString("aodun.password"),
  31. IPusername: conf.GetString("aodunIp.username"),
  32. IPpassword: conf.GetString("aodunIp.password"),
  33. domainUserName: conf.GetString("domainWhite.username"),
  34. domainPassword: conf.GetString("domainWhite.password"),
  35. }
  36. }
  37. type aoDunService struct {
  38. *Service
  39. Url string
  40. clientID string
  41. username string
  42. password string
  43. IPusername string
  44. IPpassword string
  45. domainUserName string
  46. domainPassword string
  47. }
  48. func (s *aoDunService) sendFormData(ctx context.Context,apiUrl string,tokenType string,token string,formData map[string]interface{}) ([]byte,error) {
  49. URL := s.Url + apiUrl
  50. jsonData, err := json.Marshal(formData)
  51. if err != nil {
  52. return nil, fmt.Errorf("序列化请求数据失败: %w", err)
  53. }
  54. req, err := http.NewRequest("POST", URL, bytes.NewBuffer(jsonData))
  55. if err != nil {
  56. return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
  57. }
  58. // 设置请求头 Content-Type 为 "application/json"
  59. req.Header.Set("Content-Type", "application/json")
  60. if tokenType == "" {
  61. req.Header.Set("Authorization", tokenType + " " + token)
  62. }
  63. tr := &http.Transport{
  64. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // <--- 关键修改:忽略 SSL 验证
  65. }
  66. // 5. 使用 HTTP 客户端发送请求
  67. client := &http.Client{
  68. Transport: tr,
  69. Timeout: 15 * time.Second, // 设置一个合理的超时时间,例如15秒
  70. }
  71. resp, err := client.Do(req)
  72. if err != nil {
  73. return nil, fmt.Errorf("发送 HTTP 请求失败: %w", err)
  74. }
  75. // defer 确保在函数返回前关闭响应体,防止资源泄露
  76. defer resp.Body.Close()
  77. // 6. 读取响应体内容
  78. body, err := io.ReadAll(resp.Body)
  79. if err != nil {
  80. return nil, fmt.Errorf("读取响应体失败: %w", err)
  81. }
  82. return body, nil
  83. }
  84. func (s *aoDunService) sendDomainFormData(ctx context.Context,domain string,ip string,apiType string) ([]byte,error) {
  85. var URL string
  86. if apiType == "add" {
  87. URL = "http://zapi.zzybgp.com/api/user/do_main"
  88. } else {
  89. URL = "http://zapi.zzybgp.com/api/user/do_main/delete"
  90. }
  91. formData := url.Values{}
  92. formData.Set("username", s.domainUserName)
  93. formData.Set("password", s.domainPassword)
  94. formData.Add("do_main_list[name][]", domain)
  95. formData.Add("do_main_list[ip]", ip)
  96. encodedData := formData.Encode()
  97. req, err := http.NewRequest("POST", URL, bytes.NewBuffer([]byte(encodedData)))
  98. if err != nil {
  99. return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
  100. }
  101. // 设置请求头 Content-Type 为 "application/x-www-form-urlencoded"
  102. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  103. tr := &http.Transport{
  104. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // <--- 关键修改:忽略 SSL 验证
  105. }
  106. // 5. 使用 HTTP 客户端发送请求
  107. client := &http.Client{
  108. Transport: tr,
  109. Timeout: 15 * time.Second, // 设置一个合理的超时时间,例如15秒
  110. }
  111. resp, err := client.Do(req)
  112. if err != nil {
  113. return nil, fmt.Errorf("发送 HTTP 请求失败: %w", err)
  114. }
  115. // defer 确保在函数返回前关闭响应体,防止资源泄露
  116. defer resp.Body.Close()
  117. // 6. 读取响应体内容
  118. body, err := io.ReadAll(resp.Body)
  119. if err != nil {
  120. return nil, fmt.Errorf("读取响应体失败: %w", err)
  121. }
  122. return body, nil
  123. }
  124. func (s *aoDunService) GetToken(ctx context.Context) (string,string,error) {
  125. formData := map[string]interface{}{
  126. "ClientID": s.clientID,
  127. "GrantType": "password",
  128. "Username": s.IPusername,
  129. "Password": s.IPpassword,
  130. }
  131. resBody, err := s.sendFormData(ctx,"/oauth/token","","",formData)
  132. if err != nil {
  133. return "", "", err
  134. }
  135. // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
  136. var responsePayload v1.GetTokenRespone
  137. if err := json.Unmarshal(resBody, &responsePayload); err != nil {
  138. // 如果反序列化失败,可能是响应格式不符合预期
  139. return "", "", fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
  140. }
  141. // 8. 检查 API 返回的操作结果代码
  142. if responsePayload.Code != 0 {
  143. return "", "", fmt.Errorf("API 错误: code %d, msg '%s', remote_ip '%s'",
  144. responsePayload.Code, responsePayload.Msg, responsePayload.RemoteIP)
  145. }
  146. // 9. 成功:返回 access_token
  147. if responsePayload.AccessToken == "" {
  148. // 理论上 code 为 0 时应该有 access_token,这是一个额外的健壮性检查
  149. return "", "", fmt.Errorf("API 成功 (code 0) 但 access_token 为空")
  150. }
  151. return responsePayload.TokenType,responsePayload.AccessToken, nil
  152. }
  153. func (s *aoDunService) AddWhiteStaticList(ctx context.Context,req []v1.IpInfo) error {
  154. tokenType,token, err := s.GetToken(ctx)
  155. if err != nil {
  156. return err
  157. }
  158. formData := map[string]interface{}{
  159. "action" : "add",
  160. "bwflag" : "white",
  161. "insert_bw_list": req,
  162. }
  163. resBody, err := s.sendFormData(ctx,"/v1.0/firewall/static_bw_list",tokenType,token,formData)
  164. if err != nil {
  165. return err
  166. }
  167. // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
  168. var res v1.IpResponse
  169. if err := json.Unmarshal(resBody, &res); err != nil {
  170. // 如果反序列化失败,可能是响应格式不符合预期
  171. return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
  172. }
  173. if res.Code != 0 {
  174. if strings.Contains(res.Msg,"操作部分成功,重复IP如下") {
  175. s.logger.Info(res.Msg)
  176. return nil
  177. }
  178. return fmt.Errorf("API 错误: code %d, msg '%s'",
  179. res.Code, res.Msg)
  180. }
  181. return nil
  182. }
  183. func (s *aoDunService) GetWhiteStaticList(ctx context.Context,ip string) (int,error) {
  184. tokenType,token, err := s.GetToken(ctx)
  185. if err != nil {
  186. return 0, err
  187. }
  188. formData := map[string]interface{}{
  189. "action" : "get",
  190. "bwflag" : "white",
  191. "page" : 1,
  192. "ids": ip,
  193. }
  194. resBody, err := s.sendFormData(ctx,"/v1.0/firewall/static_bw_list",tokenType,token,formData)
  195. if err != nil {
  196. return 0, err
  197. }
  198. // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
  199. var res v1.IpGetResponse // 使用我们定义的 IpResponse 结构体
  200. if err := json.Unmarshal(resBody, &res); err != nil {
  201. // 如果反序列化失败,说明响应格式不符合预期
  202. return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
  203. }
  204. // 2. 检查 API 返回的 code,这是处理业务失败的关键
  205. if res.Code != 0 {
  206. // API 返回了错误码,例如 IP 不存在、参数错误等
  207. return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Msg)
  208. }
  209. // 3. 检查 data 数组是否为空
  210. // 即使 code 为 0,也可能因为没有匹配的数据而返回一个空数组
  211. if len(res.Data) == 0 {
  212. return 0, fmt.Errorf("API 调用成功,但未找到与 IP '%s' 相关的记录", ip)
  213. }
  214. // 4. 获取 ID 并返回
  215. // 假设我们总是取返回结果中的第一个元素的 ID
  216. id := res.Data[0].ID
  217. return id, nil // 成功!返回获取到的 id 和 nil 错误
  218. }
  219. func (s *aoDunService) DelWhiteStaticList(ctx context.Context, req v1.DeleteIp) error {
  220. tokenType, token, err := s.GetToken(ctx)
  221. if err != nil {
  222. return err
  223. }
  224. formData := map[string]interface{}{
  225. "action": "del",
  226. "bwflag": "white",
  227. "flag": 0,
  228. "ids": req.Ids,
  229. }
  230. resBody, err := s.sendFormData(ctx, "/v1.0/firewall/static_bw_list", tokenType, token, formData)
  231. if err != nil {
  232. return err
  233. }
  234. var res v1.IpResponse
  235. if err := json.Unmarshal(resBody, &res); err != nil {
  236. return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
  237. }
  238. if res.Code != 0 {
  239. return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Msg)
  240. }
  241. return nil
  242. }
  243. func (s *aoDunService) DomainWhiteList(ctx context.Context, domain string, ip string, apiType string) error {
  244. resBody, err := s.sendDomainFormData(ctx,domain,ip,apiType)
  245. if err != nil {
  246. return err
  247. }
  248. var res v1.DomainResponse
  249. if err := json.Unmarshal(resBody, &res); err != nil {
  250. return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
  251. }
  252. if res.Code != 200 && apiType == "add" {
  253. return fmt.Errorf("API 错误: code %d, msg '%s', data '%s", res.Code, res.Msg, res.Info)
  254. }
  255. if res.Code != 600 && apiType == "del" {
  256. return fmt.Errorf("API 错误: code %d, msg '%s', data '%s", res.Code, res.Msg, res.Info)
  257. }
  258. return nil
  259. }