-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersons.ps1
344 lines (295 loc) · 12.2 KB
/
persons.ps1
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
Write-Information "Processing Persons"
#region Configuration
$config = ConvertFrom-Json $configuration
#endregion Configuration
#region Support Functions
function Get-AuthToken {
[cmdletbinding()]
Param (
[string]$BaseUri,
[string]$TokenUri,
[string]$ClientKey,
[string]$ClientSecret,
[string]$PageSize
)
Process
{
$requestUri = $TokenURI
$pair = "{0}:{1}" -f $ClientKey,$ClientSecret
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$bear_token = [System.Convert]::ToBase64String($bytes)
$headers = @{
Authorization = "Basic {0}" -f $bear_token
Accept = "application/json"
}
$parameters = @{
grant_type="client_credentials"
scope='http://purl.imsglobal.org/spec/or/v1p2/scope/roster.readonly http://purl.imsglobal.org/spec/or/v1p2/scope/roster-demographics.readonly http://purl.imsglobal.org/spec/or/v1p2/scope/resource.readonly https://purl.imsglobal.org/spec/or/v1p2/scope/gradebook.readonly https://purl.imsglobal.org/spec/or/v1p2/scope/gradebook-core.readonly https://purl.imsglobal.org/spec/or/v1p2/scope/gradebook.createput'
}
Write-Information ("POST {0}" -f $requestUri)
$splat = @{
Method = 'Post'
URI = $requestUri
Body = $parameters
Headers = $headers
Verbose = $false
}
$response = Invoke-RestMethod @splat
#Write-Information $response
$accessToken = $response.access_token
#Add the authorization header to the request
$authorization = @{
Authorization = "Bearer {0}" -f $accesstoken
'Content-Type' = "application/json"
Accept = "application/json"
}
$authorization
}
}
function Get-Data {
[cmdletbinding()]
Param (
[string]$BaseUri,
[string]$TokenUri,
[string]$ClientKey,
[string]$ClientSecret,
[string]$PageSize,
[string]$EndpointUri,
[string]$PropertyName,
[string]$Filter,
[object]$Authorization
)
Begin
{
$offset = 0
$requestUri = "{0}{1}" -f $BaseURI,$EndPointUri
$propertyArray = $PropertyName
$results = [System.Collections.Generic.List[object]]::new()
}
Process
{
do
{
$parameters = [ordered]@{}
if($filter -ne $null -and $filter.Length -gt 0)
{
$parameters['filter'] = $filter
}
$parameters['limit'] =$Pagesize
$parameters['offset'] = $offset
Write-Information ("GET {0} ({1})" -f $requestUri, $offset)
$splat = @{
Method = 'GET'
Uri = $requestUri
Body = $parameters
Headers = $Authorization
Verbose = $false
}
try {
$response = Invoke-RestMethod @splat
}
catch {
if($_.Exception.Response.StatusCode.value__ -eq 401)
{
throw "Client is unauthorized"
}
elseif($_.Exception.Response.StatusCode.value__ -eq 404)
{
throw "Endpoint is not found (404) - $($requestUri)"
}
else
{
Write-Warning (" Retrying RestMethod. Error: {0}" -f $_)
Start-Sleep -seconds 5
$response = Invoke-RestMethod @splat
}
}
if($response.$propertyArray.getType().BaseType -eq [System.Array])
{
$results.AddRange($response.$propertyArray)
}
else
{
$results.Add($response.$propertyArray)
}
$offset = $offset + $response.$propertyArray.count
} while ($response.$propertyArray.count -eq $PageSize)
}
End
{
return $results
}
}
function Group-ObjectHashtable
{
param(
[string[]] $Property
)
begin
{ # create an empty hashtable
$hashtable = @{}
}
process
{ # create a key based on the submitted properties, and turn it into a string
$key = $(foreach($prop in $Property) { $_.$prop }) -join ','
# check to see if the key is present already
if ($hashtable.ContainsKey($key) -eq $false)
{ # add an empty list
$hashtable[$key] = [Collections.Generic.List[psobject]]::new()
}
# add element to appropriate array list:
$hashtable[$key].Add($_)
}
end
{ # return the entire hashtable:
$hashtable
}
}
#endregion Support Functions
#region Get Data
$splat = @{
BaseURI = $config.BaseURI
TokenUri = $config.TokenUri
ClientKey = $config.ClientKey
ClientSecret = $config.ClientSecret
PageSize = $config.PageSize
}
try {
$splat['Authorization'] = Get-AuthToken @splat
} catch {
throw "Authorization Failed - $($_)"
}
try {
$orgs = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/orgs" -PropertyName "orgs" -Filter $config.OrgFilter
$orgs_ht = $orgs | Group-ObjectHashtable 'sourcedId'
$orgs_empty = @{}
$orgs[0].PSObject.Properties.ForEach({$orgs_empty[$_.name -Replace '\W','_'] = ''})
$academicSessions = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/academicSessions" -PropertyName "academicSessions"
$academicSessions_ht= $academicSessions | Group-ObjectHashtable 'sourcedId'
$enrollments = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/enrollments" -PropertyName "enrollments" -Filter $config.EnrollmentFilter
$enrollments_ht = $enrollments | Group-Object -Property @{e={$_.user.sourcedID}} -AsString -AsHashTable
$classes = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/classes" -PropertyName "classes" -Filter $config.ClassFilter
$classes_ht = $classes | Group-ObjectHashtable 'sourcedId'
$courses = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/courses" -PropertyName "courses" -Filter $config.CourseFilter
$courses_ht = $courses | Group-ObjectHashtable 'sourcedId'
#User can be used instead if guardians or other roles are needed. Filtering by roles doesn't seem to be working, thus separate endpoints vs just users.
#$users = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/users" -PropertyName "users" -Filter $confg.UserFIlter
$students = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/students" -PropertyName "users" -Filter $config.UserFilter
$teachers = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/teachers" -PropertyName "users" -Filter $config.UserFilter
$demographics = Get-Data @splat -EndpointUri "/ims/oneroster/rostering/v1p2/demographics" -PropertyName "demographics" -Filter $config.DemographicFilter
$demographics_ht = $demographics | Group-ObjectHashtable 'sourcedId'
$availablePersons = [System.Collections.Generic.List[object]]::new()
#$availablePersons.AddRange($users)
$availablePersons.AddRange($students)
$availablePersons.AddRange($teachers)
} catch {
throw "Get Data Failed - $($_)"
}
#endregion Get Data
#region Prepare Return Data
foreach($user in $availablePersons)
{
$person = @{}
$person['ExternalId'] = '{0}' -f $user.sourcedId
$person['DisplayName'] = '{0} {1} ({2})' -f $user.givenName, $user.familyName, $user.sourcedId
$_skipfields = @("agents","grades")
foreach($prop in ($user.PSObject.properties))
{
if($_skipfields -notcontains $prop.Name)
{
$person[$prop.Name -replace '\W','_'] = $prop.Value
}
}
$person['demographics'] = try{ $demographics_ht[$user.sourcedId] } catch{''}
# Grade - Convert from Array to just a string.
$person['grades'] = try{$user.grades[0]}catch{''}
# Not including Agents. Only needed if mapping Parent/Guardian data.
#$person['agents'] = $user.agents.sourcedId
# Add Contracts
$person['Contracts'] = [System.Collections.Generic.List[psobject]]::new()
# Add Class Enrollments
foreach($e in $enrollments_ht[$user.sourcedId.ToString()])
{
$contract = @{
externalID = $e.sourcedId
Class = @{}
}
# Process Enrollment Fields
$_skipfields = @("class","school","user")
foreach($prop in ($e.PSObject.properties)) # | ? {$_skipfields -notcontains $_.Name}))
{
if($_skipfields -notcontains $prop.Name)
{
$contract[$prop.Name -replace '\W','_'] = $prop.Value
}
}
#Class for Enrollment
$c = $classes_ht[$e.class.sourcedId.ToString()][0]
$_skipfields = @("course","school","terms") #"periods","subjects","subjectCodes",
foreach($prop in ($c.PSObject.properties))# | ? {$_skipfields -notcontains $_.Name}))
{
if($_skipfields -notcontains $prop.Name)
{
$contract.class[$prop.Name -replace '\W','_'] = $prop.Value
}
}
# Sequence used for Priority Logic. Priority: HomeRoom, scheduled, everything else
switch ($c.classType)
{
'homeroom' {$contract['Sequence'] = 1}
'scheduled' {$contract['Sequence'] = 2}
default {$contract['Sequence'] = 3}
}
# Extra logic to lower priority of 'tobedeleted' records.
if($contract.status -ne 'active') {$contract.Sequence = 3}
#Academic Sessions/Terms for Class (Not including Terms due to excessive memory use in HelloID error)
#$contract['terms'] = [System.Collections.Generic.List[psobject]]::new()
foreach($_term in $c.terms)
{
$term = @{}
$as = $academicSessions_ht[$_term.sourcedId.ToString()][0]
$_skipfields = @("children","parent")
foreach($prop in ($as.PSObject.properties)) # | ? {$_skipfields -notcontains $_.Name}))
{
if($_skipfields -notcontains $prop.Name)
{
$term[$prop.Name -replace '\W','_'] = $prop.Value
}
}
#$contract['terms'].Add($term)
# Update Earliest and Latest Term Start/End Dates for Class.
$contract['startDate'] = $(if(!$contract['startDate'] -OR $contract['startDate'] -gt $term.startDate){$term.startDate}else{$contract['startDate']})
$contract['endDate'] = $(if(!$contract['endDate'] -OR $contract['endDate'] -lt $term.endDate){$term.endDate}else{$contract['endDate']})
}
#Course for Class
$contract['course'] = @{}
$crs = $courses_ht[$c.course.sourcedId.ToString()][0]
$_skipfields = @("org","subjectCodes","subjects")
foreach($prop in ($crs.PSObject.properties)) # | ? {$_skipfields -notcontains $_.Name}))
{
if($_skipfields -notcontains $prop.Name)
{
$contract.course[$prop.Name -replace '\W','_'] = $prop.Value
}
}
#School for Enrollment
$contract['school'] = @{}
$sch = $orgs_ht[$c.school.sourcedId.ToString()][0]
$_skipfields = @("parent")
foreach($prop in ($sch.PSObject.properties)) # | ? {$_skipfields -notcontains $_.Name}))
{
if($_skipfields -notcontains $prop.Name)
{
$contract.school[$prop.Name -replace '\W','_'] = $prop.Value
}
}
# Add Location Enrichment Data Here (if needed)
$person.Contracts.Add($contract)
}
Write-Output ($person | ConvertTo-Json -Depth 10)
}
#endregion Prepare Return Data
#region Return Data to HelloID
Write-Information "Finished Processing Persons"
#endregion Return Data to HelloID