Compare commits

...

9 Commits
v0.0.2 ... main

9 changed files with 172 additions and 74 deletions

7
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": []
}

View File

@ -8,9 +8,14 @@ import (
)
func (api *Api) GetApInfo(siteID model.SiteID, macAddress string) (*model.ApInfo, error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
resp, err := api.getApInfo(siteID, macAddress)
if err != nil {
return nil, err
}
return &resp.Result, nil
}
func (api *Api) getApInfo(siteID model.SiteID, macAddress string) (*model.Response[model.ApInfo], error) {
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("GET"),
@ -21,16 +26,18 @@ func (api *Api) GetApInfo(siteID model.SiteID, macAddress string) (*model.ApInfo
macAddress)),
)
resp, err := ezhttp.Do(req)
resp, err := api.doRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.Response[model.ApInfo]](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.Response[model.ApInfo]](resp)
if err != nil {
return nil, err
}
return &response.Result, nil
return handleResponseErrors(api, response, func() (*model.Response[model.ApInfo], error) {
return api.getApInfo(siteID, macAddress)
})
}

82
api.go
View File

@ -1,7 +1,6 @@
package omadaapi
import (
"context"
"fmt"
"net/http"
"sync"
@ -40,49 +39,61 @@ func NewApi(config ApiConfig) (*Api, error) {
config: config,
}
if err := api.InitSession(); err != nil {
return nil, err
}
return api, nil
}
func (api *Api) InitSession() error {
api.refreshMutex.Lock()
defer api.refreshMutex.Unlock()
return api.initSessionNoMutexLock()
}
func (api *Api) initSessionNoMutexLock() error {
loginResponse, err := api.Login()
if err != nil {
return nil, fmt.Errorf("login request failed: %w", err)
return fmt.Errorf("login request failed: %w", err)
}
if loginResponse.ErrorCode != 0 {
return nil, fmt.Errorf("login request failed: %s", loginResponse.Message)
return fmt.Errorf("login request failed: %s", loginResponse.Message)
}
authCodeResponse, err := api.AuthCode(loginResponse.Result.CsrfToken, loginResponse.Result.SessionID)
if err != nil {
return nil, fmt.Errorf("auth code request failed: %w", err)
return fmt.Errorf("auth code request failed: %w", err)
}
if authCodeResponse.ErrorCode != 0 {
return nil, fmt.Errorf("auth code request failed: %s", authCodeResponse.Message)
return fmt.Errorf("auth code request failed: %s", authCodeResponse.Message)
}
authTokenResponse, err := api.AuthToken(*authCodeResponse.Result)
if err != nil {
return nil, fmt.Errorf("auth token request failed: %w", err)
return fmt.Errorf("auth token request failed: %w", err)
}
if authTokenResponse.ErrorCode != 0 {
return nil, fmt.Errorf("auth token request failed: %s", authTokenResponse.Message)
return fmt.Errorf("auth token request failed: %s", authTokenResponse.Message)
}
api.expiration = time.Now().Add(time.Duration(authTokenResponse.Result.ExpiresIn-1) * time.Second)
api.expiration = time.Now().Add(time.Duration(authTokenResponse.Result.ExpiresIn) * time.Second)
api.accessToken = authTokenResponse.Result.AccessToken
api.refreshToken = authTokenResponse.Result.RefreshToken
api.tmpl = ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Headers("Authorization", "AccessToken="+api.accessToken),
ezhttp.RemoveAllHeaders(),
ezhttp.Auth(api.getAuthHeader),
)
return api, nil
return nil
}
func (api *Api) Login() (*model.LoginResponse, error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
reqBody := model.LoginRequest{
Username: api.config.Username,
Password: api.config.Password,
@ -102,7 +113,7 @@ func (api *Api) Login() (*model.LoginResponse, error) {
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.LoginResponse](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.LoginResponse](resp)
if err != nil {
return nil, err
}
@ -111,9 +122,6 @@ func (api *Api) Login() (*model.LoginResponse, error) {
}
func (api *Api) AuthCode(csrfToken, sessionID string) (*model.AuthCodeResponse, error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("POST"),
@ -128,7 +136,7 @@ func (api *Api) AuthCode(csrfToken, sessionID string) (*model.AuthCodeResponse,
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.AuthCodeResponse](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.AuthCodeResponse](resp)
if err != nil {
return nil, err
}
@ -137,9 +145,6 @@ func (api *Api) AuthCode(csrfToken, sessionID string) (*model.AuthCodeResponse,
}
func (api *Api) AuthToken(authCode string) (*model.AuthTokenResponse, error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("POST"),
@ -158,7 +163,7 @@ func (api *Api) AuthToken(authCode string) (*model.AuthTokenResponse, error) {
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.AuthTokenResponse](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.AuthTokenResponse](resp)
if err != nil {
return nil, err
}
@ -166,21 +171,7 @@ func (api *Api) AuthToken(authCode string) (*model.AuthTokenResponse, error) {
return response, nil
}
func (api *Api) AutoRefresh(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
case <-time.After(time.Until(api.expiration)):
if err := api.Refresh(); err != nil {
return err
}
}
}
}
func (api *Api) Refresh() error {
fmt.Println("refresh")
api.refreshMutex.Lock()
defer api.refreshMutex.Unlock()
@ -202,15 +193,28 @@ func (api *Api) Refresh() error {
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.AuthTokenResponse](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.AuthTokenResponse](resp)
if err != nil {
return err
}
api.expiration = time.Now().Add(time.Duration(response.Result.ExpiresIn-1) * time.Second)
if response.ErrorCode == ErrCodeRefreshTokenExpired {
return api.initSessionNoMutexLock()
}
api.expiration = time.Now().Add(time.Duration(response.Result.ExpiresIn) * time.Second)
api.accessToken = response.Result.AccessToken
api.refreshToken = response.Result.RefreshToken
fmt.Println("refresh successful")
return nil
}
func (api *Api) doRequest(r *http.Request) (*http.Response, error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
return ezhttp.Do(r)
}
func (api *Api) getAuthHeader() string {
return "AccessToken=" + api.accessToken
}

View File

@ -4,12 +4,13 @@ import (
"fmt"
"strconv"
"git.tordarus.net/tordarus/channel"
"git.tordarus.net/tordarus/ezhttp"
"git.tordarus.net/tordarus/omada-api/model"
)
func (api *Api) GetClients(siteID model.SiteID) <-chan *model.Client {
out := make(chan *model.Client, 1000)
func (api *Api) GetClients(siteID model.SiteID) <-chan channel.Result[model.Client] {
out := make(chan channel.Result[model.Client], 1000)
go func() {
defer close(out)
@ -17,11 +18,12 @@ func (api *Api) GetClients(siteID model.SiteID) <-chan *model.Client {
for page := 1; ; page++ {
resp, err := api.getClients(page, siteID)
if err != nil {
out <- channel.ResultOf[model.Client](nil, err)
return
}
for _, v := range resp.Result.Data {
out <- &v
out <- channel.ResultOfValue(v, nil)
}
if resp.Result.CurrentPage*resp.Result.CurrentSize >= resp.Result.TotalRows {
@ -34,9 +36,6 @@ func (api *Api) GetClients(siteID model.SiteID) <-chan *model.Client {
}
func (api *Api) getClients(page int, siteID model.SiteID) (*model.PagedResponse[model.Client], error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("GET"),
@ -47,16 +46,18 @@ func (api *Api) getClients(page int, siteID model.SiteID) (*model.PagedResponse[
),
)
resp, err := ezhttp.Do(req)
resp, err := api.doRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Client]](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Client]](resp)
if err != nil {
return nil, err
}
return response, nil
return handlePagedResponseErrors(api, response, func() (*model.PagedResponse[model.Client], error) {
return api.getClients(page, siteID)
})
}

View File

@ -4,12 +4,13 @@ import (
"fmt"
"strconv"
"git.tordarus.net/tordarus/channel"
"git.tordarus.net/tordarus/ezhttp"
"git.tordarus.net/tordarus/omada-api/model"
)
func (api *Api) GetDevices(siteID model.SiteID) <-chan *model.Device {
out := make(chan *model.Device, 1000)
func (api *Api) GetDevices(siteID model.SiteID) <-chan channel.Result[model.Device] {
out := make(chan channel.Result[model.Device], 1000)
go func() {
defer close(out)
@ -17,11 +18,12 @@ func (api *Api) GetDevices(siteID model.SiteID) <-chan *model.Device {
for page := 1; ; page++ {
resp, err := api.getDevices(page, siteID)
if err != nil {
out <- channel.ResultOf[model.Device](nil, err)
return
}
for _, v := range resp.Result.Data {
out <- &v
out <- channel.ResultOfValue(v, nil)
}
if resp.Result.CurrentPage*resp.Result.CurrentSize >= resp.Result.TotalRows {
@ -34,9 +36,6 @@ func (api *Api) GetDevices(siteID model.SiteID) <-chan *model.Device {
}
func (api *Api) getDevices(page int, siteID model.SiteID) (*model.PagedResponse[model.Device], error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("GET"),
@ -47,16 +46,18 @@ func (api *Api) getDevices(page int, siteID model.SiteID) (*model.PagedResponse[
),
)
resp, err := ezhttp.Do(req)
resp, err := api.doRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Device]](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Device]](resp)
if err != nil {
return nil, err
}
return response, nil
return handlePagedResponseErrors(api, response, func() (*model.PagedResponse[model.Device], error) {
return api.getDevices(page, siteID)
})
}

5
go.mod
View File

@ -2,4 +2,7 @@ module git.tordarus.net/tordarus/omada-api
go 1.23.0
require git.tordarus.net/tordarus/ezhttp v0.0.3
require (
git.tordarus.net/tordarus/channel v0.1.19
git.tordarus.net/tordarus/ezhttp v0.0.9
)

6
go.sum
View File

@ -1,2 +1,4 @@
git.tordarus.net/tordarus/ezhttp v0.0.3 h1:K6IlLmqkAFUF68HJsOTKcP3ejco7qfm+MuEagohoouo=
git.tordarus.net/tordarus/ezhttp v0.0.3/go.mod h1:Zq9o0Hibny61GqSCwJHa0PfGjVoUFv/zt2PjiQHXvmY=
git.tordarus.net/tordarus/channel v0.1.19 h1:d9xnSwFyvBh4B1/82mt0A7Gpm2nIZJTc+9ceJMIOu5Q=
git.tordarus.net/tordarus/channel v0.1.19/go.mod h1:8/dWFTdGO7g4AeSZ7cF6GerkGbe9c4dBVMVDBxOd9m4=
git.tordarus.net/tordarus/ezhttp v0.0.9 h1:YwdQ4YcJwvpMw5CX5NcCEM23XQL+WCz5nWuc2dzX/84=
git.tordarus.net/tordarus/ezhttp v0.0.9/go.mod h1:Zq9o0Hibny61GqSCwJHa0PfGjVoUFv/zt2PjiQHXvmY=

19
site.go
View File

@ -4,12 +4,13 @@ import (
"fmt"
"strconv"
"git.tordarus.net/tordarus/channel"
"git.tordarus.net/tordarus/ezhttp"
"git.tordarus.net/tordarus/omada-api/model"
)
func (api *Api) GetSites() <-chan *model.Site {
out := make(chan *model.Site, 1000)
func (api *Api) GetSites() <-chan channel.Result[model.Site] {
out := make(chan channel.Result[model.Site], 1000)
go func() {
defer close(out)
@ -17,11 +18,12 @@ func (api *Api) GetSites() <-chan *model.Site {
for page := 1; ; page++ {
resp, err := api.getSites(page)
if err != nil {
out <- channel.ResultOf[model.Site](nil, err)
return
}
for _, v := range resp.Result.Data {
out <- &v
out <- channel.ResultOfValue(v, nil)
}
if resp.Result.CurrentPage*resp.Result.CurrentSize >= resp.Result.TotalRows {
@ -34,9 +36,6 @@ func (api *Api) GetSites() <-chan *model.Site {
}
func (api *Api) getSites(page int) (*model.PagedResponse[model.Site], error) {
api.refreshMutex.RLock()
defer api.refreshMutex.RUnlock()
req := ezhttp.Request(
ezhttp.Template(api.tmpl),
ezhttp.Method("GET"),
@ -47,16 +46,18 @@ func (api *Api) getSites(page int) (*model.PagedResponse[model.Site], error) {
),
)
resp, err := ezhttp.Do(req)
resp, err := api.doRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Site]](resp.Body)
response, err := ezhttp.ParseJsonResponse[model.PagedResponse[model.Site]](resp)
if err != nil {
return nil, err
}
return response, nil
return handlePagedResponseErrors(api, response, func() (*model.PagedResponse[model.Site], error) {
return api.getSites(page)
})
}

72
utils.go Normal file
View File

@ -0,0 +1,72 @@
package omadaapi
import (
"fmt"
"git.tordarus.net/tordarus/omada-api/model"
)
const ErrCodeAccessTokenExpired = -44112
const ErrCodeRefreshTokenExpired = -44114
func handleResponseErrors[T any](api *Api, response *model.Response[T], retry func() (*model.Response[T], error)) (*model.Response[T], error) {
switch response.ErrorCode {
case 0:
return response, nil
case ErrCodeAccessTokenExpired:
if err := api.Refresh(); err != nil {
return nil, fmt.Errorf("could not refresh access token: %w", err)
}
newResp, err := retry()
if err != nil {
return nil, err
}
return handleResponseErrors(api, newResp, retry)
case ErrCodeRefreshTokenExpired:
if err := api.InitSession(); err != nil {
return nil, fmt.Errorf("could not initialize new session: %w", err)
}
newResp, err := retry()
if err != nil {
return nil, err
}
return handleResponseErrors(api, newResp, retry)
default:
return nil, fmt.Errorf("invalid error code %d with message: %s", response.ErrorCode, response.Message)
}
}
func handlePagedResponseErrors[T any](api *Api, response *model.PagedResponse[T], retry func() (*model.PagedResponse[T], error)) (*model.PagedResponse[T], error) {
switch response.ErrorCode {
case 0:
return response, nil
case ErrCodeAccessTokenExpired:
if err := api.Refresh(); err != nil {
return nil, fmt.Errorf("could not refresh access token: %w", err)
}
newResp, err := retry()
if err != nil {
return nil, err
}
return handlePagedResponseErrors(api, newResp, retry)
case ErrCodeRefreshTokenExpired:
if err := api.InitSession(); err != nil {
return nil, fmt.Errorf("could not initialize new session: %w", err)
}
newResp, err := retry()
if err != nil {
return nil, err
}
return handlePagedResponseErrors(api, newResp, retry)
default:
return nil, fmt.Errorf("invalid error code %d with message: %s", response.ErrorCode, response.Message)
}
}