forked from DavidKrau/terraform-provider-simplemdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapps_data_source.go
More file actions
274 lines (240 loc) · 8.63 KB
/
apps_data_source.go
File metadata and controls
274 lines (240 loc) · 8.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package provider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/DavidKrau/simplemdm-go-client"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ datasource.DataSource = &appsDataSource{}
_ datasource.DataSourceWithConfigure = &appsDataSource{}
)
type appsDataSource struct {
client *simplemdm.Client
}
type appsDataSourceModel struct {
IncludeShared types.Bool `tfsdk:"include_shared"`
Apps []appsDataSourceAppModel `tfsdk:"apps"`
}
type appsDataSourceAppModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
AppStoreID types.String `tfsdk:"app_store_id"`
BundleID types.String `tfsdk:"bundle_id"`
AppType types.String `tfsdk:"app_type"`
Version types.String `tfsdk:"version"`
PlatformSupport types.String `tfsdk:"platform_support"`
ProcessingStatus types.String `tfsdk:"processing_status"`
InstallationChannels types.List `tfsdk:"installation_channels"`
CreatedAt types.String `tfsdk:"created_at"`
UpdatedAt types.String `tfsdk:"updated_at"`
}
func AppsDataSource() datasource.DataSource {
return &appsDataSource{}
}
func (d *appsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_apps"
}
func (d *appsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Fetches the collection of apps from your SimpleMDM account, with optional filtering by shared catalog.",
Attributes: map[string]schema.Attribute{
"include_shared": schema.BoolAttribute{
Optional: true,
Description: "Include apps from the SimpleMDM shared catalog. When set to true, the data source will query apps available in the shared catalog in addition to account-specific apps. Defaults to false.",
},
},
Blocks: map[string]schema.Block{
"apps": schema.ListNestedBlock{
Description: "Collection of app records returned by the API.",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
Description: "App identifier.",
},
"name": schema.StringAttribute{
Computed: true,
Description: "Name of the app.",
},
"app_store_id": schema.StringAttribute{
Computed: true,
Description: "The Apple App Store ID associated with the app.",
},
"bundle_id": schema.StringAttribute{
Computed: true,
Description: "The bundle identifier of the app.",
},
"app_type": schema.StringAttribute{
Computed: true,
Description: "The catalog classification of the app (e.g., app store, enterprise, custom b2b).",
},
"version": schema.StringAttribute{
Computed: true,
Description: "The latest version reported by SimpleMDM for the app.",
},
"platform_support": schema.StringAttribute{
Computed: true,
Description: "The platform supported by the app (iOS, macOS, etc.).",
},
"processing_status": schema.StringAttribute{
Computed: true,
Description: "The current processing status of the app binary within SimpleMDM.",
},
"installation_channels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
Description: "The deployment channels supported by the app.",
},
"created_at": schema.StringAttribute{
Computed: true,
Description: "Timestamp when the app was added to SimpleMDM.",
},
"updated_at": schema.StringAttribute{
Computed: true,
Description: "Timestamp when the app was last updated in SimpleMDM.",
},
},
},
},
},
}
}
func (d *appsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var config appsDataSourceModel
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
apps, err := fetchAllApps(ctx, d.client, config.IncludeShared)
if err != nil {
resp.Diagnostics.AddError(
"Unable to list SimpleMDM apps",
err.Error(),
)
return
}
entries := make([]appsDataSourceAppModel, 0, len(apps))
for _, app := range apps {
installationChannels, diags := types.ListValueFrom(ctx, types.StringType, app.Attributes.InstallationChannels)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
entry := appsDataSourceAppModel{
ID: types.StringValue(strconv.Itoa(app.ID)),
Name: types.StringValue(app.Attributes.Name),
AppStoreID: intToStringValue(app.Attributes.AppStoreID),
BundleID: stringValueOrNull(app.Attributes.BundleIdentifier),
AppType: stringValueOrNull(app.Attributes.AppType),
Version: stringValueOrNull(app.Attributes.Version),
PlatformSupport: stringValueOrNull(app.Attributes.PlatformSupport),
ProcessingStatus: stringValueOrNull(app.Attributes.ProcessingStatus),
InstallationChannels: installationChannels,
CreatedAt: stringValueOrNull(app.Attributes.CreatedAt),
UpdatedAt: stringValueOrNull(app.Attributes.UpdatedAt),
}
entries = append(entries, entry)
}
config.Apps = entries
diags = resp.State.Set(ctx, &config)
resp.Diagnostics.Append(diags...)
}
func (d *appsDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*simplemdm.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Data Source Configure Type",
fmt.Sprintf("Expected *Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
d.client = client
}
// fetchAllApps retrieves all apps with pagination support
func fetchAllApps(ctx context.Context, client *simplemdm.Client, includeShared types.Bool) ([]appData, error) {
var allApps []appData
startingAfter := 0
limit := 100
iterations := 0
const maxPaginationIterations = 1000 // Safety limit to prevent infinite loops
for {
// Safety check to prevent infinite loops
if iterations >= maxPaginationIterations {
return nil, fmt.Errorf("exceeded maximum pagination iterations (%d), possibly too many apps or API error", maxPaginationIterations)
}
iterations++
// Check context cancellation
if err := ctx.Err(); err != nil {
return nil, err
}
url := fmt.Sprintf("https://%s/api/v1/apps?limit=%d", client.HostName, limit)
if startingAfter > 0 {
url += fmt.Sprintf("&starting_after=%d", startingAfter)
}
if !includeShared.IsNull() && includeShared.ValueBool() {
url += "&include_shared=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
body, err := client.RequestResponse200(req)
if err != nil {
return nil, err
}
var response appsAPIResponse
if err := json.Unmarshal(body, &response); err != nil {
return nil, err
}
allApps = append(allApps, response.Data...)
if !response.HasMore {
break
}
if len(response.Data) > 0 {
startingAfter = response.Data[len(response.Data)-1].ID
} else {
break
}
}
return allApps, nil
}
// appsAPIResponse represents the paginated API response for apps list
type appsAPIResponse struct {
Data []appData `json:"data"`
HasMore bool `json:"has_more"`
}
// appData represents a single app in the list response
type appData struct {
ID int `json:"id"`
Type string `json:"type"`
Attributes appAttributes `json:"attributes"`
}
type appAttributes struct {
Name string `json:"name"`
AppStoreID int `json:"itunes_store_id"`
BundleIdentifier string `json:"bundle_identifier"`
AppType string `json:"app_type"`
Version string `json:"version"`
PlatformSupport string `json:"platform_support"`
ProcessingStatus string `json:"processing_status"`
InstallationChannels []string `json:"installation_channels"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// Helper function to convert int to string value or null
func intToStringValue(val int) types.String {
if val == 0 {
return types.StringNull()
}
return types.StringValue(strconv.Itoa(val))
}