Debian Codegraph @

manager_builder.go

raw
1 package proton
2
3 import (
4 "net/http"
5 "time"
6
7 "github.com/ProtonMail/gluon/async"
8 "github.com/go-resty/resty/v2"
9 )
10
11 const (
12 // DefaultHostURL is the default host of the API.
13 DefaultHostURL = "https://mail.proton.me/api"
14
15 // DefaultAppVersion is the default app version used to communicate with the API.
16 // This must be changed (using the WithAppVersion option) for production use.
17 DefaultAppVersion = "go-proton-api"
18
19 // DefaultUserAgent is the default user agent used to communicate with the API.
20 // See: https://github.com/emersion/hydroxide/issues/252
21 DefaultUserAgent = ""
22 )
23
24 type managerBuilder struct {
25 hostURL string
26 appVersion string
27 userAgent string
28 transport http.RoundTripper
29 verifyProofs bool
30 cookieJar http.CookieJar
31 retryCount int
32 logger resty.Logger
33 debug bool
34 panicHandler async.PanicHandler
35 }
36
37 func newManagerBuilder() *managerBuilder {
38 return &managerBuilder{
39 hostURL: DefaultHostURL,
40 appVersion: DefaultAppVersion,
41 userAgent: DefaultUserAgent,
42 transport: http.DefaultTransport,
43 verifyProofs: true,
44 cookieJar: nil,
45 retryCount: 3,
46 logger: nil,
47 debug: false,
48 panicHandler: async.NoopPanicHandler{},
49 }
50 }
51
52 func (builder *managerBuilder) build() *Manager {
53 m := &Manager{
54 rc: resty.New(),
55
56 errHandlers: make(map[Code][]Handler),
57
58 verifyProofs: builder.verifyProofs,
59
60 panicHandler: builder.panicHandler,
61 }
62
63 // Set the API host.
64 m.rc.SetBaseURL(builder.hostURL)
65
66 // Set the transport.
67 m.rc.SetTransport(builder.transport)
68
69 // Set the cookie jar.
70 m.rc.SetCookieJar(builder.cookieJar)
71
72 // Set the logger.
73 if builder.logger != nil {
74 m.rc.SetLogger(builder.logger)
75 }
76
77 // Set the debug flag.
78 m.rc.SetDebug(builder.debug)
79
80 // Set app version in header.
81 m.rc.OnBeforeRequest(func(_ *resty.Client, req *resty.Request) error {
82 req.SetHeader("x-pm-appversion", builder.appVersion)
83 req.SetHeader("User-Agent", builder.userAgent)
84 return nil
85 })
86
87 // Set middleware.
88 m.rc.OnAfterResponse(catchAPIError)
89 m.rc.OnAfterResponse(updateTime)
90 m.rc.OnAfterResponse(m.checkConnUp)
91 m.rc.OnError(m.checkConnDown)
92 m.rc.OnError(m.handleError)
93
94 // Configure retry mechanism.
95 m.rc.SetRetryCount(builder.retryCount)
96 m.rc.SetRetryMaxWaitTime(time.Minute)
97 m.rc.AddRetryCondition(catchTooManyRequests)
98 m.rc.AddRetryCondition(catchDialError)
99 m.rc.AddRetryCondition(catchDropError)
100 m.rc.SetRetryAfter(catchRetryAfter)
101
102 // Set the data type of API errors.
103 m.rc.SetError(&APIError{})
104
105 return m
106 }