ZoneCloudflareServer.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. package server
  2. import (
  3. "bytes"
  4. "cfTest/cloudflareApi/zone"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/cloudflare/cloudflare-go"
  10. "github.com/samber/lo"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "net/http"
  15. "strings"
  16. "time"
  17. )
  18. type ZoneServer struct {
  19. zone.UnimplementedZoneCloudflareServer
  20. }
  21. type Subscription struct {
  22. ID string `json:"id"`
  23. RatePlan struct {
  24. ID string `json:"id"`
  25. PublicName string `json:"public_name"`
  26. Currency string `json:"currency"`
  27. Scope string `json:"scope"`
  28. ExternallyManaged bool `json:"externally_managed"`
  29. Sets []string `json:"sets"`
  30. IsContract bool `json:"is_contract"`
  31. } `json:"rate_plan"`
  32. ComponentValues []struct {
  33. Name string `json:"name"`
  34. Value int `json:"value"`
  35. Default int `json:"default,omitempty"`
  36. } `json:"component_values"`
  37. Zone struct {
  38. ID string `json:"id"`
  39. Name string `json:"name"`
  40. } `json:"zone"`
  41. Frequency string `json:"frequency"`
  42. Currency string `json:"currency"`
  43. Price int `json:"price"`
  44. Product struct {
  45. Name string `json:"name"`
  46. Period string `json:"period"`
  47. Billing string `json:"billing"`
  48. PublicName string `json:"public_name"`
  49. Duration int `json:"duration"`
  50. } `json:"product"`
  51. CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
  52. CreatedDate time.Time `json:"created_date"`
  53. }
  54. var ArgoSubscriptionId = "argo_zone_ent_tryout"
  55. func (s *ZoneServer) GetArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  56. log.Printf("apiKey Received: %v", request.GetApiKey())
  57. log.Printf("apiEmail Received: %v", request.GetApiEmail())
  58. log.Printf("zoneId Received: %v", request.GetZoneId())
  59. //设置HTTP请求
  60. client := &http.Client{}
  61. req, err := http.NewRequest("GET", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscriptions", nil)
  62. if err != nil {
  63. return nil, err
  64. }
  65. req.Header.Add("X-Auth-Key", request.GetApiKey())
  66. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  67. //执行HTTP请求
  68. resp, err := client.Do(req)
  69. if err != nil {
  70. return nil, err
  71. }
  72. defer func(Body io.ReadCloser) {
  73. _ = Body.Close()
  74. }(resp.Body)
  75. body, _ := ioutil.ReadAll(resp.Body)
  76. type ResponseType struct {
  77. Errors []interface{} `json:"errors"`
  78. Messages []interface{} `json:"messages"`
  79. Result []Subscription `json:"result"`
  80. ResultInfo struct {
  81. NextPage bool `json:"next_page"`
  82. } `json:"result_info"`
  83. Success bool `json:"success"`
  84. }
  85. var r ResponseType
  86. err = json.Unmarshal(body, &r)
  87. //处理返回逻辑
  88. if err != nil {
  89. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  90. }
  91. if r.Success != true {
  92. return nil, fmt.Errorf("%s", r.Errors)
  93. }
  94. log.Printf("Response: %v", r)
  95. for _, v := range r.Result {
  96. if v.RatePlan.ID == ArgoSubscriptionId {
  97. return &zone.ArgoSetting{Enabled: true}, nil
  98. }
  99. }
  100. return &zone.ArgoSetting{Enabled: false}, nil
  101. }
  102. func (s *ZoneServer) CreateArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  103. log.Printf("apiKey Received: %v", request.GetApiKey())
  104. log.Printf("apiEmail Received: %v", request.GetApiEmail())
  105. log.Printf("zoneId Received: %v", request.GetZoneId())
  106. type RequestType struct {
  107. RatePlan struct {
  108. ID string `json:"id"`
  109. } `json:"rate_plan"`
  110. Zone struct {
  111. ID string `json:"id"`
  112. Name string `json:"name"`
  113. } `json:"zone"`
  114. }
  115. type ResponseType struct {
  116. Errors []interface{} `json:"errors"`
  117. Messages []interface{} `json:"messages"`
  118. Result Subscription `json:"result"`
  119. Success bool `json:"success"`
  120. }
  121. bytesData, err := json.Marshal(RequestType{
  122. RatePlan: struct {
  123. ID string `json:"id"`
  124. }{
  125. ID: ArgoSubscriptionId,
  126. },
  127. Zone: struct {
  128. ID string `json:"id"`
  129. Name string `json:"name"`
  130. }{
  131. ID: request.ZoneId,
  132. },
  133. })
  134. if err != nil {
  135. return nil, err
  136. }
  137. //设置HTTP请求
  138. client := &http.Client{}
  139. req, err := http.NewRequest("POST", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscription", bytes.NewReader(bytesData))
  140. if err != nil {
  141. return nil, err
  142. }
  143. req.Header.Add("X-Auth-Key", request.GetApiKey())
  144. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  145. //执行HTTP请求
  146. resp, err := client.Do(req)
  147. if err != nil {
  148. return nil, err
  149. }
  150. defer func(Body io.ReadCloser) {
  151. _ = Body.Close()
  152. }(resp.Body)
  153. body, _ := ioutil.ReadAll(resp.Body)
  154. var r ResponseType
  155. err = json.Unmarshal(body, &r)
  156. //处理返回逻辑
  157. if err != nil {
  158. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  159. }
  160. if r.Success != true {
  161. return nil, fmt.Errorf("%s", r.Errors)
  162. }
  163. log.Printf("Response: %v", r)
  164. if r.Result.RatePlan.ID == ArgoSubscriptionId {
  165. return &zone.ArgoSetting{Enabled: true}, nil
  166. }
  167. return &zone.ArgoSetting{Enabled: false}, nil
  168. }
  169. func (s *ZoneServer) UpdateArgoSetting(ctx context.Context, requestCloudflare *zone.UpdateArgoRequestCloudflare) (*zone.ArgoSetting, error) {
  170. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  171. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  172. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  173. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  174. if err != nil {
  175. return nil, err
  176. }
  177. settingValue := Proto2GoArgoSetting(requestCloudflare.GetArgoSetting())
  178. setting, err := api.UpdateArgoSmartRouting(ctx, requestCloudflare.ZoneId, settingValue)
  179. if err != nil {
  180. return nil, err
  181. }
  182. return Go2ProtoArgoSetting(setting.Value), nil
  183. }
  184. func (s *ZoneServer) GetArgoSetting(ctx context.Context, requestCloudflare *zone.IdRequest) (*zone.ArgoSetting, error) {
  185. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  186. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  187. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  188. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  189. if err != nil {
  190. return nil, err
  191. }
  192. setting, err := api.ArgoSmartRouting(ctx, requestCloudflare.ZoneId)
  193. if err != nil {
  194. return nil, err
  195. }
  196. return Go2ProtoArgoSetting(setting.Value), nil
  197. }
  198. func (s *ZoneServer) ZoneIDByNameCloudflare(ctx context.Context, requestCloudflare *zone.ZoneIDByNameRequestCloudflare) (*zone.ZoneIDByNameReplyCloudflare, error) {
  199. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  200. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  201. log.Printf("zoneName Received: %v", requestCloudflare.GetZoneName())
  202. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  203. if err != nil {
  204. return nil, err
  205. }
  206. id, err := api.ZoneIDByName(requestCloudflare.ZoneName)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return &zone.ZoneIDByNameReplyCloudflare{ZoneId: id}, err
  211. }
  212. func (s *ZoneServer) ZoneDetails(ctx context.Context, requestCloudflare *zone.ZoneDetailsRequestCloudflare) (*zone.ZoneDetailsReplyCloudflare, error) {
  213. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  214. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  215. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  216. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  217. if err != nil {
  218. return nil, err
  219. }
  220. ctxAPI := context.Background()
  221. details, err := api.ZoneDetails(ctxAPI, requestCloudflare.GetZoneId())
  222. if err != nil {
  223. return nil, err
  224. }
  225. return &zone.ZoneDetailsReplyCloudflare{
  226. Result: Go2ProtoZone(details),
  227. }, err
  228. }
  229. func (s *ZoneServer) GetZones(ctx context.Context, requestCloudflare *zone.GetZonesRequestCloudflare) (*zone.GetZonesReplyCloudflare, error) {
  230. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  231. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  232. log.Printf("domain Received: %v", requestCloudflare.GetDomain())
  233. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  234. if err != nil {
  235. return nil, err
  236. }
  237. details, err := api.ListZones(ctx, "name", requestCloudflare.GetDomain())
  238. if err != nil {
  239. return nil, err
  240. }
  241. list := make([]*zone.ZoneCloudflareEntity, len(details))
  242. for i, detail := range details {
  243. list[i] = Go2ProtoZone(detail)
  244. }
  245. return &zone.GetZonesReplyCloudflare{
  246. Result: list,
  247. Success: true,
  248. }, err
  249. }
  250. func (s *ZoneServer) ListZones(ctx context.Context, requestCloudflare *zone.ListZonesRequestCloudflare) (*zone.ZonesList, error) {
  251. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  252. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  253. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  254. if err != nil {
  255. return nil, err
  256. }
  257. ctxAPI := context.Background()
  258. details, err := api.ListZones(ctxAPI)
  259. if err != nil {
  260. return nil, err
  261. }
  262. list := make([]*zone.ZoneCloudflareEntity, len(details))
  263. for i, detail := range details {
  264. list[i] = Go2ProtoZone(detail)
  265. }
  266. return &zone.ZonesList{
  267. Result: list,
  268. }, err
  269. }
  270. func (s *ZoneServer) ListZonesByAccountId(ctx context.Context, requestCloudflare *zone.ListZonesByAccountIdRequestCloudflare) (*zone.ZonesList, error) {
  271. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  272. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  273. log.Printf("accountId Received: %v", requestCloudflare.GetAccountId())
  274. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  275. if err != nil {
  276. return nil, err
  277. }
  278. ctxAPI := context.Background()
  279. opt := cloudflare.WithZoneFilters("", requestCloudflare.AccountId, "")
  280. details, err := api.ListZonesContext(ctxAPI, opt)
  281. if err != nil {
  282. return nil, err
  283. }
  284. list := make([]*zone.ZoneCloudflareEntity, len(details.Result))
  285. for i, detail := range details.Result {
  286. list[i] = Go2ProtoZone(detail)
  287. }
  288. return &zone.ZonesList{
  289. Result: list,
  290. }, err
  291. }
  292. func (s *ZoneServer) EditZone(ctx context.Context, requestCloudflare *zone.EditZoneRequestCloudflare) (*zone.EditZoneReplyCloudflare, error) {
  293. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  294. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  295. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  296. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  297. if err != nil {
  298. return nil, err
  299. }
  300. ctxAPI := context.Background()
  301. opts := cloudflare.ZoneOptions{}
  302. opts.Paused = requestCloudflare.Paused
  303. if requestCloudflare.PlanId != nil {
  304. opts.Plan = &cloudflare.ZonePlan{
  305. ZonePlanCommon: cloudflare.ZonePlanCommon{
  306. ID: requestCloudflare.GetPlanId(),
  307. },
  308. }
  309. }
  310. if requestCloudflare.Type != nil {
  311. opts.Type = requestCloudflare.GetType()
  312. }
  313. editZone, err := api.EditZone(ctxAPI, requestCloudflare.GetZoneId(), opts)
  314. if err != nil {
  315. return nil, err
  316. }
  317. return &zone.EditZoneReplyCloudflare{
  318. Result: Go2ProtoZone(editZone),
  319. Success: true,
  320. }, nil
  321. }
  322. func (s *ZoneServer) DeleteZone(ctx context.Context, requestCloudflare *zone.DeleteZoneRequestCloudflare) (*zone.DeleteZoneReplyCloudflare, error) {
  323. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  324. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  325. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  326. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  327. if err != nil {
  328. return nil, err
  329. }
  330. ctxAPI := context.Background()
  331. deleteZone, err := api.DeleteZone(ctxAPI, requestCloudflare.GetZoneId())
  332. if err != nil {
  333. return nil, err
  334. }
  335. return &zone.DeleteZoneReplyCloudflare{
  336. Success: true,
  337. Id: deleteZone.ID,
  338. }, nil
  339. }
  340. func (s *ZoneServer) CreateZone(ctx context.Context, requestCloudflare *zone.CreateZoneRequestCloudflare) (*zone.CreateZoneReplyCloudflare, error) {
  341. log.Printf("request Received: %+v", requestCloudflare)
  342. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  343. if err != nil {
  344. return nil, err
  345. }
  346. ctxAPI := context.Background()
  347. account, _, err := api.Account(ctxAPI, requestCloudflare.GetAccountId())
  348. if err != nil {
  349. return nil, err
  350. }
  351. createZone, err := api.CreateZone(ctxAPI, requestCloudflare.GetDomain(), false, account, "partial")
  352. if err != nil {
  353. return nil, err
  354. }
  355. return &zone.CreateZoneReplyCloudflare{
  356. Success: true,
  357. Id: createZone.ID,
  358. }, nil
  359. }
  360. func (s *ZoneServer) SetZonePlan(ctx context.Context, requestCloudflare *zone.SetZonePlanRequestCloudflare) (*zone.SetZonePlanReplyCloudflare, error) {
  361. log.Printf("request Received: %+v", requestCloudflare)
  362. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  363. if err != nil {
  364. return nil, err
  365. }
  366. ctxAPI := context.Background()
  367. err = api.ZoneSetPlan(ctxAPI, requestCloudflare.GetZoneId(), requestCloudflare.GetZonePlan())
  368. if err != nil {
  369. return nil, err
  370. }
  371. return &zone.SetZonePlanReplyCloudflare{
  372. Success: true,
  373. }, nil
  374. }
  375. func (s *ZoneServer) ActivationCheck(ctx context.Context, requestCloudflare *zone.ActivationCheckRequestCloudflare) (*zone.ActivationCheckReplyCloudflare, error) {
  376. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  377. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  378. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  379. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  380. if err != nil {
  381. return nil, err
  382. }
  383. ctxAPI := context.Background()
  384. activationCheck, err := api.ZoneActivationCheck(ctxAPI, requestCloudflare.GetZoneId())
  385. if err != nil {
  386. return nil, err
  387. }
  388. return &zone.ActivationCheckReplyCloudflare{
  389. Success: activationCheck.Success,
  390. }, nil
  391. }
  392. var phaseMap = map[zone.Phase]string{
  393. zone.Phase_http_request_sanitize: "http_request_sanitize",
  394. zone.Phase_http_request_transform: "http_request_transform",
  395. //zone.Phase_http_request_origin: "http_request_origin",
  396. //zone.Phase_http_request_cache_settings: "http_request_cache_settings",
  397. //zone.Phase_http_config_settings: "http_config_settings",
  398. //zone.Phase_http_request_dynamic_redirect: "http_request_dynamic_redirect",
  399. //zone.Phase_ddos_l7: "ddos_l7",
  400. //zone.Phase_http_request_firewall_custom: "http_request_firewall_custom",
  401. //zone.Phase_http_ratelimit: "http_ratelimit",
  402. //zone.Phase_http_request_firewall_managed: "http_request_firewall_managed",
  403. //zone.Phase_http_request_sbfm: "http_request_sbfm",
  404. //zone.Phase_http_request_redirect: "http_request_redirect",
  405. zone.Phase_http_request_late_transform: "http_request_late_transform",
  406. //zone.Phase_http_custom_errors: "http_custom_errors",
  407. zone.Phase_http_response_headers_transform: "http_response_headers_transform",
  408. //zone.Phase_http_response_firewall_managed: "http_response_firewall_managed",
  409. //zone.Phase_http_log_custom_fields: "http_log_custom_fields",
  410. }
  411. func (s *ZoneServer) GetRuleSet(ctx context.Context, requestCloudflare *zone.GetRuleSetRequestCloudflare) (*zone.RuleList, error) {
  412. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  413. if err != nil {
  414. return nil, err
  415. }
  416. ctxAPI := context.Background()
  417. switch phaseMap[requestCloudflare.Phase] {
  418. case "http_request_transform", "http_request_late_transform", "http_response_headers_transform":
  419. default:
  420. return nil, errors.New("未定义规则阶段")
  421. }
  422. ruleset, err := api.GetZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phaseMap[requestCloudflare.Phase])
  423. if err != nil {
  424. _, ok := err.(*cloudflare.NotFoundError)
  425. if ok {
  426. ruleset.Rules = make([]cloudflare.RulesetRule, 0)
  427. err = nil
  428. } else {
  429. return nil, err
  430. }
  431. }
  432. filterMap := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  433. phase, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  434. if err != nil {
  435. return nil, false
  436. }
  437. return phase, true
  438. })
  439. return &zone.RuleList{Rules: filterMap}, nil
  440. }
  441. func (s *ZoneServer) UpdateRuleSet(ctx context.Context, requestCloudflare *zone.UpdateRuleSetRequestCloudflare) (*zone.RuleList, error) {
  442. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  443. if err != nil {
  444. return nil, err
  445. }
  446. ctxAPI := context.Background()
  447. phase := phaseMap[requestCloudflare.Phase]
  448. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  449. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  450. if err != nil || ruleResult == nil {
  451. return cloudflare.RulesetRule{}, false
  452. }
  453. return *ruleResult, true
  454. })
  455. //for _, rule := range requestCloudflare.Rules {
  456. // ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  457. // if err != nil {
  458. // return nil, err
  459. // }
  460. // if ruleResult != nil {
  461. // ruleSet.Rules = append(ruleSet.Rules, *ruleResult)
  462. // }
  463. //}
  464. ruleset, err := api.UpdateZoneRulesetPhase(ctxAPI, requestCloudflare.ZoneId, phase, cloudflare.Ruleset{
  465. Rules: filterMap,
  466. })
  467. if err != nil {
  468. return nil, err
  469. }
  470. rulesReturn := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  471. ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  472. if err != nil {
  473. return nil, false
  474. }
  475. return ruleReturn, true
  476. })
  477. //var rulesReturn []*zone.Rule
  478. //for _, rule := range rulesetResult.Rules {
  479. // ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, rulesetResult.Phase)
  480. // if err != nil {
  481. // return nil, err
  482. // }
  483. // if ruleReturn != nil {
  484. // rulesReturn = append(rulesReturn, ruleReturn)
  485. // }
  486. //}
  487. return &zone.RuleList{Rules: rulesReturn}, nil
  488. }
  489. //func UpdateRuleSet(apiKey, apiEmail, zoneID, rulesetPhase string, ruleset cloudflare.Ruleset) (*cloudflare.Ruleset, error) {
  490. // api, err := cloudflare.New(apiKey, apiEmail)
  491. // if err != nil {
  492. // return nil, err
  493. // }
  494. // ctxAPI := context.Background()
  495. // phase, err := api.UpdateZoneRulesetPhase(ctxAPI, zoneID, rulesetPhase, ruleset)
  496. // if err != nil {
  497. // return nil, err
  498. // }
  499. // return &phase, nil
  500. //}
  501. //PageRule CURD
  502. func (s *ZoneServer) ListPageRule(ctx context.Context, requestCloudflare *zone.ListPageRuleRequestCloudflare) (*zone.PageRuleList, error) {
  503. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  504. if err != nil {
  505. return nil, err
  506. }
  507. ctxAPI := context.Background()
  508. rules, err := api.ListPageRules(ctxAPI, requestCloudflare.GetZoneId())
  509. if err != nil {
  510. return nil, err
  511. }
  512. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  513. pageRule := Go2ProtoPageRule(&rule)
  514. return pageRule, true
  515. })
  516. return &zone.PageRuleList{PageRules: filterMap}, nil
  517. }
  518. func (s *ZoneServer) CreatePageRule(ctx context.Context, requestCloudflare *zone.CreatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  519. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  520. if err != nil {
  521. return nil, err
  522. }
  523. ctxAPI := context.Background()
  524. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  525. if err != nil {
  526. return nil, err
  527. }
  528. pageRule, err := api.CreatePageRule(ctxAPI, requestCloudflare.GetZoneId(), *rule)
  529. if err != nil {
  530. return nil, err
  531. }
  532. return Go2ProtoPageRule(pageRule), nil
  533. }
  534. func (s *ZoneServer) UpdatePageRule(ctx context.Context, requestCloudflare *zone.UpdatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  535. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  536. if err != nil {
  537. return nil, err
  538. }
  539. ctxAPI := context.Background()
  540. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  541. if err != nil {
  542. return nil, err
  543. }
  544. err = api.UpdatePageRule(ctxAPI, requestCloudflare.GetZoneId(), rule.ID, *rule)
  545. if err != nil {
  546. return nil, err
  547. }
  548. return requestCloudflare.PageRule, nil
  549. }
  550. func (s *ZoneServer) DeletePageRule(ctx context.Context, requestCloudflare *zone.DeletePageRuleRequestCloudflare) (*zone.PageRule, error) {
  551. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  552. if err != nil {
  553. return nil, err
  554. }
  555. ctxAPI := context.Background()
  556. err = api.DeletePageRule(ctxAPI, requestCloudflare.ZoneId, requestCloudflare.PageRuleId)
  557. if err != nil {
  558. return nil, err
  559. }
  560. return &zone.PageRule{}, nil
  561. }
  562. //func UpdatePageRule(apiKey, apiEmail, zoneID string, rule *zone.PageRule) (*zone.PageRule, error) {
  563. // api, err := cloudflare.New(apiKey, apiEmail)
  564. // if err != nil {
  565. // return nil, err
  566. // }
  567. //
  568. // ctxAPI := context.Background()
  569. // goPageRule, err := Proto2GoPageRule(rule)
  570. // if err != nil {
  571. // return nil, err
  572. // }
  573. // pageRule, err := api.CreatePageRule(ctxAPI, zoneID, *goPageRule)
  574. // if err != nil {
  575. // return nil, err
  576. // }
  577. //
  578. // protoPageRule := Go2ProtoPageRule(pageRule)
  579. //
  580. // return protoPageRule, nil
  581. //}
  582. type PageRuleActionCacheKeyFieldsQueryString struct {
  583. Exclude interface{} `json:"exclude"`
  584. Include interface{} `json:"include"`
  585. }
  586. type PageRuleActionCacheKeyFields struct {
  587. QueryString PageRuleActionCacheKeyFieldsQueryString `json:"query_string"`
  588. }
  589. type UpdatePageRulesPrioritiesStruct struct {
  590. Id string `json:"id"`
  591. Priority int `json:"priority"`
  592. }
  593. func (s *ZoneServer) UpdatePageRulesPriorities(ctx context.Context, requestCloudflare *zone.UpdatePageRulesPrioritiesRequestCloudflare) (*zone.PageRuleList, error) {
  594. //TODO 参数检查
  595. //设置HTTP请求
  596. client := &http.Client{}
  597. bytesData, err := json.Marshal(requestCloudflare.Data)
  598. if err != nil {
  599. return nil, err
  600. }
  601. req, err := http.NewRequest("PUT", "https://api.cloudflare.com/client/v4/zones/"+requestCloudflare.ZoneId+"/pagerules/priorities", bytes.NewReader(bytesData))
  602. if err != nil {
  603. return nil, err
  604. }
  605. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  606. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  607. //执行HTTP请求
  608. resp, err := client.Do(req)
  609. if err != nil {
  610. return nil, err
  611. }
  612. defer func(Body io.ReadCloser) {
  613. _ = Body.Close()
  614. }(resp.Body)
  615. body, _ := ioutil.ReadAll(resp.Body)
  616. //解析HTTP返回数据
  617. var r cloudflare.PageRulesResponse
  618. err = json.Unmarshal(body, &r)
  619. //处理返回逻辑
  620. if err != nil {
  621. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  622. }
  623. if r.Success != true {
  624. return nil, fmt.Errorf("%s", r.Errors)
  625. }
  626. rules := r.Result
  627. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  628. pageRule := Go2ProtoPageRule(&rule)
  629. return pageRule, true
  630. })
  631. return &zone.PageRuleList{PageRules: filterMap}, nil
  632. }
  633. // 默认开启Smarttiered cache
  634. func (s *ZoneServer) SetSmartTieredCache(ctx context.Context, requestCloudflare *zone.SetSmartTieredCacheRequestCloudflare) (*zone.SetSmartTieredCacheReplyCloudflare, error) {
  635. log.Printf("apiKey Received: %v", requestCloudflare.GetApiKey())
  636. log.Printf("apiEmail Received: %v", requestCloudflare.GetApiEmail())
  637. log.Printf("zoneId Received: %v", requestCloudflare.GetZoneId())
  638. type ResponseType struct {
  639. Errors []interface{} `json:"errors"`
  640. Messages []interface{} `json:"messages"`
  641. Result interface{} `json:"result"`
  642. Success bool `json:"success"`
  643. }
  644. //设置HTTP请求
  645. client := &http.Client{}
  646. url := "https://api.cloudflare.com/client/v4/zones/" + requestCloudflare.ZoneId + "/cache/tiered_cache_smart_topology_enable"
  647. payload := strings.NewReader("{\n \"value\": \"on\"\n}")
  648. req, err := http.NewRequest("PATCH", url, payload)
  649. if err != nil {
  650. return nil, err
  651. }
  652. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  653. req.Header.Add("Content-Type", "application/json")
  654. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  655. //执行HTTP请求
  656. resp, err := client.Do(req)
  657. if err != nil {
  658. return nil, err
  659. }
  660. defer func(Body io.ReadCloser) {
  661. _ = Body.Close()
  662. }(resp.Body)
  663. body, _ := ioutil.ReadAll(resp.Body)
  664. print(body)
  665. //解析HTTP返回数据
  666. var r ResponseType
  667. err = json.Unmarshal(body, &r)
  668. if err != nil {
  669. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  670. }
  671. if r.Success != true {
  672. print(fmt.Errorf("%s", r.Errors))
  673. }
  674. return &zone.SetSmartTieredCacheReplyCloudflare{Enabled: r.Success}, nil
  675. }