@@ -38,6 +38,7 @@ const (
38
38
)
39
39
40
40
var ErrAlreadyInProgress = fmt .Errorf ("already in progress" )
41
+ var ErrAlreadyCancelled = fmt .Errorf ("already cancelled" )
41
42
42
43
type OtaApiClient struct {
43
44
client * http.Client
@@ -58,7 +59,11 @@ func NewClient(credentials *config.Credentials) *OtaApiClient {
58
59
}
59
60
60
61
func (c * OtaApiClient ) performGetRequest (endpoint , token string ) (* http.Response , error ) {
61
- req , err := http .NewRequest ("GET" , endpoint , nil )
62
+ return c .performRequest (endpoint , "GET" , token )
63
+ }
64
+
65
+ func (c * OtaApiClient ) performRequest (endpoint , method , token string ) (* http.Response , error ) {
66
+ req , err := http .NewRequest (method , endpoint , nil )
62
67
if err != nil {
63
68
return nil , err
64
69
}
@@ -205,3 +210,35 @@ func (c *OtaApiClient) GetOtaStatusByDeviceID(deviceID string, limit int, order
205
210
206
211
return nil , err
207
212
}
213
+
214
+ func (c * OtaApiClient ) CancelOta (otaid string ) (bool , error ) {
215
+
216
+ if otaid == "" {
217
+ return false , fmt .Errorf ("invalid ota-id: empty" )
218
+ }
219
+
220
+ userRequestToken , err := c .src .Token ()
221
+ if err != nil {
222
+ if strings .Contains (err .Error (), "401" ) {
223
+ return false , errors .New ("wrong credentials" )
224
+ }
225
+ return false , fmt .Errorf ("cannot retrieve a valid token: %w" , err )
226
+ }
227
+
228
+ endpoint := c .host + "/ota/v1/ota/" + otaid + "/cancel"
229
+ res , err := c .performRequest (endpoint , "PUT" , userRequestToken .AccessToken )
230
+ if err != nil {
231
+ return false , err
232
+ }
233
+ defer res .Body .Close ()
234
+
235
+ if res .StatusCode == 200 {
236
+ return true , nil
237
+ } else if res .StatusCode == 404 || res .StatusCode == 400 {
238
+ return false , fmt .Errorf ("ota-id %s not found" , otaid )
239
+ } else if res .StatusCode == 409 {
240
+ return false , ErrAlreadyCancelled
241
+ }
242
+
243
+ return false , err
244
+ }
0 commit comments