Top Level Namespace

Defined Under Namespace

Modules: D2lSdk

Instance Method Summary collapse

Instance Method Details

#_delete(path, isD2l = true) ⇒ Object

Performs a delete request by creating an authenticated uri and using the RestClient delete method and specifying the content_type as being JSON.



111
112
113
114
115
# File 'lib/d2l_sdk/requests.rb', line 111

def _delete(path, isD2l = true)
    auth_uri = path
    auth_uri = create_authenticated_uri(path, 'DELETE') if isD2l == true
    RestClient.delete(auth_uri, content_type: :json)
end

#_get(path, isD2l = true) ⇒ Object

returns: JSON parsed response.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/d2l_sdk/requests.rb', line 14

def _get(path, isD2l = true)
    uri_string = path
    uri_string = create_authenticated_uri(path, 'GET') if isD2l == true
    ap uri_string if @debug
    RestClient.get(uri_string) do |response, _request, _result|
      begin
        #ap _request
        case response.code
        when 200
            # ap JSON.parse(response) # Here is the JSON fmt'd response printed
            JSON.parse(response)
        else
            display_response_code(response.code)
            ap JSON.parse(response.body) if @debug
        end
      rescue => e
        display_response_code(response.code)
        ap JSON.parse(response.body) if @debug
        raise
      end
    end
end

#_get_raw(path, isD2l = true) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/d2l_sdk/requests.rb', line 37

def _get_raw(path, isD2l = true)
  uri_string = path
  uri_string = create_authenticated_uri(path, 'GET') if isD2l == true
  RestClient.get(uri_string) do |response, _request, _result|
    begin
      case response.code
      when 200
          # ap JSON.parse(response) # Here is the JSON fmt'd response printed
          response
      else
          display_response_code(response.code)
          ap response.body
      end
    rescue => e
      display_response_code(response.code)
      ap response.body
      raise
    end
  end
end

#_get_string(path, http_method) ⇒ Object

Used as a helper method for create_authenticated_uri in order to properly create a query string that will (hopefully) work with the Valence API. the arguments path and http_method are used as arguments with the current time for format_signature and build_authenticated_uri_query_string.

returns: String::query_string



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/d2l_sdk/auth.rb', line 85

def _get_string(path, http_method)
    timestamp = Time.now.to_i
    signature = format_signature(path, http_method, timestamp)
    unless path.include? "/auth/api/token"
      build_authenticated_uri_query_string(signature, timestamp)
    else
      # build authenticated query string not using typical schema
      build_authenticated_token_uri_query_string(signature, timestamp)
    end
    # returns: String::query_string
end

#_get_user_by_string(parameter, search_string, range, regex = false) ⇒ Object

get_user_by_string uses arguments search_string and range. To use these, a range is created, an array of matching names is initialized, and then the entire range is iterated to check for names that have the search_string in them. Upon reaching a page that has an empty items JSON array, the search ends. This is due to the fact that pages with zero items will not have any more users past them. The array of matching names is then returned.

returns: array::matching_names



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/d2l_sdk/user.rb', line 168

def _get_user_by_string(parameter, search_string, range, regex = false)
    # puts "searching from #{range.min.to_s} to #{range.max.to_s}"
    i = range.min
    matching_names = []
    # Average difference between each paged bookmarks beginnings is 109.6
    while i.to_i < range.max
        # path = "/d2l/api/lp/#{$lp_ver}/users/?bookmark=" + i.to_s
        response = get_users_by_bookmark(i.to_s)
        if response['PagingInfo']['HasMoreItems'] == false
            # ap 'response returned zero items, last page possible for this thread..'
            return matching_names
        end
        response['Items'].each do |user|
            if regex && !user[parameter].nil?
                matching_names.push(user) if (user[parameter] =~ search_string) != nil
            elsif !user[parameter].nil?
                matching_names.push(user) if user[parameter].include? search_string
            end
        end
        i = response['PagingInfo']['Bookmark']
    end
    matching_names
end

#_post(path, payload, isD2l = true) ⇒ Object

performs a post request using the path and the payload arguments. First, an authenticated uri is created to reference a particular resource. Then, the post method is executed using the payload and specifying that it is formatted as JSON.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/d2l_sdk/requests.rb', line 64

def _post(path, payload, isD2l = true)
    auth_uri = path
    auth_uri = create_authenticated_uri(path, 'POST') if isD2l == true
    RestClient.post(auth_uri, payload.to_json, content_type: :json) do |response|
      case response.code
      when 200
        return nil if response == ""
        JSON.parse(response)
        ap JSON.parse(response.body)
      else
        display_response_code(response.code)
        ap JSON.parse(response.body) if $debug
      end
    end
end

#_put(path, payload, isD2l = true) ⇒ Object

performs a put request using the path and the payload arguments. After first creating an authenticated uri, the put request is performed using the authenticated uri, the payload argument, and specifying that the payload is formatted in JSON.



102
103
104
105
106
107
# File 'lib/d2l_sdk/requests.rb', line 102

def _put(path, payload, isD2l = true)
    auth_uri = path
    auth_uri = create_authenticated_uri(path, 'PUT') if isD2l == true
    # Perform the put action, updating the data; Provide feedback to client.
    RestClient.put(auth_uri, payload.to_json, content_type: :json)
end

#add_child_org_unit(org_unit_id, child_org_unit_id) ⇒ Object

Adds a child to the org unit by using org_unit_id to reference the soon-to-be parent of the child_org_unit and referencing the soon-to-be child through the child_org_unit_id argument. Then, a path is created to reference the children of the soon-to-be parent and executing a post http method that adds the child.

TL;DR, this adds a child org_unit to the children of an org_unit.



161
162
163
164
# File 'lib/d2l_sdk/org_unit.rb', line 161

def add_child_org_unit(org_unit_id, child_org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/children/"
    _post(path, child_org_unit_id)
end

#add_child_to_module(org_unit_id, module_id) ⇒ Object

Add a child module or topic to a specific module’s structure. Can be used in multiple ways. D2L categorizes it into 3 different ways: –Module: add child module to parent module –Link Topic: add child topic to parent module structure consisting of a LINK

type topic.

–File Topic: add child topic to parent module structure consisting of a FILE

type topic.

INPUT: (depends upon if its module, link topic, or file topic) –Module: POST body containing a ContentObjectData JSON data block of type Module –Link Topic: POST body containing a ContentObjectData JSON data block of type Topic

URL property in it points to resource you want to the link to point to.

–File Topic: Multipart/mixed post body w/ 2 parts

1. +ContentObjectData+ JSON data block of type Topic
2. File attachment data itself you want to store in OU content area

Returns (if successful) a JSON data block containing properties of the newly created object



69
70
71
72
# File 'lib/d2l_sdk/course_content.rb', line 69

def add_child_to_module(org_unit_id, module_id) # POST
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/modules/#{module_id}/structure/"
  # TODO
end

#add_course_to_semester(course_id, semester_id) ⇒ Object

Moreso a bridge function, but assists in adding a course to a particular semester. This is done by referencing each of these resources by ids. This returns a 200 response is the ids are correct.



55
56
57
# File 'lib/d2l_sdk/semester.rb', line 55

def add_course_to_semester(course_id, semester_id)
    add_child_org_unit(semester_id, course_id)
end

#add_parent_to_org_unit(parent_ou_id, child_ou_id) ⇒ Object

performs a post method to assign a parent to a particular child org unit. This is done by first referencing all the parents of the child_ou and then POSTing the id of another org unit that is to be added to the parents.



44
45
46
47
48
49
50
# File 'lib/d2l_sdk/org_unit.rb', line 44

def add_parent_to_org_unit(parent_ou_id, child_ou_id)
    # Must follow structure of data
    # (course <-- semester <== org -->custom dept--> dept -->templates--> courses)
    # Refer to valence documentation for further structural understanding..
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{child_ou_id}/parents/"
    _post(path, parent_ou_id)
end

#build_authenticated_uri_query_string(signature, timestamp) ⇒ Object

Builds an authenticated uniform resource identifier query string that works properly with the Valence API.

Required Variables:

  • app_id, user_id, app_key, user_key

returns: String::‘authenticated_uri’



49
50
51
52
53
54
55
56
# File 'lib/d2l_sdk/auth.rb', line 49

def build_authenticated_uri_query_string(signature, timestamp)
    "?x_a=#{$app_id}"\
    "&x_b=#{$user_id}"\
    "&x_c=#{get_base64_hash_string($app_key, signature)}"\
    "&x_d=#{get_base64_hash_string($user_key, signature)}"\
    "&x_t=#{timestamp}"
    # returns: String::'authenticated_uri'
end

#check_content_module_validity(content_module) ⇒ Object



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
# File 'lib/d2l_sdk/course_content.rb', line 74

def check_content_module_validity(content_module)
    schema = {
        'type' => 'object',
        'required' => %w(Title ShortTitle Type ModuleStartDate
                         ModuleEndDate ModuleDueDate IsHidden
                         IsLocked Description Duration),
        'properties' => {
            'Title' => { 'type' => 'string' },
            'ShortTitle' => { 'type' => 'string' },
            'Type' => { 'type' => 'integer' },
            'ModuleStartDate' => { 'type' => %w(string null) },
            'ModuleEndDate' => { 'type' => %w(string null) },
            'ModuleDueDate' => { 'type' => %w(string null) },
            'IsHidden' => { 'type' => %w(string null) },
            'IsLocked' => { 'type' => 'boolean' },
            'Description' => {
              'type' => 'object',
              'properties'=>
              {
                "Content" => "string",
                "Type" => "string" #"Text|HTML"
              }
            }, # Added with LE v1.10 API
            'Duration' => { 'type' => %w(integer null) } #Added in LE's unstable contract as of LE v10.6.8
        }
    }
    JSON::Validator.validate!(schema, content_module, validate_schema: true)
end

#check_content_topic_validity(content_topic) ⇒ Object



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
# File 'lib/d2l_sdk/course_content.rb', line 103

def check_content_topic_validity(content_topic)
    schema = {
        'type' => 'object',
        'required' => %w(Title ShortTitle Type  TopicType Url StartDate
                         EndDate DueDate IsHidden IsLocked OpenAsExternalResource
                         Description MajoyUpdate MajorUpdateText ResetCompletionTracking),
        'properties' => {
            'Title' => { 'type' => 'string' },
            'ShortTitle' => { 'type' => 'string' },
            'Type' => { 'type' => 'integer' },
            'TopicType' => { 'type' => 'integer' },
            'StartDate' => { 'type' => %w(string null) },
            'EndDate' => { 'type' => %w(string null) },
            'DueDate' => { 'type' => %w(string null) },
            'IsHidden' => { 'type' => %w(string null) },
            'IsLocked' => { 'type' => 'boolean' },
            'OpenAsExternalResource' => { 'type' => %w(boolean null) }, # Added with LE v1.6 API
            'Description' => { # Added with LE v1.10 API
              'type' => 'object',
              'properties'=>
              {
                "Content" => "string",
                "Type" => "string" #"Text|HTML"
              }
            },
            'MajorUpdate' => { 'type' => %w(boolean null) }, # Added with LE v1.12 API
            'MajorUpdateText' => { 'type' => 'string' }, #Added with LE v1.12 API
            'ResetCompletionTracking' => { 'type' => %w(boolean null) } #Added with LE v1.12 API
        }
    }
    JSON::Validator.validate!(schema, content_topic, validate_schema: true)
end

#check_course_data_validity(course_data) ⇒ Object

Checks whether the created course data conforms to the valence api for the course data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/d2l_sdk/course.rb', line 11

def check_course_data_validity(course_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code CourseTemplateId SemesterId
                         StartDate EndDate LocaleId ForceLocale
                         ShowAddressBook),
        'properties' => {
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'CourseTemplateId' => { 'type' => 'integer' },
            'SemesterId' => { 'type' => %w(integer null) },
            'StartDate' => { 'type' => %w(string null) },
            'EndDate' => { 'type' => %w(string null) },
            'LocaleId' => { 'type' => %w(integer null) },
            'ForceLocale' => { 'type' => 'boolean' },
            'ShowAddressBook' => { 'type' => 'boolean' }
        }
    }
    JSON::Validator.validate!(schema, course_data, validate_schema: true)
end

#check_course_template_data_validity(course_template_data) ⇒ Object

Checks if the created course template data conforms to the valence api for the course template JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/d2l_sdk/course_template.rb', line 11

def check_course_template_data_validity(course_template_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code Path ParentOrgUnitIds),
        'properties' => {
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'Path' => { 'type' => 'string' },
            'ParentOrgUnitIds' => { 'type' => 'array',
                                    'items' => { 'type' => 'integer', 'minItems' => 1 }
                         }
        }
    }
    JSON::Validator.validate!(schema, course_template_data, validate_schema: true)
end

#check_course_template_updated_data_validity(course_template_data) ⇒ Object

Checks if the updated course template data conforms to the valence api for the course template JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



121
122
123
124
125
126
127
128
129
130
131
# File 'lib/d2l_sdk/course_template.rb', line 121

def check_course_template_updated_data_validity(course_template_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code),
        'properties' => {
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' }
        }
    }
    JSON::Validator.validate!(schema, course_template_data, validate_schema: true)
end

#check_create_copy_job_request_validity(create_copy_job_request) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/d2l_sdk/course.rb', line 207

def check_create_copy_job_request_validity(create_copy_job_request)
    schema = {
        'type' => 'object',
        'required' => %w(SourceOrgUnitId Components CallbackUrl),
        'properties' => {
            'SourceOrgUnitId' => { 'type' => 'integer' },
            'Components' => {
                'type' => ['array', "null"],
                'items' =>
                  {
                      'type' => "string"
                  }
            },
            'CallbackUrl' => { 'type' => ['string', 'null'] }
        }
    }
    JSON::Validator.validate!(schema, create_copy_job_request, validate_schema: true)
end

#check_create_enrollment_data_validity(enrollment_data) ⇒ Object

Check the validity of the CreateEnrollmentData that is passed as a payload



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/d2l_sdk/enroll.rb', line 8

def check_create_enrollment_data_validity(enrollment_data)
    schema = {
        'type' => 'object',
        'required' => %w(OrgUnitId UserId RoleId),
        'properties' => {
            'OrgUnitId' => { 'type' => 'integer' },
            'UserId' => { 'type' => 'integer' },
            'RoleId' => { 'type' => 'integer' },
        }
    }
    JSON::Validator.validate!(schema, enrollment_data, validate_schema: true)
end

#check_create_org_unit_type_data_validity(org_unit_type_data) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/d2l_sdk/org_unit.rb', line 306

def check_create_org_unit_type_data_validity(org_unit_type_data)
    schema = {
        'type' => 'object',
        'required' => %w(Code Name Description SortOrder),
        'properties' => {
            'Code' => { 'type' => 'string' },
            'Name' => { 'type' => 'string' },
            'Description' => { 'type' => 'string' },
            'SortOrder' => { 'type' => 'integer'}
        }
    }
    JSON::Validator.validate!(schema, org_unit_type_data, validate_schema: true)
end

#check_if_product_supports_api_version(product_code, version) ⇒ Object

determine if a specific product component supports a particular API version



205
206
207
208
# File 'lib/d2l_sdk/requests.rb', line 205

def check_if_product_supports_api_version(product_code, version)
  path = "/d2l/api/#{product_code}/versions/#{version}"
  _get(path)
end

#check_org_unit_data_validity(org_unit_data) ⇒ Object

Checks whether the created org unit data conforms to the valence api for the org unit data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/d2l_sdk/org_unit.rb', line 205

def check_org_unit_data_validity(org_unit_data)
    schema = {
        'type' => 'object',
        'required' => %w(Type Name Code Parents),
        'properties' => {
            'Type' => { 'type' => 'integer' },
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'Parents' => { 'type' => 'array',
                           'items' => { 'type' => 'integer', 'minItems' => 1 }
                         }
        }
    }
    JSON::Validator.validate!(schema, org_unit_data, validate_schema: true)
end

#check_org_unit_updated_data_validity(org_unit_data) ⇒ Object

Checks whether the updated org unit data conforms to the valence api for the org unit data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/d2l_sdk/org_unit.rb', line 241

def check_org_unit_updated_data_validity(org_unit_data)
    schema = {
        'type' => 'object',
        'required' => %w(Identifier Name Code Path Type),
        'properties' => {
            'Identifier' => { 'type' => 'string' },
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'Path' => { 'type' => 'string' },
            'Type' => {
                'required' => %w(Id Code Name),
                'properties' => {
                    'Id' => { 'type' => 'integer' },
                    'Code' => { 'type' => 'string' },
                    'Name' => { 'type' => 'string' }
                }
            }
        }
    }
    JSON::Validator.validate!(schema, org_unit_data, validate_schema: true)
end

#check_product_versions(supported_version_request) ⇒ Object

determine versions supported by the back-end Brightspace API requires: JSON SupportedVersionRequest data block



228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/d2l_sdk/requests.rb', line 228

def check_product_versions(supported_version_request)
  payload =
  [
    {
      "ProductCode" => "9.9",
      "Version" => "9.9"
    }
  ].merge!(supported_version_request)
  # requires: JSON SupportedVersionRequest data block
  check_supported_version_request_validity(payload)
  path = "/d2l/api/versions/check"
  _post(path, payload)
  # returns: BulkSupportedVersionResponse JSON block
end

#check_section_data_validity(section_data) ⇒ Object

Check the validity of the SectionData that is passed as a payload



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/d2l_sdk/section.rb', line 88

def check_section_data_validity(section_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code Description),
        'properties' => {
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'Description' =>
            {
                'type' => 'object',
                'properties' =>
                {
                    'Content' => 'string',
                    'Type' => 'string'
                }
            }
        }
    }
    JSON::Validator.validate!(schema, section_data, validate_schema: true)
end

#check_section_enrollment_validity(section_enrollment) ⇒ Object

Check the validity of the SectionEnrollment that is passed as a payload



125
126
127
128
129
130
131
132
133
134
# File 'lib/d2l_sdk/section.rb', line 125

def check_section_enrollment_validity(section_enrollment)
    schema = {
        'type' => 'object',
        'required' => %w(UserId),
        'properties' => {
            'UserId' => { 'type' => 'integer' }
        }
    }
    JSON::Validator.validate!(schema, section_enrollment, validate_schema: true)
end

#check_section_property_data_validity(section_property_data) ⇒ Object

Check the validity of the SectionPropertyData that is passed as a payload



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/d2l_sdk/section.rb', line 148

def check_section_property_data_validity(section_property_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code Description),
        'properties' => {
            'EnrollmentStyle' => { 'type' => 'integer' },
            'EnrollmentQuantity' => { 'type' => 'integer' },
            'AutoEnroll' => { 'type' => 'boolean' },
            'RandomizeEnrollments' => { 'type' => 'boolean' }
        }
    }
    JSON::Validator.validate!(schema, section_property_data, validate_schema: true)
end

#check_semester_data_validity(semester_data) ⇒ Object

Checks if the created semester data conforms to the valence api for the semester JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



12
13
14
# File 'lib/d2l_sdk/semester.rb', line 12

def check_semester_data_validity(semester_data)
    check_org_unit_data_validity(semester_data)
end

#check_semester_updated_data_validity(semester_data) ⇒ Object

Checks if the updated semester data conforms to the valence api for the semester JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



104
105
106
# File 'lib/d2l_sdk/semester.rb', line 104

def check_semester_updated_data_validity(semester_data)
    check_org_unit_updated_data_validity(semester_data)
end

#check_supported_version_request_validity(supported_version_request) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/d2l_sdk/requests.rb', line 210

def check_supported_version_request_validity(supported_version_request)
    schema = {
      'type' => 'array',
      'items' =>
        {
            'type' => "object",
            "properties" =>
            {
              "Productcode" => {'type'=>"string"},
              "Version" => {'type'=>"string"}
            }
        }
    }
    JSON::Validator.validate!(schema, supported_version_request, validate_schema: true)
end

#check_updated_course_data_validity(course_data) ⇒ Object

Checks whether the updated course data conforms to the valence api for the update data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/d2l_sdk/course.rb', line 155

def check_updated_course_data_validity(course_data)
    schema = {
        'type' => 'object',
        'required' => %w(Name Code StartDate EndDate IsActive),
        'properties' => {
            'Name' => { 'type' => 'string' },
            'Code' => { 'type' => 'string' },
            'StartDate' => { 'type' => ['string', "null"] },
            'EndDate' => { 'type' => ['string', "null"] },
            'IsActive' => { 'type' => "boolean" },
        }
    }
    JSON::Validator.validate!(schema, course_data, validate_schema: true)
end

#check_updated_user_data_validity(user_data) ⇒ Object

Checks whether the updated user data conforms to the valence api for the user data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



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
# File 'lib/d2l_sdk/user.rb', line 208

def check_updated_user_data_validity(user_data)
    schema = {
        'type' => 'object',
        'required' => %w(OrgDefinedId FirstName MiddleName
                         LastName ExternalEmail UserName
                         Activation),
        'properties' => {
            'OrgDefinedId' => { 'type' => 'string' },
            'FirstName' => { 'type' => 'string' },
            'MiddleName' => { 'type' => 'string' },
            'LastName' => { 'type' => 'string' },
            'ExternalEmail' => { 'type' => %w(string null) },
            'UserName' => { 'type' => 'string' },
            'Activation' => {
                'required' => ['IsActive'],
                'properties' => {
                    'IsActive' => {
                        'type' => 'boolean'
                    }
                }
            }
        }
    }
    JSON::Validator.validate!(schema, user_data, validate_schema: true)
end

#check_user_data_validity(user_data) ⇒ Object

Checks whether the created user data conforms to the valence api for the user data JSON object. If it does conform, then nothing happens and it simply returns true. If it does not conform, then the JSON validator raises an exception.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/d2l_sdk/user.rb', line 13

def check_user_data_validity(user_data)
    schema = {
        'type' => 'object',
        'required' => %w(OrgDefinedId FirstName MiddleName
                         LastName ExternalEmail UserName
                         RoleId IsActive SendCreationEmail),
        'properties' => {
            'OrgDefinedId' => { 'type' => 'string' },
            'FirstName' => { 'type' => 'string' },
            'MiddleName' => { 'type' => 'string' },
            'LastName' => { 'type' => 'string' },
            'ExternalEmail' => { 'type' => %w(string null) },
            'UserName' => { 'type' => 'string' },
            'RoleId' => { 'type' => 'integer' },
            'IsActive' => { 'type' => 'boolean' },
            'SendCreationEmail' => { 'type' => 'boolean' }
        }
    }
    JSON::Validator.validate!(schema, user_data, validate_schema: true)
end

#create_authenticated_uri(path, http_method) ⇒ Object

Creates an authenticated uniform resource identifier that works with Valence by calling URI.parse using the path downcased, then creating a query string by calling _get_string with the parsed_url and the http_method. These are used as the Variables and then returned as the finished uri.

Input that is required is:

* path: The path to the resource you are trying to accessing
* http_method: The method utilized to access/modify the resource

returns: String::uri



32
33
34
35
36
37
38
39
40
# File 'lib/d2l_sdk/auth.rb', line 32

def create_authenticated_uri(path, http_method)
    parsed_url = URI.parse(path.downcase)
    uri_scheme = 'https'
    query_string = _get_string(parsed_url.path, http_method)
    uri = uri_scheme + '://' + $hostname + parsed_url.path + query_string
    uri << '&' + parsed_url.query if parsed_url.query
    uri
    # returns: String::uri
end

#create_course_data(course_data) ⇒ Object

Creates the course based upon a merged result of the argument course_data and a preformatted payload. This is then passed as a new payload in the _post method in order to create the defined course. Required: “Name”, “Code” Creates the course offering



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
# File 'lib/d2l_sdk/course.rb', line 38

def create_course_data(course_data)
    # ForceLocale- course override the user’s locale preference
    # Path- root path to use for this course offering’s course content
    #       if your back-end service has path enforcement set on for
    #       new org units, leave this property as an empty string
    # Define a valid, empty payload and merge! with the user_data. Print it.
    # can be an issue if more than one course template associated with
    # a course and the last course template parent to a course cannot be deleted
    payload = { 'Name' => '', # String
                'Code' => 'off_SEMESTERCODE_STARNUM', # String
                'Path' => '', # String
                'CourseTemplateId' => 99_989, # number: D2L_ID
                'SemesterId' => nil, # number: D2L_ID  | nil
                'StartDate' => nil, # String: UTCDateTime | nil
                'EndDate' => nil, # String: UTCDateTime | nil
                'LocaleId' => nil, # number: D2L_ID | nil
                'ForceLocale' => false, # bool
                'ShowAddressBook' => false # bool
              }.merge!(course_data)
    check_course_data_validity(payload)
    # ap payload
    # requires: CreateCourseOffering JSON block
    path = "/d2l/api/lp/#{$lp_ver}/courses/"
    _post(path, payload)
    puts '[+] Course creation completed successfully'.green
end

#create_course_template(course_template_data) ⇒ Object

This method creates a course template using a merged payload between a pre-formatted payload and the argument “course_template_data”. Upon this merge the path is defined for the POST http method that is then executed to create the course_template object. Required: “Name”, “Code” /d2l/api/lp/(version)/coursetemplates/ [POST]



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/d2l_sdk/course_template.rb', line 33

def create_course_template(course_template_data)
    # Path- root path to use for this course offering’s course content
    #       if your back-end service has path enforcement set on for
    #       new org units, leave this property as an empty string
    # Define a valid, empty payload and merge! with the user_data. Print it.
    payload = { 'Name' => '', # String
                'Code' => 'off_SEMESTERCODE_STARNUM', # String
                'Path' => '', # String
                'ParentOrgUnitIds' => [99_989], # number: D2L_ID
              }.merge!(course_template_data)
    check_course_template_data_validity(payload)
    puts 'Creating Course Template:'
    ap payload
    # Define a path referencing the courses path
    # requires: CreateCourseTemplate JSON block
    path = "/d2l/api/lp/#{$lp_ver}/coursetemplates/"
    _post(path, payload)
    puts '[+] Course template creation completed successfully'.green
    # returns: CourseTemplate JSON block containing the new data.
end

#create_custom_org_unit(org_unit_data) ⇒ Object

Functions considered for basic added functionality to api, not sure if needed.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/d2l_sdk/org_unit.rb', line 222

def create_custom_org_unit(org_unit_data)
    # Requires the type to have the correct parent. This will work fine in this
    # sample, as the department (101) can have the parent Organiation (6606)
    payload = { 'Type' => 101, # Number:D2LID
                'Name' => 'custom_ou_name', # String
                'Code' => 'custom_ou_code', # String
                'Parents' => [6606], # Number:D2LID
              }.merge!(org_unit_data)
    check_org_unit_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/"
    # Requires: OrgUnitCreateData JSON block
    _post(path, payload)
    # returns: OrgUnit JSON data block
end

#create_custom_outype(create_org_unit_type_data) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/d2l_sdk/org_unit.rb', line 320

def create_custom_outype(create_org_unit_type_data)
  payload =
  {
    'Code' => '',
    'Name' => '',
    'Description' => '',
    'SortOrder' => 0
  }.merge!(create_org_unit_type_data)
  #validate schema
  check_create_org_unit_type_data_validity(payload)
  path = "/d2l/api/lp/#{$lp_ver}/outypes/"
  _post(path, payload)
  # returns OrgUnitType JSON data block
end

#create_export_job(create_export_job_data) ⇒ Object

Create an export job for the requested data set



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/d2l_sdk/datahub.rb', line 68

def create_export_job(create_export_job_data)
    # init payload and merge with export job data
    payload = {
        'DataSetId' => '',
        'Filters' => [] # {"Name"=> "startDate", "Value" => UTCDATETIME STRING}
    }.merge!(create_export_job_data)
    validate_create_export_job_data(payload)
    # Requires: CreateExportJobData JSON parameter
    path = "/d2l/api/lp/#{$lp_ver}/dataExport/create"
    _post(path, payload)
    # returns ExportJobData JSON block
end

#create_isbn_org_unit_association(org_unit_id, isbn_association_data) ⇒ Object

Create a new association between an ISBN and an org unit.



270
271
272
273
274
275
276
277
278
279
280
# File 'lib/d2l_sdk/course_content.rb', line 270

def create_isbn_org_unit_association(org_unit_id, isbn_association_data) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}content/isbn/"
  payload = {
    "OrgUnitId" => 0,
    "Isbn" => ""
    #"IsRequired" => false ## optional
  }.merge!(isbn_association_data)
  _post(query_string, payload)
  # Returns: a IsbnAssociation JSON data block specifying
  # the association between an org unit and an ISBN.
end

#create_new_copy_job_request(org_unit_id, create_copy_job_request) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/d2l_sdk/course.rb', line 227

def create_new_copy_job_request(org_unit_id, create_copy_job_request)
  payload =
  {
    'SourceOrgUnitId' => 0, # int
    'Components' => nil, # [Str,...] || nil
    'CallbackUrl' => nil # str | nil
  }.merge!(create_copy_job_request)
  # Check that the payload conforms to the JSON Schema of CreateCopyJobRequest
  check_create_copy_job_request_validity(payload)
  # Check each one of the components to see if they are valid Component types
  payload["Components"].each do |component|
    # If one of the components is not valid, cancel the CopyJobRequest operation
    if(!is_course_component(key))
      puts "'#{component}' specified is not a valid Copy Job Request component"
      puts "Please retry with a valid course component such as 'Dropbox' or 'Grades'"
      break
    end
  end
  path = "/d2l/api/le/#{$le_ver}/import/#{org_unit_id}/copy/"
  _post(path, payload)
  # Returns CreateCopyJobResponse JSON block
end

#create_org_unit_group(org_unit_id, group_category_id, group_data) ⇒ Object

Create a new group for an org unit.



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/d2l_sdk/group.rb', line 143

def create_org_unit_group(org_unit_id, group_category_id, group_data)
  payload =
  {
    "Name" => "string",
    "Code" => "string",
    "Description" => {}
  }.merge!(group_data)
  # Requires: JSON block of GroupData
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/"
  _post(path, payload)
  # returns a GroupData JSON block, in the Fetch form, of the new group
end

#create_org_unit_group_category(org_unit_id, group_category_data) ⇒ Object

See validate_create_group_category_data for details on schema formal requirements of values Create a new group category for an org unit.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/d2l_sdk/group.rb', line 100

def create_org_unit_group_category(org_unit_id, group_category_data)
  payload = { 'Name' => '', # String
              'Description' => {}, # RichTextInput
              'EnrollmentStyle' => 0, # number : group_enroll
              'EnrollmentQuantity' => nil, # number | null
              'AutoEnroll' => false, # bool
              'RandomizeEnrollments' => false, # bool
              'NumberOfGroups' => nil, # number | nil
              'MaxUsersPerGroup' => nil, # number | nil
              'AllocateAfterExpiry' => false, # bool
              'SelfEnrollmentExpiryDate' => nil, # string: UTCDateTime | nil
              'GroupPrefix' => nil, # String | nil
            }.merge!(group_category_data)
  # Requires: JSON block of GroupCategoryData
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/"
  _post(path, payload)
  # returns a GroupCategoryData JSON block, in the Fetch form, of the new categ.
end

#create_org_unit_section(org_unit_id, section_data) ⇒ Object

Create a new section in a particular org unit.



110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/d2l_sdk/section.rb', line 110

def create_org_unit_section(org_unit_id, section_data)
  payload = { 'Name' => '', # String
              'Code' => '', # String
              'Description' => {}, # RichTextInput -- e.g. {'Content'=>'x', 'Type'=>'y'}
            }.merge!(section_data)
  # Check the validity of the SectionData that is passed as a payload
  check_section_data_validity(payload)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/"
  # JSON param: SectionData
  _post(path, payload)
    # returns the SectionData JSON block, in its Fetch form, for the
    # org unit's new section.
end

#create_range(min, max) ⇒ Object

Uses a min and max to create a range. returns: range obj



103
104
105
106
# File 'lib/d2l_sdk/user.rb', line 103

def create_range(min, max)
    (min..max)
    # returns: range obj
end

#create_root_module(org_unit_id, content_module) ⇒ Object

Create a new root module for an org unit. INPUT: ContentObjectData (of type Module) – New root module property data. Returns JSON array of ContentObject data blocks of type Module



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/d2l_sdk/course_content.rb', line 139

def create_root_module(org_unit_id, content_module) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/root/"
  payload = {
    "Title" => "",
    "ShortTitle" => "",
    "Type" => 0,
    "ModuleStartDate" => nil, #<string:UTCDateTime>|null
    "ModuleEndDate" => nil, #<string:UTCDateTime>|null
    "ModuleDueDate" => nil, #<string:UTCDateTime>|null
    "IsHidden" => false,
    "IsLocked" => false,
    "Description" => nil, #{ <composite:RichTextInput> }|null --Added with LE v1.10 API
    "Duration" => nil #  <number>|null --Added in LE's +unstable+ contract as of LE v10.6.8
  }.merge!(content_module)
  check_content_module_validity(payload)
  _post(query_string, payload)
end

#create_semester_code(star_num, course_date) ⇒ Object

WesternOnline Specific GET Section ID by Code



17
18
19
# File 'lib/d2l_sdk/section.rb', line 17

def create_semester_code(star_num, course_date)
    "sec_#{course_date}_#{star_num}"
end

#create_semester_data(semester_data) ⇒ Object

Creates a semester based upon a merged result from merging a preformatted payload and the inputed semester data. This is then created server-side via executing a POST http method using a predefined path and the new payload.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/d2l_sdk/semester.rb', line 19

def create_semester_data(semester_data)
    # Define a valid, empty payload and merge! with the semester_data. Print it.
    payload = { 'Type' => 5, # Number:D2LID
                'Name' => 'Winter 2013 Semester', # String
                'Code' => '201701', # String #YearNUM where NUM{sp:01,su:06,fl:08}
                'Parents' => [6606], # ARR of Number:D2LID
              }.merge!(semester_data)
    # ap payload
    check_semester_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/"
    _post(path, payload)
    puts '[+] Semester creation completed successfully'.green
end

#create_semester_formatted_path(org_id, code) ⇒ Object

This is simply a helper function that can assist in preformatting a path that conforms to the required ‘Path’ for updating semester data.

returns: preformatted semester ‘Path’ string



96
97
98
# File 'lib/d2l_sdk/semester.rb', line 96

def create_semester_formatted_path(org_id, code)
    "/content/enforced/#{org_id}-#{code}/"
end

#create_user_data(user_data) ⇒ Object

Creates the user using user_data as an argument. A Hash is merged with the user_data. The data types for each Hash key is specified below. For the ExternalEmail, there must be either nil for the value or a WELL FORMED email address. The username must be unique, meaning no other user has that name. All of the rest can remain the same, assuming roleId 110 exists in your system.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/d2l_sdk/user.rb', line 40

def create_user_data(user_data)
    # Define a valid, empty payload and merge! with the user_data. Print it.
    payload = { 'OrgDefinedId' => '', # String
                'FirstName' => 'TestUser', # String
                'MiddleName' => 'Test', # String
                'LastName' => 'Test', # String
                'ExternalEmail' => nil, # String (nil or well-formed email addr)
                'UserName' => 'test12345a', # String
                'RoleId' => 110, # number
                'IsActive' => false, # bool
                'SendCreationEmail' => false, # bool
              }.merge!(user_data)
    # requires: UserData JSON block
    # Define a path referencing the course data using the course_id
    check_user_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/users/"
    _post(path, payload)
    puts '[+] User creation completed successfully'.green
    # returns a UserData JSON block for the newly created user
end

#create_user_enrollment(course_enrollment_data) ⇒ Object

Create a new enrollment for a user.



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/d2l_sdk/enroll.rb', line 22

def create_user_enrollment(course_enrollment_data)
    payload = { 'OrgUnitId' => '', # String
                'UserId' => '', # String
                'RoleId' => '', # String
              }.merge!(course_enrollment_data)
    # ap payload
    # requires: CreateEnrollmentData JSON block
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/"
    _post(path, payload)
    puts '[+] User successfully enrolled'.green
    # Returns: EnrollmentData JSON block for the newly enrolled user.
end

#delete_all_course_templates_with_name(name) ⇒ Object

As a more streamlined approach to deleting many course templates conforming to a particular naming style, this function performs deletions based on a string. Using the name argument, get_course_template_by_name is called in order to retrieve all matching templates. They are then deleted by referencing each of their Identifiers as arguments for delete_course_template.



168
169
170
171
172
173
174
175
# File 'lib/d2l_sdk/course_template.rb', line 168

def delete_all_course_templates_with_name(name)
    puts "[!] Deleting all course templates with the name: #{name}"
    get_course_template_by_name(name).each do |course_template|
        puts '[!] Deleting the following course:'.red
        ap course_template
        delete_course_template(course_template['Identifier'])
    end
end

#delete_course_by_id(org_unit_id) ⇒ Object

Deletes a course based, referencing it via its org_unit_id This reference is created through a formatted path appended with the id. Then, a delete http method is executed using this path, deleting the course.



290
291
292
293
294
295
# File 'lib/d2l_sdk/course.rb', line 290

def delete_course_by_id(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/courses/#{org_unit_id}" # setup user path
    #ap path
    _delete(path)
    puts '[+] Course data deleted successfully'.green
end

#delete_course_template(org_unit_id) ⇒ Object

Simply, a course template can be deleted by refencing it using its Identifier as an argument for this method. The argument is then used to refernce the obj by a path and then the path is passed in for a delete http method. /d2l/api/lp/(version)/coursetemplates/(orgUnitId) [DELETE]



157
158
159
160
161
# File 'lib/d2l_sdk/course_template.rb', line 157

def delete_course_template(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/coursetemplates/#{org_unit_id}"
    _delete(path)
    puts '[+] Course template data deleted successfully'.green
end

#delete_course_templates_by_regex(regex) ⇒ Object

TO DO:



178
179
# File 'lib/d2l_sdk/course_template.rb', line 178

def delete_course_templates_by_regex(regex)
end

#delete_group(org_unit_id, group_category_id, group_id) ⇒ Object

Delete a particular group from an org unit.



13
14
15
16
# File 'lib/d2l_sdk/group.rb', line 13

def delete_group(org_unit_id, group_category_id, group_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/(groupId)"
  _delete(path)
end

#delete_group_category(org_unit_id, group_category_id) ⇒ Object

Delete a particular group category from an org unit.



7
8
9
10
# File 'lib/d2l_sdk/group.rb', line 7

def delete_group_category(org_unit_id, group_category_id)
   path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}"
   _delete(path)
end

#delete_isbn_association(org_unit_id, isbn) ⇒ Object

Remove the association between an ISBN and org unit.



227
228
229
230
# File 'lib/d2l_sdk/course_content.rb', line 227

def delete_isbn_association(org_unit_id, isbn) # DELETE
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/isbn/#{isbn}"
  _delete(query_string)
end

#delete_module(org_unit_id, module_id) ⇒ Object

Delete a specific module from an org unit.



7
8
9
10
# File 'lib/d2l_sdk/course_content.rb', line 7

def delete_module(org_unit_id, module_id) # DELETE
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/modules/#{module_id}"
  _delete(query_string)
end

#delete_outype(outype_id) ⇒ Object

Delete a particular org unit type



366
367
368
369
# File 'lib/d2l_sdk/org_unit.rb', line 366

def delete_outype(outype_id)
  path = "/d2l/api/lp/#{$lp_ver}/outypes/#{outype_id}"
  _delete(path)
end

#delete_recycled_org_unit(org_unit_id) ⇒ Object

deletes a particular org unit. This is done via referencing the org unit by its id and performing a delete method.



188
189
190
191
# File 'lib/d2l_sdk/org_unit.rb', line 188

def delete_recycled_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/recyclebin/#{org_unit_id}"
    _delete(path)
end

#delete_relationship_of_child_with_parent(parent_ou_id, child_ou_id) ⇒ Object

This deletes the relationship between a parent ou and a child ou by performing a delete method from the parent’s children and specifying this child through its id.



97
98
99
100
# File 'lib/d2l_sdk/org_unit.rb', line 97

def delete_relationship_of_child_with_parent(parent_ou_id, child_ou_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{parent_ou_id}/children/#{child_ou_id}"
    _delete(path)
end

#delete_relationship_of_parent_with_child(parent_ou_id, child_ou_id) ⇒ Object

This deletes the relationship between a child ou and a parent ou by performing a delete method from the child’s parents and specifying this parent through its id.



105
106
107
108
# File 'lib/d2l_sdk/org_unit.rb', line 105

def delete_relationship_of_parent_with_child(parent_ou_id, child_ou_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{child_ou_id}/parents/#{parent_ou_id}"
    _delete(path)
end

#delete_section(org_unit_id, section_id) ⇒ Object

Delete a section from a provided org unit.



9
10
11
12
# File 'lib/d2l_sdk/section.rb', line 9

def delete_section(org_unit_id, section_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/#{section_id}"
  _delete(path)
end

#delete_topic(org_unit_id, topic_id) ⇒ Object

Delete a specific topic from an org unit.



13
14
15
16
# File 'lib/d2l_sdk/course_content.rb', line 13

def delete_topic(org_unit_id, topic_id) # DELETE
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/topics/#{topic_id}"
  _delete(query_string)
end

#delete_user_data(user_id) ⇒ Object

Deletes the user’s data (identified by user_id). By forming a path that is correctly referencing this user’s data, a delete http method is executed and effectively deleted the user that is referenced.



264
265
266
267
268
269
# File 'lib/d2l_sdk/user.rb', line 264

def delete_user_data(user_id)
    # Define a path referencing the user data using the user_id
    path = "/d2l/api/lp/#{$lp_ver}/users/#{user_id}" # setup user path
    _delete(path)
    puts '[+] User data deleted successfully'.green
end

#delete_user_demographics(user_id, entry_ids = '') ⇒ Object

Delete one or more of a particular user’s associated demographics entries. if no entries specified, it DELETES ALL. entry_ids are added as additional variables entry_ids is a CSV formatted string



14
15
16
17
18
# File 'lib/d2l_sdk/demographics.rb', line 14

def delete_user_demographics(user_id, entry_ids = '')
  path = "/d2l/api/lp/#{$lp_ver}/demographics/users/#{user_id}"
  path += "?entryIds=" + entry_ids if entry_ids != ''
  _delete(path)
end

#delete_user_enrollment(user_id, org_unit_id) ⇒ Object

Delete a user’s enrollment in a provided org unit.



119
120
121
122
123
124
# File 'lib/d2l_sdk/enroll.rb', line 119

def delete_user_enrollment(user_id, org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/users/#{user_id}/orgUnits/#{org_unit_id}"
    _delete(path)
    # Returns: EnrollmentData JSON block showing the enrollment status
    #          just before this action deleted the enrollment of the user
end

#delete_user_enrollment_alternative(user_id, org_unit_id) ⇒ Object

Delete a user’s enrollment in a provided org unit.



128
129
130
131
132
133
# File 'lib/d2l_sdk/enroll.rb', line 128

def delete_user_enrollment_alternative(user_id, org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/orgUnits/#{org_unit_id}/users/#{user_id}"
    _delete(path)
    # Returns: EnrollmentData JSON block showing the enrollment status
    #          just before this action deleted the enrollment of the user
end

#display_response_code(code) ⇒ Object

based upon the specific code that is returned from the http method, this displays the response, in the case that it is an error within the request or the server. This is simply informative and assists in describing the lacking response information from the valence api. In the case of a Bad Request, it is likely that it cannot be further specified without looking back at the d2l_api documentation or looking at the documentation on the docs.valence.desire2learn.com website.



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
# File 'lib/d2l_sdk/requests.rb', line 124

def display_response_code(code)
    case code
    when 400
        puts '[!] 400: Bad Request'
    when 401
        puts '[!] 401: Unauthorized'

    when 403
        print '[!] Error Code Forbidden 403: accessing the page or resource '\
              'you were trying to reach is absolutely forbidden for some reason.'
    when 404
        puts '[!] 404: Not Found'
    when 405
        puts '[!] 405: Method Not Allowed'
    when 406
        puts 'Unacceptable Type'\
          'Unable to provide content type matching the client\'s Accept header.'
    when 412
        puts '[!] 412: Precondition failed\n'\
          'Unsupported or invalid parameters, or missing required parameters.'
    when 415
        puts '[!] 415: Unsupported Media Type'\
          'A PUT or POST payload cannot be accepted.'
    when 423
        puts '[!] 423'
    when 500
        puts '[!] 500: General Service Error\n'\
          'Empty response body. The service has encountered an unexpected'\
            'state and cannot continue to handle your action request.'
    when 504
        puts '[!] 504: Service Error'
    end
end

#does_user_exist(username) ⇒ Object

Checks whether a username already exists returns: true if the the user exists already



110
111
112
113
114
115
116
# File 'lib/d2l_sdk/user.rb', line 110

def does_user_exist(username)
    if !get_user_by_username(username.to_s).nil?
        return true
    else
        return false
    end
end

#download_job_csv(export_job_id) ⇒ Object

Downloads the identified job and stores the zip within the working directory Extracts zipped job contents in “export_jobs” folder of working directory



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
# File 'lib/d2l_sdk/datahub.rb', line 101

def download_job_csv(export_job_id)
    attempt = 0
    puts "Attempting to download job: #{export_job_id}"
    while attempt < 20 # Attempts 20 times (~3 mins) unless job failed.
      status = get_job_status_code(export_job_id)
      case status
      when 2 # If the status was okay, break loop + return download of job
        zip_fname = 'export1.zip'
        puts "Job complete, writing to zip: #{zip_fname}"
        File.write(zip_fname,_get_raw("/d2l/api/lp/#{$lp_ver}/dataExport/download/#{export_job_id}"))
        unzip(zip_fname, /sec_|off_/) # unzip file; filter if Enrollments + CSV
        puts "file downloaded and unzipped"
        break
      when /3|4/
        puts "Job download failed due to status: #{status}"
        if status == 3
          puts "Status description: Error - An error occurred when processing the export"
        else
          puts "Status description: Deleted - File was deleted from file system"
        end
        break
      else # else, print out the status and wait 10 seconds before next attempt
        puts "The job is not currently ready to download\n Status Code: #{status}"
        if status == 0
          puts "Status description: Queued -  Export job has been received for processing."
        else
          puts "Status description: Processing - Currently in process of exporting data set."
        end
        puts "Sleeping for 10 seconds.."
        sleep 10
        attempt = attempt + 1
      end
      # returns: ZIP file containing a CSV file of data from the export job
    end
end

#enroll_user_in_group(org_unit_id, group_category_id, group_id, user_id) ⇒ Object

Enroll a user in a group



182
183
184
185
186
187
188
189
190
# File 'lib/d2l_sdk/group.rb', line 182

def enroll_user_in_group(org_unit_id, group_category_id, group_id, user_id)
  payload = {
    "UserId" => user_id
  }
  # Requires: JSON block of GroupEnrollment
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/#{group_id}/enrollments/"
  validate_group_enrollment_data(payload)
  _post(path, payload)
end

#enroll_user_in_org_unit_section(org_unit_id, section_id, section_data) ⇒ Object

Enroll a user in a section for a particular org unit.



137
138
139
140
141
142
143
144
145
# File 'lib/d2l_sdk/section.rb', line 137

def enroll_user_in_org_unit_section(org_unit_id,section_id, section_data)
  payload = { 'UserId' => 9999, # Number : D2LID
            }.merge!(section_data)
  # Check the validity of the SectionEnrollment that is passed as a payload
  check_section_enrollment_validity(payload)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/#{section_id}/enrollments/"
  # JSON param: SectionEnrollment
  _post(path, payload)
end

#filter_formatted_enrollments(csv_fname, regex_filter = //, instr_fname) ⇒ Object

Filter all enrollments and withdrawals in a csv file, excluding data that is not properly formatted (based on ou code), not a current or future course, or nil for their ou code.



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
# File 'lib/d2l_sdk/datahub.rb', line 177

def filter_formatted_enrollments(csv_fname, regex_filter = //, instr_fname)
  # Create csv with 'filtered' pre-appended to '.csv' substring
  filtered_csv = csv_fname.gsub(/\.csv/,"filtered.csv")
  File.open(filtered_csv, 'w') do |file|
    # set row num to 0 to keep track of headers
    row_num = 0
    current = get_current_courses(instr_fname)
    # for each row
    puts "Filtering #{csv_fname}"
    CSV.foreach(csv_fname) do |row|
      # the line is initialized as an empty string
      line = ""
      # Skip the row if not a valid
        # or skip in-filter OU_code,
        # or skip if the header
        # or skip if not within the INSTR SET of current/future courses
      if row[3] == nil || row_num > 0 && !(row[3] =~ regex_filter) || (!current.include? row[3][4..-1])
        row_num += 1
        next
      end
      # for values not filtered from above ^
      # for all of these values
      row[0..-1].each do |value|
        # If it a UTC date time value, then parse as Time.
        if value =~ /\b[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]*Z\b/ # if the value is UTC formatted
          line << "\"#{Time.parse(value)}\""
        elsif value == row[-1]# if its the last value in the row
          line "        else # not the last value in the row,\n          line << \"\\\"\#{value}\\\",\" # throw a comma after the value\n        end\n      end\n      file.write(line + \"\\n\") # append this line to the csv\n      row_num += 1 # increment the row number\n    end\n  end\nend\n"#{value}\"" #  then dont put a comma at the end.

#format_signature(path, http_method, timestamp) ⇒ Object

uses the path, http_method, and timestamp arguments to create a properly formatted signature. Then, this is returned.

returns: String::signature



62
63
64
65
# File 'lib/d2l_sdk/auth.rb', line 62

def format_signature(path, http_method, timestamp)
    http_method.upcase + '&' + path.encode('UTF-8') + '&' + timestamp.to_s
    # returns: String::signature
end

#get_all_childless_org_units(org_unit_type = '', org_unit_code = '', org_unit_name = '', bookmark = '') ⇒ Object

This retrieves a paged result of all the childless org units within the organization. As this is paged, it only retrieves the first 100 from the beginning of the request. If bookmark is not specified, then it only retrieves the first 100 results.

return: JSON array of childless org units.



116
117
118
119
120
121
122
123
124
125
# File 'lib/d2l_sdk/org_unit.rb', line 116

def get_all_childless_org_units(org_unit_type = '', org_unit_code = '', org_unit_name = '',
                                bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/childless/"
    path += "?orgUnitType=#{org_unit_type}" if org_unit_type != ''
    path += "?orgUnitCode=#{org_unit_code}" if org_unit_code != ''
    path += "?orgUnitName=#{org_unit_name}" if org_unit_name != ''
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # ONLY RETRIEVES FIRST 100
end

#get_all_config_var_definitions(search = '', bookmark = '') ⇒ Object

Retrieve the definitions for all the configuration variables the user has access to view.



9
10
11
12
13
14
15
# File 'lib/d2l_sdk/config_variables.rb', line 9

def get_all_config_var_definitions(search='', bookmark='')
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/definitions/"
  path += "?search=#{search}" if search != ''
  path += "?bookmark=#{bookmark}" if bookmark != ''
  _get(path)
  #returns paged result set of Definition JSON data blocks
end

#get_all_config_var_org_unit_override_values(variable_id, bookmark = '') ⇒ Object

Retrieve all the org unit override values for a configuration variable.



39
40
41
42
43
44
# File 'lib/d2l_sdk/config_variables.rb', line 39

def get_all_config_var_org_unit_override_values(variable_id, bookmark='')
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/orgUnits/"
  path += "?bookmark=#{bookmark}" if bookmark != ''
  _get(path)
  # returns paged result set of OrgUnitValue data blocks
end

#get_all_config_var_org_unit_role_override_values(variable_id, bookmark = '') ⇒ Object

Retrieve all the role override values for a configuration variable.



61
62
63
64
65
66
# File 'lib/d2l_sdk/config_variables.rb', line 61

def get_all_config_var_org_unit_role_override_values(variable_id, bookmark='')
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/roles/"
  path += "?bookmark=#{bookmark}" if bookmark != ''
  _get(path)
  # returns paged result set with RoleValue JSON data blocks
end

#get_all_course_templatesObject

Instead of explicitly retrieving a single course template, this method uses the routing table to retrieve all of the organizations descendants with the outTypeId of 2. What this means is that it is literally retrieving any and all course templates that have an ancestor of the organization…which should be all of them.

returns: JSON array of course template data objects



73
74
75
76
77
# File 'lib/d2l_sdk/course_template.rb', line 73

def get_all_course_templates
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/6606/descendants/?ouTypeId=2"
    _get(path)
    # return: JSON array of course template data objects
end

#get_all_coursesObject



87
88
89
90
# File 'lib/d2l_sdk/course.rb', line 87

def get_all_courses
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/6606/descendants/?ouTypeId=3"
    _get(path)
end

#get_all_data_setsObject

Lists all available data sets



25
26
27
28
# File 'lib/d2l_sdk/datahub.rb', line 25

def get_all_data_sets
    _get("/d2l/api/lp/#{$lp_ver}/dataExport/list")
    # returns a JSON array of DataSetData blocks
end

#get_all_demographic_fields(bookmark = '') ⇒ Object

FIELDS retrieve list of all demographics fields



59
60
61
62
63
64
# File 'lib/d2l_sdk/demographics.rb', line 59

def get_all_demographic_fields(bookmark = '')
  path = "/d2l/api/lp/#{$lp_ver}/demographics/fields/"
  path += "#{bookmark}" if bookmark != ''
  _get(path)
  # returns paged result set of DemographicsField JSON blocks
end

#get_all_demographic_types(bookmark = '') ⇒ Object

retrieve the list of all demographics data types uses DataTypeId’s as a paging control value



77
78
79
80
81
82
# File 'lib/d2l_sdk/demographics.rb', line 77

def get_all_demographic_types(bookmark = '')
  path = "/d2l/api/lp/#{$lp_ver}/demographics/dataTypes/"
  path += "#{bookmark}" if bookmark != ''
  _get(path)
  # returns paged result set of DemographicsDataType JSON blocks
end

#get_all_demographics(field_ids = '', role_ids = '', user_ids = '', search = '', bookmark = '') ⇒ Object

retrieve all demographics entries for all users with specified filters



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/d2l_sdk/demographics.rb', line 44

def get_all_demographics(field_ids = '', role_ids = '', user_ids = '',
                         search = '', bookmark = '')
  path = "/d2l/api/lp/#{$lp_ver}/demographics/users/"
  path += "#{field_ids}" if field_ids != ''
  path += "#{role_ids}" if role_ids != ''
  path += "#{user_ids}" if user_ids != ''
  path += "#{search}" if search != ''
  path += "#{bookmark}" if bookmark != ''
  _get(path)
  # returns paged result set of DemographicsUserEntryData JSON blocks
end

#get_all_demographics_by_org_unit(org_unit_id, field_ids = '', role_ids = '', user_ids = '', search = '', bookmark = '') ⇒ Object

optional params: fieldIds, roleIds, and userIds are CSV formatted Strings

search and bookmark are Strings

retrieve all the demographics entries for all users enrolled in an OU



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/d2l_sdk/demographics.rb', line 23

def get_all_demographics_by_org_unit(org_unit_id, field_ids = '', role_ids = '',
                                     user_ids = '', search = '', bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/demographics/orgUnits/#{org_unit_id}/users/"
    path += "?fieldIds=" + field_ids if field_ids != ''
    path += "?roleIds=" + role_ids if role_ids != ''
    path += "?userIds=" + user_ids if user_ids != ''
    path += "?search=" + search if search != ''
    path += "?bookmark=" + bookmark if bookmark != ''
    _get(path)
    # returns paged result set of DemographicsUserEntryData JSON blocks
end

#get_all_demographics_by_org_unit_by_user(org_unit_id, user_id, field_ids = '') ⇒ Object

retrieve all the demographics entries for a specific user within an OU



36
37
38
39
40
41
# File 'lib/d2l_sdk/demographics.rb', line 36

def get_all_demographics_by_org_unit_by_user(org_unit_id, user_id, field_ids = '')
  path = "/d2l/api/lp/#{$lp_ver}/demographics/orgUnits/#{org_unit_id}/users/(#{user_id})"
  path += "#{field_ids}" if field_ids != ''
  _get(path)
  # returns DemographicsUserEntryData JSON block
end

#get_all_enrollments_of_current_user(bookmark = '', sort_by = '', is_active = nil, start_date_time = '', end_date_time = '', can_access = nil) ⇒ Object

Retrieve the list of all enrollments for the current user Optional params: –orgUnitTypeId: CSV of D2LIDs –bookmark: String –sortBy: string –isActive: bool –startDateTime: UTCDateTime –endDateTime: UTCDateTime –canAccess: bool



97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/d2l_sdk/enroll.rb', line 97

def get_all_enrollments_of_current_user(bookmark = '', sort_by = '', is_active = nil,
                                        start_date_time = '', end_date_time = '',
                                        can_access = nil)
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/myenrollments/"
    path += "?bookmark=#{bookmark}" if bookmark != ''
    path += "?sortBy=#{sort_by}" if sort_by != ''
    path += "?isActive=#{is_active}" if is_active != nil
    path += "?startDateTime=#{start_date_time}" if start_date_time != ''
    path += "?endDateTime=#{end_date_time}" if end_date_time != ''
    path += "?canAccess=#{can_access}" if can_access != nil
    _get(path)
    # Returns: paged result set containing the resulting MyOrgUnitInfo data blocks
end

#get_all_enrollments_of_user(user_id, org_unit_type_id = 0, role_id = 0, bookmark = '') ⇒ Object

Retrieve a list of all enrollments for the provided user. Optional params: –orgUnitTypeId (CSV of D2LIDs) –roleId: D2LIDs –bookmark: string



48
49
50
51
52
53
54
55
56
# File 'lib/d2l_sdk/enroll.rb', line 48

def get_all_enrollments_of_user(user_id, org_unit_type_id = 0, role_id = 0,
                                bookmark = '')
    path = "/d2l/api/lp/1.3/enrollments/users/#{user_id}/orgUnits/"
    path += "?orgUnitTypeId=#{org_unit_type_id}" if org_unit_type_id != 0
    path += "?roleId=#{role_id}" if role_id != 0
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # Returns: paged result set w/ the resulting UserOrgUnit data blocks
end

#get_all_export_jobs(bookmark = '') ⇒ Object

List all available export jobs that you have previously submitted



82
83
84
85
86
87
# File 'lib/d2l_sdk/datahub.rb', line 82

def get_all_export_jobs(bookmark = '') # optional parameter page -- integer
    path = "/d2l/api/lp/#{$lp_ver}/dataExport/jobs"
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # returns: JSON array of paged ExportJobData blocks, sorted by SubmitDate
end

#get_all_group_category_groups(org_unit_id, group_category_id) ⇒ Object

Retrieve a list of all the groups in a specific group category for an OrgUnit



37
38
39
40
# File 'lib/d2l_sdk/group.rb', line 37

def get_all_group_category_groups(org_unit_id, group_category_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/"
  _get(path)
end

#get_all_logs(date_range_start, date_range_end, search = '', log_level = '', logger_assembly = '', user_id = 0, message_group_id = 0, include_traces = nil, org_unit_id = 0, bookmark = '') ⇒ Object

retrieve all current log messages with MANY parameters possible for filtering. REQUIRED PARAMS: date_range_start; date_range_end logLevel is CSV formatted, so simple delimit each value with a comma



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/d2l_sdk/logging.rb', line 11

def get_all_logs(date_range_start, date_range_end, search = '', log_level = '',
                 logger_assembly = '', user_id = 0, message_group_id = 0,
                 include_traces = nil, org_unit_id = 0, bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/logging/"
    path += "?dateRangeStart=#{date_range_start}"
    path += "&dateRangeEnd=#{date_range_end}"
    path += "&search=#{search}" if search != ''
    path += "&logLevel=#{log_level}" if log_level != ''
    path += "&loggerAssembly=#{logger_assembly}" if logger_assembly != ''
    path += "&userId=#{user_id}" if user_id != 0
    path += "&messageGroupId=#{message_group_id}" if message_group_id != 0
    path += "&includeTraces=#{include_traces}" if include_traces != nil
    path += "&orgUnitId=#{org_unit_id}" if org_unit_id != 0
    path += "&bookmark=#{bookmark}" if bookmark != ''
    ap path
    _get(path)
    # returns paged result set of Message data blocks
end

#get_all_message_group_logs(date_range_start, date_range_end, search = '', log_level = '', logger_assembly = '', user_id = 0, message_group_id = 0, org_unit_id = 0, bookmark = '') ⇒ Object

retrieve all current log arranged in message groups REQUIRED PARAMS: date_range_start; date_range_end logLevel is CSV formatted, so simple delimit each value with a comma



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/d2l_sdk/logging.rb', line 33

def get_all_message_group_logs(date_range_start, date_range_end, search = '',
                               log_level = '', logger_assembly = '', user_id = 0,
                               message_group_id = 0, org_unit_id = 0,
                               bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/logging/grouped/"
    path += "?dateRangeStart=#{date_range_start}"
    path += "&dateRangeEnd=#{date_range_end}"
    path += "&search=#{search}" if search != ''
    path += "&logLevel=#{log_level}" if log_level != ''
    path += "&loggerAssembly=#{logger_assembly}" if logger_assembly != ''
    path += "&userId=#{user_id}" if user_id != 0
    path += "&messageGroupId=#{message_group_id}" if message_group_id != 0
    path += "&orgUnitId=#{org_unit_id}" if org_unit_id != 0
    path += "&bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # returns paged result set of MessageGroupSummary data blocks
end

#get_all_notification_carrier_channelsObject

Notifications



335
336
337
338
# File 'lib/d2l_sdk/user.rb', line 335

def get_all_notification_carrier_channels
  path = "/d2l/api/lp/#{$lp_ver}/notifications/instant/carriers/"
  _get(path)
end

#get_all_org_unit_group_categories(org_unit_id) ⇒ Object

Retrieve a list of all the group categories for the provided org unit.



25
26
27
28
# File 'lib/d2l_sdk/group.rb', line 25

def get_all_org_unit_group_categories(org_unit_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/"
  _get(path)
end

#get_all_org_units_by_type_id(outype_id) ⇒ Object

Retrieves the org units that are a particular id. This is done by obtaining all of the children of the organization and then filtering by this id.

return: JSON array of all org units of an outype.



301
302
303
304
# File 'lib/d2l_sdk/org_unit.rb', line 301

def get_all_org_units_by_type_id(outype_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/6606/children/?ouTypeId=#{outype_id}"
    _get(path)
end

#get_all_orphans(org_unit_type = '', org_unit_code = '', org_unit_name = '', bookmark = '') ⇒ Object

Retrieves a paged result of all orphaned org units within the organization. This is a paged result, so only for the first 100 from the beginning bookmark are retrieved. Simply put, if the bookmark is not defined, it only gets the first 100 orphans.

return: JSON array of orphaned org units.



145
146
147
148
149
150
151
152
153
# File 'lib/d2l_sdk/org_unit.rb', line 145

def get_all_orphans(org_unit_type = '', org_unit_code = '', org_unit_name = '',
                    bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/orphans/"
    path += "?orgUnitType=#{org_unit_type}" if org_unit_type != ''
    path += "?orgUnitCode=#{org_unit_code}" if org_unit_code != ''
    path += "?orgUnitName=#{org_unit_name}" if org_unit_name != ''
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
end

#get_all_outypesObject

retrieves all outypes that are known and visible. This is returned as a JSON array of orgunittype data blocks.



344
345
346
347
# File 'lib/d2l_sdk/org_unit.rb', line 344

def get_all_outypes
    path = "/d2l/api/lp/#{$lp_ver}/outypes/"
    _get(path)
end

#get_all_products_supported_versionsObject

Versions######



161
162
163
164
165
# File 'lib/d2l_sdk/requests.rb', line 161

def get_all_products_supported_versions
  path = "/d2l/api/versions/"
  _get(path)
  # returns array of product codes in a JSON block
end

#get_all_semestersObject

This retrieves all semesters via getting all children from the main organization and filtering them by the default data type of semesters.

Returns: Array of all semester JSON formatted data



37
38
39
40
# File 'lib/d2l_sdk/semester.rb', line 37

def get_all_semesters
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/6606/children/?ouTypeId=5"
    _get(path)
end

#get_all_subscriptions_by_carrier(carrier_id) ⇒ Object



340
341
342
343
# File 'lib/d2l_sdk/user.rb', line 340

def get_all_subscriptions_by_carrier(carrier_id)
  path = "/d2l/api/lp/#{$lp_ver}/notifications/instant/carriers/#{carrier_id}/subscriptions/"
  _get(path)
end

#get_all_user_rolesObject

retrieve list of all known user roles



282
283
284
285
286
# File 'lib/d2l_sdk/user.rb', line 282

def get_all_user_roles
  path = "/d2l/api/lp/#{$lp_ver}/roles/"
  _get(path)
  # returns a JSON array of Role data blocks
end

#get_base64_hash_string(key, signature) ⇒ Object

uses the key and signature as arguments to create a hash using OpenSSL::HMAC.digest with an additional argument denoting the hashing algorithm as ‘sha256’. The hash is then encoded properly and all “=” are deleted to officially create a base64 hash string.

returns: String::base64_hash_string



73
74
75
76
77
# File 'lib/d2l_sdk/auth.rb', line 73

def get_base64_hash_string(key, signature)
    hash = OpenSSL::HMAC.digest('sha256', key, signature)
    Base64.urlsafe_encode64(hash).delete('=')
    # returns: String::base64_hash_string
end

#get_bookmarked_topics(org_unit_id) ⇒ Object

Retrieve a list of topics that have been bookmarked.



316
317
318
319
320
# File 'lib/d2l_sdk/course_content.rb', line 316

def get_bookmarked_topics(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/bookmarks"
  _get(query_string)
  # Returns: a JSON array of Topic ToC entries.
end

#get_config_var_current_org_value(variable_id) ⇒ Object

Retrieve the current org value for a configuration variable.



32
33
34
35
36
# File 'lib/d2l_sdk/config_variables.rb', line 32

def get_config_var_current_org_value(variable_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/org"
  _get(path)
  # returns OrgValue JSON data block
end

#get_config_var_definitions(variable_id) ⇒ Object

Retrieve the definitions for a configuration variable.



18
19
20
21
22
# File 'lib/d2l_sdk/config_variables.rb', line 18

def get_config_var_definitions(variable_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/(#{variable_id}/definition"
  _get(path)
  # returns Definition JSON data block
end

#get_config_var_org_unit_effective_value(variable_id, org_unit_id) ⇒ Object

Retrieve the effective value for a configuration variable within an org unit.



54
55
56
57
58
# File 'lib/d2l_sdk/config_variables.rb', line 54

def get_config_var_org_unit_effective_value(variable_id, org_unit_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/effectiveValues/orgUnits/#{org_unit_id}"
  _get(path)
  # returns OrgUnitValue JSON block
end

#get_config_var_org_unit_override_value(variable_id, org_unit_id) ⇒ Object

Retrieve an org unit override value for a configuration variable.



47
48
49
50
51
# File 'lib/d2l_sdk/config_variables.rb', line 47

def get_config_var_org_unit_override_value(variable_id, org_unit_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/orgUnits/#{org_unit_id}"
  _get(path)
  # returns OrgUnitValue JSON block
end

#get_config_var_resolver(variable_id) ⇒ Object



78
79
80
81
# File 'lib/d2l_sdk/config_variables.rb', line 78

def get_config_var_resolver(variable_id)
  path = "/d2l/api/lp/#{lp_ver}/configVariables/#{variable_id}/resolver"
  _get(path)
end

#get_config_var_role_override_value(variable_id, role_id) ⇒ Object



68
69
70
71
# File 'lib/d2l_sdk/config_variables.rb', line 68

def get_config_var_role_override_value(variable_id, role_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/roles/#{role_id}"
  _get(path)
end

#get_config_var_system_value(variable_id) ⇒ Object



73
74
75
76
# File 'lib/d2l_sdk/config_variables.rb', line 73

def get_config_var_system_value(variable_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values/system"
  _get(path)
end

#get_config_var_values(variable_id) ⇒ Object

Retrieve the value summary for a configuration variable.



25
26
27
28
29
# File 'lib/d2l_sdk/config_variables.rb', line 25

def get_config_var_values(variable_id)
  path = "/d2l/api/lp/#{$lp_ver}/configVariables/#{variable_id}/values"
  _get(path)
  # returns Values JSON data block
end

#get_copy_job_request_status(org_unit_id, job_token) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
# File 'lib/d2l_sdk/course.rb', line 250

def get_copy_job_request_status(org_unit_id, job_token)
    path = "/d2l/api/le/#{le_ver}/import/#{org_unit_id}/copy/#{job_token}"
    _get(path)
    # returns GetCopyJobResponse JSON block
    # GetImportJobResponse:
    # {"JobToken" => <string:COPYJOBSTATUS_T>,
    #  "TargetOrgUnitID" => <number:D2LID>,
    #  "Status" => <string:IMPORTJOBTSTATUS_T>}
    # States of getImport: UPLOADING, PROCESSING, PROCESSED, IMPORTING,
    #                      IMPORTFAILED, COMPLETED
end

#get_course_by_id(org_unit_id) ⇒ Object

Performs a get request to retrieve a particular course using the org_unit_id of this particular course. If the course does not exist, as specified by the org_unit_id, the response is typically a 404 error.

returns: JSON object of the course



81
82
83
84
85
# File 'lib/d2l_sdk/course.rb', line 81

def get_course_by_id(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/courses/#{org_unit_id}"
    _get(path)
    # returns: JSON object of the course
end

#get_course_image(org_unit_id, width = 0, height = 0) ⇒ Object



304
305
306
307
308
309
310
311
# File 'lib/d2l_sdk/course.rb', line 304

def get_course_image(org_unit_id, width = 0, height = 0)
  path = "/d2l/api/lp/#{lp_ver}/courses/#{org_unit_id}/image"
  if width > 0 && height > 0
    path += "?width=#{width}"
    path += "&height=#{height}"
  end
  _get(path)
end

#get_course_import_job_request_logs(org_unit_id, job_token, bookmark = '') ⇒ Object



280
281
282
283
284
285
# File 'lib/d2l_sdk/course.rb', line 280

def get_course_import_job_request_logs(org_unit_id, job_token, bookmark = '')
  path = "/d2l/api/le/#{le_ver}/import/#{org_unit_id}/imports/#{job_token}/logs"
  path += "?bookmark=#{bookmark}" if bookmark != ''
  _get(path)
  # returns PAGED RESULT of ImportCourseLog JSON blocks following bookmark param
end

#get_course_import_job_request_status(org_unit_id, job_token) ⇒ Object

def create_course_import_request(org_unit_id, callback_url = ”)

path = "/d2l/le/#{le_ver}/import/#{org_unit_id}/imports/"
path += "?callbackUrl=#{callback_url}" if callback_url != ''
#_post(path, payload)
#_upload(path, json, file, 'POST', 'file', filename)

end



271
272
273
274
275
276
277
278
# File 'lib/d2l_sdk/course.rb', line 271

def get_course_import_job_request_status(org_unit_id, job_token)
  path = "/d2l/api/le/#{le_ver}/import/#{org_unit_id}/imports/#{job_token}"
  _get(path)
  # returns GetImportJobResponse JSON block
  # example:
  # {"JobToken" => <string:COPYJOBSTATUS_T>}
  # States: PENDING, PROCESSING, COMPLETE, FAILED, CANCELLED
end

#get_course_overview(org_unit_id) ⇒ Object

Retrieve the overview for a course offering.



208
209
210
211
212
213
# File 'lib/d2l_sdk/course_content.rb', line 208

def get_course_overview(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/overview"
  _get(query_string)
  # Returns: a Overview JSON data block containing
  # the course offering overview’s details.
end

#get_course_overview_file_attachment(org_unit_id) ⇒ Object

Retrieve the overview file attachment for a course offering.



216
217
218
219
220
# File 'lib/d2l_sdk/course_content.rb', line 216

def get_course_overview_file_attachment(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/overview/attachment"
  _get(query_string)
  # Returns: a file stream containing the course offering’s overview attachment.
end

#get_course_template(org_unit_id) ⇒ Object

Retrieves a course template based upon an explicitly defined course template org_unit_id or Identifier. This is done by using the identifier as a component of the path, and then performing a GET http method that is then returned.

returns: JSON course template data /d2l/api/lp/(version)/coursetemplates/(orgUnitId) [GET]



60
61
62
63
64
# File 'lib/d2l_sdk/course_template.rb', line 60

def get_course_template(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/coursetemplates/#{org_unit_id}"
    _get(path)
    # return: JSON course template data
end

#get_course_template_by_name(org_unit_name) ⇒ Object

This method retrieves all course templates that have a specific string, as specified by org_unit_name, within their names. This is done by first defining that none are found yet and initializing an empty array. Then, by searching through all course templates for ones that do have a particular string within their name, the matches are pushed into the previously empty array of matches. This array is subsequently returned; if none were found, a message is returned

returns: JSON array of matching course template data objects



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/d2l_sdk/course_template.rb', line 87

def get_course_template_by_name(org_unit_name)
    course_template_not_found = true
    course_template_results = []
    puts "[+] Searching for templates using search string: \'#{org_unit_name}\'".yellow
    results = get_all_course_templates
    results.each do |x|
        if x['Name'].downcase.include? org_unit_name.downcase
            course_template_not_found = false
            course_template_results.push(x)
        end
    end
    if course_template_not_found
        puts '[-] No templates could be found based upon the search string.'.yellow
    end
    course_template_results
    # return: JSON array of matching course template data objects
end

#get_course_templates_schemaObject

Moreso a helper method, but this really just returns the schema of the course templates. This is predefined in the routing table, and retrieved via a GET http method.

returns: JSON of course templates schema /d2l/api/lp/(version)/coursetemplates/schema [GET]



111
112
113
114
115
# File 'lib/d2l_sdk/course_template.rb', line 111

def get_course_templates_schema
    path = "/d2l/api/lp/#{$lp_ver}/coursetemplates/schema"
    _get(path)
    # This action returns a JSON array of SchemaElement blocks.
end

#get_courses_by_code(org_unit_code) ⇒ Object

much slower means of getting courses if less than 100 courses



93
94
95
96
97
98
99
100
# File 'lib/d2l_sdk/course.rb', line 93

def get_courses_by_code(org_unit_code)
  all_courses = get_all_courses
  courses = []
  all_courses.each do |course|
    courses.push(course) if course["Code"].downcase.include? "#{org_unit_code}".downcase
  end
  courses
end

#get_courses_by_name(org_unit_name) ⇒ Object

returns: JSON array of matching course data objects



108
109
110
# File 'lib/d2l_sdk/course.rb', line 108

def get_courses_by_name(org_unit_name)
    get_courses_by_property_by_string('Name', org_unit_name)
end

#get_courses_by_property_by_regex(property, regex) ⇒ Object

Retrieves all courses that have the specified prop match a regular expression. This is done by iterating through all courses and returning an array of all that match a regular expression.

returns: array of JSON course objects (with property that matches regex)



139
140
141
142
143
144
145
146
147
148
149
# File 'lib/d2l_sdk/course.rb', line 139

def get_courses_by_property_by_regex(property, regex)
    puts "[+] Searching for courses using regex: #{regex}".yellow +
         + " -- And property: #{property}"
    courses_results = []
    results = get_all_courses
    results.each do |x|
        courses_results.push(x) if (x[property] =~ regex) != nil
    end
    courses_results
    # returns array of all matching courses in JSON format.
end

#get_courses_by_property_by_string(property, search_string) ⇒ Object

Retrieves all matching courses that are found using a property and a search string. First, it is considered that the class is not found. Then, all courses are retrieved and stored as a JSON array in the varaible results. After this each of the results is iterated, downcased, and checked for their matching of the particular search string. If there is a match, they are pushed to an array called courses_results. This is returned at the end of this op.

returns: array of JSON course objects (that match the search string/property)



120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/d2l_sdk/course.rb', line 120

def get_courses_by_property_by_string(property, search_string)
    puts "[+] Searching for courses using search string: #{search_string}".yellow +
         + " -- And property: #{property}"
    courses_results = []
    results = get_all_courses
    results.each do |x|
        if x[property].downcase.include? search_string.downcase
            courses_results.push(x)
        end
    end
    courses_results
    # returns array of all matching courses in JSON format.
end

#get_current_courses(csv_fname) ⇒ Object

Get all ‘current’ courses, assuming all instr courses are current and add their sec/off course_term_star_num codes to a set. return: set of current classes formatted as “#course_term_#star_number”



163
164
165
166
167
168
169
170
171
172
# File 'lib/d2l_sdk/datahub.rb', line 163

def get_current_courses(csv_fname)
  puts "Retrieving current courses from #{csv_fname}"
  instr_courses = Set.new
  CSV.foreach(csv_fname, :headers => true) do |row|
    star_number = row[0]
    course_term = row[10]
    instr_courses.add("#{course_term}_#{star_number}")
  end
  instr_courses
end

#get_current_user_feed(since = "", _until = "") ⇒ Object

if since not specified, only includes most ‘recent’ feed items if since specified but until is not, all items since ‘since’ are fetched if since and until are specified, all items between these two dates are fetched if since > until, an empty feed list is returned purpose: fetch the feed for the current user context



12
13
14
15
16
17
18
19
20
# File 'lib/d2l_sdk/news.rb', line 12

def get_current_user_feed(since = "", _until = "")
  path = "/d2l/api/lp/#{$lp_ver}/feed/"
  # if since is specified, then until can be. Until is not required though.
  if since != ""
    path += "?since=#{since}"
    path += "&until=#{_until}" if _until != ""
  end
  _get(path)
end

#get_current_user_overdue_items(org_unit_ids_CSV = nil) ⇒ Object

Retrieves the calling user’s overdue items, within a number of org units. org_unit_ids_CSV is a CSV of D2LIDs or rather Org unit IDs (optional) Returns: An ObjectListPage JSON block containing a list of OverdueItem. NOTE: If using a support account, try not to use this without defining a csv…

It will consider all courses designated as somehow linked to the acc.
and return ALL overdue items EVER for the support .


304
305
306
307
308
309
# File 'lib/d2l_sdk/course_content.rb', line 304

def get_current_user_overdue_items(org_unit_ids_CSV = nil) # GET
  query_string = "/d2l/api/le/#{$le_ver}/overdueItems/myItems"
  query_string += "?orgUnitIdsCSV=#{org_unit_ids_CSV}" unless org_unit_ids_CSV.nil?
  _get(query_string)
  # Returns: An ObjectListPage JSON block containing a list of OverdueItem.
end

#get_current_user_profileObject

retrieve personal profile info for the current user context



297
298
299
300
301
# File 'lib/d2l_sdk/user.rb', line 297

def 
  path = "/d2l/api/lp/#{$lp_ver}/profile/myProfile"
  _get(path)
  # Returns UserProfile JSON data block
end

#get_current_user_profile_image(size = 0) ⇒ Object



323
324
325
326
327
# File 'lib/d2l_sdk/user.rb', line 323

def (size = 0)
  path = "/d2l/api/lp/#{$lp_ver}/profile/myProfile/image"
  path += "?size=#{size}" if size != 0
  _get(path)
end

#get_current_user_progress(org_unit_id, level) ⇒ Object

Retrieves the aggregate count of completed and required content topics in an org unit for the calling user. levels: 1=OrgUnit, 2=RootModule, 3=Topic



343
344
345
346
347
348
349
# File 'lib/d2l_sdk/course_content.rb', line 343

def get_current_user_progress(org_unit_id, level) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/completions/mycount/"
  query_string += "?level=#{level}"
  _get(query_string)
  # Returns: ObjectListPage JSON block containing
  # a list of ContentAggregateCompletion items.
end

#get_data_export_job(export_job_id) ⇒ Object

Retrieves information about a data export job that you have previously submitted.



90
91
92
93
# File 'lib/d2l_sdk/datahub.rb', line 90

def get_data_export_job(export_job_id)
    _get("/d2l/api/lp/#{$lp_ver}/dataExport/jobs/#{export_job_id}")
    # returns: ExportJobData JSON block
end

#get_data_set(data_set_id) ⇒ Object

Retrieve a data set



31
32
33
34
# File 'lib/d2l_sdk/datahub.rb', line 31

def get_data_set(data_set_id)
    _get("/d2l/api/lp/#{$lp_ver}/dataExport/list/#{data_set_id}")
    # returns a DataSetData JSON block
end

#get_demographic_field(field_id) ⇒ Object

retrieve a single demographic field



67
68
69
70
71
# File 'lib/d2l_sdk/demographics.rb', line 67

def get_demographic_field(field_id)
  path = "/d2l/api/lp/#{$lp_ver}/demographics/fields/#{field_id}"
  _get(path)
  # returns fetch form of DemographicsField JSON block
end

#get_demographic_type(data_type_id) ⇒ Object

retrieve a single demographic data type



85
86
87
88
89
# File 'lib/d2l_sdk/demographics.rb', line 85

def get_demographic_type(data_type_id)
  path = "/d2l/api/lp/#{$lp_ver}/demographics/dataTypes/#{data_type_id}"
  _get(path)
  # returns DemographicsDataType JSON block
end

#get_department_outypeObject

retrieve org unit type of department org units



372
373
374
375
376
# File 'lib/d2l_sdk/org_unit.rb', line 372

def get_department_outype
  path = "/d2l/api/lp/#{$lp_ver}/outypes/department"
  _get(path)
  # returns OrgUnitType JSON data block
end

#get_enrolled_roles_in_org_unit(org_unit_id) ⇒ Object

Retrieve a list of all the enrolled user roles the calling user can view in an org unit



273
274
275
276
277
278
279
# File 'lib/d2l_sdk/user.rb', line 273

def get_enrolled_roles_in_org_unit(org_unit_id)
  # this only lists ones viewable by the CALLING user
  # also, only includes roles that are enrolled in the org unit
  path = "/d2l/api/#{$lp_ver}/#{org_unit_id}/roles/"
  _get(path)
  # returns JSON array of Role data blocks
end

#get_enrolled_users_in_classlist(org_unit_id) ⇒ Object

Retrieve the enrolled users in the classlist for an org unit



112
113
114
115
116
# File 'lib/d2l_sdk/enroll.rb', line 112

def get_enrolled_users_in_classlist(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/classlist/"
    _get(path)
    # Returns: JSON array of ClasslistUser data blocks.
end

#get_enrollments_details_of_current_userObject

Retrieve the enrollment details for the current user in the provided org unit.



82
83
84
85
86
# File 'lib/d2l_sdk/enroll.rb', line 82

def get_enrollments_details_of_current_user
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/myenrollments/org_unit_id/"
    _get(path)
    # Returns: MyOrgUnitInfo JSON block.
end

#get_isbn_org_unit_association(org_unit_id, isbn) ⇒ Object

Retrieve the association between a ISBN and org unit.



249
250
251
252
253
254
# File 'lib/d2l_sdk/course_content.rb', line 249

def get_isbn_org_unit_association(org_unit_id, isbn) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}content/isbn/#{isbn}"
  _get(query_string)
  # Returns: a IsbnAssociation JSON data block specifying
  # the association between an org unit and an ISBN.
end

#get_isbns_of_org_unit(org_unit_id) ⇒ Object

Retrieve all ISBNs associated with an org unit.



241
242
243
244
245
246
# File 'lib/d2l_sdk/course_content.rb', line 241

def get_isbns_of_org_unit(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}content/isbn/"
  _get(query_string)
  # Returns: JSON array of IsbnAssociation data blocks specifying
  # all the org units associated with the provided ISBN.
end

#get_job_status_code(export_job_id) ⇒ Object



95
96
97
# File 'lib/d2l_sdk/datahub.rb', line 95

def get_job_status_code(export_job_id)
  get_data_export_job(export_job_id)["Status"] #if 2 is OKAY/COMPLETED
end

#get_latest_product_version(product_code) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/d2l_sdk/requests.rb', line 173

def get_latest_product_version(product_code)
  begin
    get_product_supported_versions(product_code)["SupportedVersions"][-1]
  rescue SocketError => e
    puts "\n[!] Error likely caused by an incorrect 'd2l_config.json' hostname value: #{e}"
    exit
  rescue NoMethodError => e
    puts "\n[!] Error likely caused by incorrect 'd2l_config.json' api or user values: #{e}"
    exit
  end
end

#get_log_message(log_message_id, include_traces = nil) ⇒ Object

retrieve identified log message



52
53
54
55
56
57
# File 'lib/d2l_sdk/logging.rb', line 52

def get_log_message(log_message_id, include_traces = nil)
  path = "/d2l/api/lp/#{$lp_ver}/logging/#{log_message_id}/"
  path += "?includeTraces=#{include_traces}" if include_traces != nil
  _get(path)
  # returns Message JSON block
end

#get_module(org_unit_id, module_id) ⇒ Object

Retrieve a specific module for an org unit. Returns ContentObject JSON data block of type Module



20
21
22
23
# File 'lib/d2l_sdk/course_content.rb', line 20

def get_module(org_unit_id, module_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/modules/#{module_id}"
  _get(query_string)
end

#get_module_structure(org_unit_id, module_id) ⇒ Object

Retrieve the structure for a specific module in an org unit. Returns JSON array of ContentObject data blocks (either Module or Topic)



27
28
29
30
# File 'lib/d2l_sdk/course_content.rb', line 27

def get_module_structure(org_unit_id, module_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/modules/#{module_id}/structure/"
  _get(query_string)
end

#get_most_recently_visited_topics(org_unit_id) ⇒ Object

Retrieve a list of the most recently visited topics.



323
324
325
326
327
# File 'lib/d2l_sdk/course_content.rb', line 323

def get_most_recently_visited_topics(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/recent"
  _get(query_string)
  # Returns: a JSON array of Topic ToC entries.
end

#get_org_department_classes(org_unit_id) ⇒ Object

In order to retrieve an entire department’s class list, this method uses a predefined org_unit identifier. This identifier is then appended to a path and all classes withiin the department are returned as JSON objects in an arr.

returns: JSON array of classes.



70
71
72
73
74
# File 'lib/d2l_sdk/course.rb', line 70

def get_org_department_classes(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}"
    _get(path)
    # returns: JSON array of classes.
end

#get_org_unit_ancestors(org_unit_id, ou_type_id = 0) ⇒ Object

Gets all org unit ancestors. Simply, this method references all of the ancestors of the particular org unit and then returns them in a JSON array.

return: JSON array of org_unit ancestors.



56
57
58
59
60
61
# File 'lib/d2l_sdk/org_unit.rb', line 56

def get_org_unit_ancestors(org_unit_id, ou_type_id = 0)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/ancestors/"
    path += "?ouTypeId=#{ou_type_id}" if ou_type_id != 0
    _get(path)
    # return json of org_unit ancestors
end

#get_org_unit_children(org_unit_id, ou_type_id = 0) ⇒ Object

gets all children of a particular org unit, as referenced by the “org_unit_id” argument. A get request is then performed by a preformatted path.



66
67
68
69
70
71
# File 'lib/d2l_sdk/org_unit.rb', line 66

def get_org_unit_children(org_unit_id, ou_type_id = 0)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/children/"
    path += "?ouTypeId=#{ou_type_id}" if ou_type_id != 0
    _get(path)
    # return json of org_unit children
end

#get_org_unit_descendants(org_unit_id, ou_type_id = 0) ⇒ Object

gets all descendents of a particular org unit, as referenced by the “org_unit_id” argument. A get request is then performed by a preformatted path.



11
12
13
14
15
16
# File 'lib/d2l_sdk/org_unit.rb', line 11

def get_org_unit_descendants(org_unit_id, ou_type_id = 0)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/descendants/"
    path += "?ouTypeId=#{ou_type_id}" if ou_type_id != 0
    _get(path)
    # return JSON array of OrgUnit data blocks
end

#get_org_unit_enrollment_data_by_user(org_unit_id, user_id) ⇒ Object

Retrieve enrollment details for a user in the provided org unit. Note: Same as get_user_enrollment_data_by_org_unit This call is equivalent to the route that fetches by specifying the user first, and then the org unit.



63
64
65
66
67
# File 'lib/d2l_sdk/enroll.rb', line 63

def get_org_unit_enrollment_data_by_user(org_unit_id, user_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgUnits/#{org_unit_id}/users/#{user_id}"
    _get(path)
    # Returns: EnrollmentData JSON block.
end

#get_org_unit_enrollments(org_unit_id, role_id = 0, bookmark = '') ⇒ Object

Retrieve the collection of users enrolled in the identified org unit. Optional params: –roleId: D2LID –bookmark: String



73
74
75
76
77
78
79
# File 'lib/d2l_sdk/enroll.rb', line 73

def get_org_unit_enrollments(org_unit_id, role_id = 0, bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/orgUnits/#{org_unit_id}/users/"
    path += "?roleId=#{role_id}" if role_id != 0
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # Returns: paged result set containing the resulting OrgUnitUser data blocks
end

#get_org_unit_group(org_unit_id, group_category_id, group_id) ⇒ Object

Retrieve a particular group in an org unit.



43
44
45
46
# File 'lib/d2l_sdk/group.rb', line 43

def get_org_unit_group(org_unit_id, group_category_id, group_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/#{group_id}"
  _get(path)
end

#get_org_unit_group_category(org_unit_id, group_category_id) ⇒ Object

Retrieve a particular group category for an org unit.



31
32
33
34
# File 'lib/d2l_sdk/group.rb', line 31

def get_org_unit_group_category(org_unit_id, group_category_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}"
  _get(path)
end

#get_org_unit_parents(org_unit_id, ou_type_id = 0) ⇒ Object

gets all parents of a particular org unit, as referenced by the “org_unit_id” argument. A get request is then performed by a preformatted path.



34
35
36
37
38
39
# File 'lib/d2l_sdk/org_unit.rb', line 34

def get_org_unit_parents(org_unit_id, ou_type_id = 0)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/parents/"
    path += "?ouTypeId=#{ou_type_id}" if ou_type_id != 0
    _get(path)
    # return json of org_unit parents
end

#get_org_unit_properties(org_unit_id) ⇒ Object

gets all properties of a particular org unit, as referenced by the “org_unit_id” argument. A get request is then performed by a preformatted path.



88
89
90
91
92
# File 'lib/d2l_sdk/org_unit.rb', line 88

def get_org_unit_properties(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}"
    _get(path)
    # return json of org_unit properties
end

#get_org_unit_section_property_data(org_unit_id) ⇒ Object

Retrieve the section property data for an org unit.



74
75
76
77
78
# File 'lib/d2l_sdk/section.rb', line 74

def get_org_unit_section_property_data(org_unit_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/settings"
  _get(path)
    # returns a SectionPropertyData JSON block in the Fetch form.
end

#get_org_unit_sections(org_unit_id) ⇒ Object

Retrieve all the sections for a provided org unit.



67
68
69
70
71
# File 'lib/d2l_sdk/section.rb', line 67

def get_org_unit_sections(org_unit_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/"
  _get(path)
    # returns a JSON array of SectionData blocks in the Fetch form
end

#get_org_unit_toc(org_unit_id, ignore_module_data_restrictions = false) ⇒ Object

Retrieve the table of course content for an org unit.



330
331
332
333
334
335
# File 'lib/d2l_sdk/course_content.rb', line 330

def get_org_unit_toc(org_unit_id, ignore_module_data_restrictions = false) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/toc"
  query_string += "?ignoreModuleDateRestrictions=true" if ignore_module_data_restrictions
  _get(query_string)
  # Returns: a TableOfContents JSON block.
end

#get_org_units_of_isbn(isbn) ⇒ Object

Retrieve all the org units associated with an ISBN.



233
234
235
236
237
238
# File 'lib/d2l_sdk/course_content.rb', line 233

def get_org_units_of_isbn(isbn) # GET
  query_string = "/d2l/api/le/#{$le_ver}/content/isbn/#{isbn}"
  _get(query_string)
  # Returns: JSON array of IsbnAssociation data blocks specifying
  # all the org units associated with the provided ISBN.
end

#get_organization_infoObject

Retrieves the organization info. Only gets a small amount of information, but may be useful in some instances.



291
292
293
294
295
# File 'lib/d2l_sdk/org_unit.rb', line 291

def get_organization_info
    path = "/d2l/api/lp/#{$lp_ver}/organization/info"
    _get(path)
    # return: Organization JSON block
end

#get_outype(outype_id) ⇒ Object

This retrieves information about a partituclar org unit type, referenced via the outype_id argument. This is then returned as a JSON object.



337
338
339
340
# File 'lib/d2l_sdk/org_unit.rb', line 337

def get_outype(outype_id)
    path = "/d2l/api/lp/#{$lp_ver}/outypes/#{outype_id}"
    _get(path)
end

#get_paged_org_unit_children(org_unit_id, bookmark = '') ⇒ Object

Gets all children of the org unit, but in a paged result. These are first referenced via the org_unit_id argument, and then a bookmark is appended if there is one specified. This is then returned as a json array.

return: JSON array of org unit children.



78
79
80
81
82
83
# File 'lib/d2l_sdk/org_unit.rb', line 78

def get_paged_org_unit_children(org_unit_id, bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/children/paged/"
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # return json of org_unit children
end

#get_paged_org_unit_descendants(org_unit_id, ou_type_id = 0, bookmark = '') ⇒ Object

gets a paged result of the org unit’s descendants. The descendants are first referenced by a preformatted path; then if there is a defined bookmark, the bookmark parameter is appended to the path.

return: JSON array of org unit descendants (paged)



23
24
25
26
27
28
29
# File 'lib/d2l_sdk/org_unit.rb', line 23

def get_paged_org_unit_descendants(org_unit_id, ou_type_id = 0, bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}/descendants/paged/"
    path += "?ouTypeId=#{ou_type_id}" if ou_type_id != 0
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # return paged json of org_unit descendants
end

#get_parent_outypes_courses_schema_constraintsObject

retrieve the list of parent org unit type constraints for course offerings



298
299
300
301
302
# File 'lib/d2l_sdk/course.rb', line 298

def get_parent_outypes_courses_schema_constraints
  path = "/d2l/api/lp/#{$lp_ver}/courses/schema"
  _get(path)
  # returns a JSON array of SchemaElement blocks
end

#get_product_supported_versions(product_code) ⇒ Object

Retrieve the collection of versions supported by a specific product component



168
169
170
171
# File 'lib/d2l_sdk/requests.rb', line 168

def get_product_supported_versions(product_code)
  path = "/d2l/api/#{product_code}/versions/"
  _get(path)
end

#get_profile_image(profile_id, size = 0) ⇒ Object



317
318
319
320
321
# File 'lib/d2l_sdk/user.rb', line 317

def get_profile_image(profile_id, size = 0)
  path = "/d2l/api/lp/#{$lp_ver}/profile/#{profile_id}/image"
  path += "?size=#{size}" if size != 0
  _get(path)
end

#get_properties_of_all_org_units(org_unit_type = '', org_unit_code = '', org_unit_name = '', bookmark = '') ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
# File 'lib/d2l_sdk/org_unit.rb', line 127

def get_properties_of_all_org_units(org_unit_type = '', org_unit_code = '', org_unit_name = '',
                                bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/"
    path += "?orgUnitType=#{org_unit_type}" if org_unit_type != ''
    path += "?orgUnitCode=#{org_unit_code}" if org_unit_code != ''
    path += "?orgUnitName=#{org_unit_name}" if org_unit_name != ''
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # ONLY RETRIEVES FIRST 100 after bookmark
    # returns: paged result of OrgUnitProperties blocks
end

#get_recycled_org_units(bookmark = '') ⇒ Object

Retrieves a paged result of all recycled org units. Thus, only the first 100 are retrieved since the first referenced org unit. As such, if the bookmark is not defined, then it only retrieves the first 100.

return: JSON array of recycled org units.



171
172
173
174
175
176
# File 'lib/d2l_sdk/org_unit.rb', line 171

def get_recycled_org_units(bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/recyclebin/"
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # GETS ONLY FIRST 100
end

#get_root_modules(org_unit_id) ⇒ Object

Retrieve the root module(s) for an org unit. Returns JSON array of ContentObject data blocks of type Module



34
35
36
37
# File 'lib/d2l_sdk/course_content.rb', line 34

def get_root_modules(org_unit_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/root/"
  _get(query_string)
end

#get_section_by_section_code(code) ⇒ Object



21
22
23
# File 'lib/d2l_sdk/section.rb', line 21

def get_section_by_section_code(code)
  _get("/d2l/api/lp/1.4/orgstructure/?orgUnitCode=#{code}")["Items"][0]
end

#get_section_data(org_unit_id, section_id) ⇒ Object

Retrieve a section from a particular org unit.



81
82
83
84
85
# File 'lib/d2l_sdk/section.rb', line 81

def get_section_data(org_unit_id, section_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/#{section_id}"
  _get(path)
    # returns a SectionData JSON block in the Fetch form.
end

#get_section_data_by_code(code) ⇒ Object



29
30
31
32
33
# File 'lib/d2l_sdk/section.rb', line 29

def get_section_data_by_code(code)
    sect_id = get_section_by_section_code(code)["Identifier"]
    parent_id = get_org_unit_parents(sect_id)[0]["Identifier"]
    get_section_data(parent_id, sect_id)
end

#get_section_id_by_section_code(code) ⇒ Object



25
26
27
# File 'lib/d2l_sdk/section.rb', line 25

def get_section_id_by_section_code(code)
  get_section_by_section_code(code)["Identifier"]
end

#get_semester_by_id(org_unit_id) ⇒ Object

Retrieves a semester by a particular id. This is done by referencing it by its org unit id in the organization and then performing a get request on it.

return: JSON of org unit properties.



46
47
48
49
50
# File 'lib/d2l_sdk/semester.rb', line 46

def get_semester_by_id(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/" + org_unit_id.to_s
    _get(path)
    # return json of org_unit properties
end

#get_semester_by_name(search_string) ⇒ Object

Rather than retrieving all semesters, this retrieves all semesters by a particular string. First, a boolean is created where it is assumed the semester is not found. Then an array is created with all the ‘found’ semesters assuming none are found, but providing the structure to still return uniform data that can be iterated. Then, by iterating through all semesters and only storing ones that conform to the search string, all matched semesters are then returned.

Returns: Array of all semester JSON formatted data (with search string in name)



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/d2l_sdk/semester.rb', line 75

def get_semester_by_name(search_string)
    semester_not_found = true
    semester_results = []
    puts "[+] Searching for semesters using search string: \'#{search_string}\'".yellow
    results = get_all_semesters
    results.each do |x|
        if x['Name'].downcase.include? search_string.downcase
            semester_not_found = false
            semester_results.push(x)
        end
    end
    if semester_not_found
        puts '[-] No semesters could be found based upon the search string.'.yellow
    end
    semester_results
end

#get_semester_outypeObject

retrieve org unit type of semester org units



379
380
381
382
383
# File 'lib/d2l_sdk/org_unit.rb', line 379

def get_semester_outype
  path = "/d2l/api/lp/#{$lp_ver}/outypes/semester"
  _get(path)
  # returns OrgUnitType JSON data block
end

#get_topic(org_unit_id, topic_id) ⇒ Object

Retrieve a specific topic for an org unit. Returns a ContentObject JSON data block of type Topic



41
42
43
44
# File 'lib/d2l_sdk/course_content.rb', line 41

def get_topic(org_unit_id, topic_id) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/topics/#{topic_id}"
  _get(query_string)
end

#get_topic_file(org_unit_id, topic_id, stream = false) ⇒ Object

Retrieve the content topic file for a content topic. Returns underlying file for a file content topic



48
49
50
51
52
# File 'lib/d2l_sdk/course_content.rb', line 48

def get_topic_file(org_unit_id, topic_id, stream = false) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/topics/#{topic_id}/file"
  query_string += "?stream=true" if stream == true
  _get(query_string)
end

#get_user_by_user_id(user_id) ⇒ Object

Retrieves a user based upon an explicitly pre-defined user_id. This is also known as the Identifier of this user object. Upon retrieving the user, it is then returned.

returns: JSON user object.



197
198
199
200
201
202
# File 'lib/d2l_sdk/user.rb', line 197

def get_user_by_user_id(user_id)
    # Retrieve data for a particular user
    path = "/d2l/api/lp/#{$lp_ver}/users/#{user_id}"
    _get(path)
    # returns a UserData JSON block
end

#get_user_by_username(username) ⇒ Object

Retrieves a user based upon an explicitly defined username. Returns: JSON response of this user.



88
89
90
# File 'lib/d2l_sdk/user.rb', line 88

def get_user_by_username(username)
    get_users('', username)
end

#get_user_enrollment_data_by_org_unit(user_id, org_unit_id) ⇒ Object

Retrieve enrollment details in an org unit for the provided user. Same as get_org_unit_enrollment_data_by_user



37
38
39
40
41
# File 'lib/d2l_sdk/enroll.rb', line 37

def get_user_enrollment_data_by_org_unit(user_id, org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/enrollments/users/#{user_id}/orgUnits/#{org_unit_id}"
    _get(path)
    # Returns: EnrollmentData JSON block.
end

#get_user_overdue_items(user_id, org_unit_ids_CSV = nil) ⇒ Object

Retrieve the overdue items for a particular user in a particular org unit. org_unit_ids_CSV is a CSV of D2LIDs or rather Org unit IDs (optional) Viewing user overdue items depends upon the current calling user’s permissions. Returns: An ObjectListPage JSON block containing a list of OverdueItem.



290
291
292
293
294
295
296
# File 'lib/d2l_sdk/course_content.rb', line 290

def get_user_overdue_items(user_id, org_unit_ids_CSV = nil) # GET
  query_string = "/d2l/api/le/#{$le_ver}/overdueItems/"
  query_string += "?userId=#{user_id}"
  query_string += "&orgUnitIdsCSV=#{org_unit_ids_CSV}" unless org_unit_ids_CSV.nil?
  _get(query_string)
  # Returns: An ObjectListPage JSON block containing a list of OverdueItem.
end

#get_user_profile_by_profile_id(profile_id) ⇒ Object

retrieve a particular personal profile, by Profile ID



311
312
313
314
315
# File 'lib/d2l_sdk/user.rb', line 311

def (profile_id)
  path = "/d2l/api/lp/#{$lp_ver}/profile/#{profile_id}"
  _get(path)
  # Returns UserProfile JSON data block
end

#get_user_profile_by_user_id(user_id) ⇒ Object

retrieve personal profile info of the specified user



304
305
306
307
308
# File 'lib/d2l_sdk/user.rb', line 304

def (user_id)
  path = "/d2l/api/lp/#{$lp_ver}/profile/user/#{user_id}"
  _get(path)
  # Returns UserProfile JSON data block
end

#get_user_profile_image(user_id) ⇒ Object



329
330
331
332
333
# File 'lib/d2l_sdk/user.rb', line 329

def (user_id)
  path = "/d2l/api/lp/#{$lp_ver}/profile/user/#{user_id}"
  path += "?size=#{size}" if size != 0
  _get(path)
end

#get_user_role(role_id) ⇒ Object

Retrieve a particular user role



289
290
291
292
293
# File 'lib/d2l_sdk/user.rb', line 289

def get_user_role(role_id)
  path = "/d2l/api/lp/#{$lp_ver}/roles/#{role_id}"
  _get(path)
  # returns a Role JSON data block
end

#get_users(org_defined_id = '', username = '', bookmark = '') ⇒ Object

Simple get users function that assists in retrieving users by particular paramerters. These parameters are then appended to the query string if they are defined by the user.

Returns: JSON of all users matching the parameters given.



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/d2l_sdk/user.rb', line 74

def get_users(org_defined_id = '', username = '', bookmark = '')
    path = "/d2l/api/lp/#{$lp_ver}/users/"
    path += "?orgDefinedId=#{org_defined_id}" if org_defined_id != ''
    path += "?userName=#{username}" if username != ''
    path += "?bookmark=#{bookmark}" if bookmark != ''
    _get(path)
    # If- username is defined, this RETURNS a single UserData JSON block
    # else if- org_defined_id is defined, this returns a UserData JSON array
    # else- if neither is defined, this RETURNS a paged result set of users after
    # the bookmark
end

#get_users_by_bookmark(bookmark = '') ⇒ Object

Helper function that retrieves the first 100 users after the specified bookmark.

Returns: JSON array of user objects.



96
97
98
99
# File 'lib/d2l_sdk/user.rb', line 96

def get_users_by_bookmark(bookmark = '')
    get_users('', '', bookmark)
    # Returns: JSON array of user objects.
end

#get_versionsObject

retrieve all supported versions for all product components



198
199
200
201
202
# File 'lib/d2l_sdk/requests.rb', line 198

def get_versions
  path = "/d2l/api/versions/"
  _get(path)
  # returns: SupportedVersion JSON block
end

#get_whoamiObject

Retrieves the whoami of the user authenticated through the config file. returns: JSON whoami response



63
64
65
66
67
# File 'lib/d2l_sdk/user.rb', line 63

def get_whoami
    path = "/d2l/api/lp/#{$lp_ver}/users/whoami"
    _get(path)
    # returns a WhoAmIUser JSON block for the current user context
end

#initialize_org_unit_sections(org_unit_id, section_property_data) ⇒ Object

Initialize one or more sections for a particular org unit.



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/d2l_sdk/section.rb', line 163

def initialize_org_unit_sections(org_unit_id, section_property_data)
    payload = {
        'EnrollmentStyle' => 0,
        'EnrollmentQuantity' => 0,
        'AutoEnroll' => false,
        'RandomizeEnrollments' => false
    }.merge!(section_property_data)
    # Check the validity of the SectionPropertyData that is passed as a payload
    check_section_property_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/"
    # JSON param: SectionPropertyData
    _put(path, payload)
    # returns a JSON array of SectionData data blocks, in the Fetch
    # form, for the org unit’s initial section(s)
end

#is_course_component(key) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
# File 'lib/d2l_sdk/course.rb', line 195

def is_course_component(key)
  valid_components = %w(AttendanceRegisters Glossary News Checklists
                        Grades QuestionLibrary Competencies GradesSettings
                        Quizzes Content Groups ReleaseConditions CourseFiles
                        Homepages Rubrics Discussions IntelligentAgents
                        Schedule DisplaySettings Links SelfAssessments
                        Dropbox LtiLink Surveys Faq LtiTP ToolNames Forms
                        Navbars Widgets)
  valid_components.include?(key)
  # returns whether the key is actually a course component
end

#is_group_category_locker_set_up(org_unit_id, group_category_id) ⇒ Object



228
229
230
231
232
# File 'lib/d2l_sdk/group.rb', line 228

def is_group_category_locker_set_up(org_unit_id, group_category_id)
    path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/locker"
    _get(path)["HasLocker"]
    #returns true if the group cat. locker has been setup already
end

#multithreaded_user_search(parameter, search_string, num_of_threads, regex = false) ⇒ Object

Initiates a multithreaded search to streamline the search of a user based upon a part of their search str. This calls get_user_by_string, which is actually using a bookmarked search. This brings the search time down from 15+ minutes to only ~10-13 seconds, depending upon the computer. This can be sped up MUCH more by using a computer with more cores. Anyways, based upon the number of threads used, iterations are performed, specifying certain ranges for each thread to search by using get_user_by_string. Upon all of the threads joining, the thread_results are returned (as they are all the matching names)

returns: Array::param_values_with_string_included example— multithreaded_user_search(“UserName”, “api”, 17) example 2— multithreaded_user_search(“UserName”, /pap/, 17, true)



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
# File 'lib/d2l_sdk/user.rb', line 130

def multithreaded_user_search(parameter, search_string, num_of_threads, regex = false)
    # Assumed: there is only up to 60,000 users.
    # Start from 1, go up to max number of users for this search...
    max_users = 60_000
    range_min = 1
    # range max = the upper limit for the search for a thread
    range_max = max_users / num_of_threads + 1
    threads = []
    thread_results = []
    # ap "creating #{num_of_threads} threads..."
    # from 0 up until max number of threads..
    (0...num_of_threads - 1).each do |iteration|
        # setup range limits for the specific thread
        min = range_min + range_max * iteration
        max = range_max + (range_max - 1) * iteration
        range = create_range(min, max)
        # push thread to threads arr and start thread search of specified range.
        threads[iteration] = Thread.new do
            _get_user_by_string(parameter, search_string, range, regex).each do |match|
                thread_results.push(match)
            end
        end
    end
    # Join all of the threads
    threads.each(&:join)
    puts "returning search results for #{parameter}::#{search_string}"
    # Return an array of users that exist with the search_string in the param.
    thread_results
end

#prompt(*args) ⇒ Object

requests input from the user, cuts off any new line and downcases it.

returns: String::downcased_user_input



16
17
18
19
20
# File 'lib/d2l_sdk/auth.rb', line 16

def prompt(*args)
    print(*args)
    gets.chomp.downcase
    # returns: String::downcased_user_input
end

#recycle_org_unit(org_unit_id) ⇒ Object

An org unit is recycled by executing a POST http method and recycling it. The path for the recycling is created using the org_unit_id argument and then the post method is executed afterwards.



181
182
183
184
# File 'lib/d2l_sdk/org_unit.rb', line 181

def recycle_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/recyclebin/#{org_unit_id}/recycle"
    _post(path, {})
end

#recycle_semester_by_name(name) ⇒ Object

Rather than recycling a semester by a specific id, this function can recycle all semesters that match a particular name. The names must be exactly the same as the “name” argument. Each name that is the exact same as this argument is then recycled, iteratively.



152
153
154
155
156
157
158
159
# File 'lib/d2l_sdk/semester.rb', line 152

def recycle_semester_by_name(name)
    results = get_semester_by_name(name)
    results.each do |semester_match|
        if semester_match['Name'] == name
            recycle_semester_data(semester_match['Identifier'])
        end
    end
end

#recycle_semester_data(org_unit_id) ⇒ Object

This function provides the means to put the semester data into the recycling bin. A path is then created using the org_unit_id argument. Once this is done the post http method is then completed in order to officially recycle the data



140
141
142
143
144
145
146
# File 'lib/d2l_sdk/semester.rb', line 140

def recycle_semester_data(org_unit_id)
    # Define a path referencing the user data using the user_id
    puts '[!] Attempting to recycle Semester data referenced by id: ' + org_unit_id.to_s
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/recyclebin/" + org_unit_id.to_s + '/recycle' # setup user path
    _post(path, {})
    puts '[+] Semester data recycled successfully'.green
end

#remove_course_from_semester(course_id, semester_id) ⇒ Object

Same as adding a course to a semester, in regards to being a bridge function. Obviously, this is used to delete the relationship between this course and this particular semester.



62
63
64
# File 'lib/d2l_sdk/semester.rb', line 62

def remove_course_from_semester(course_id, semester_id)
    delete_relationship_of_child_with_parent(semester_id, course_id)
end

#remove_user_from_group(org_unit_id, group_category_id, group_id, user_id) ⇒ Object

Remove a particular user from a group.



19
20
21
22
# File 'lib/d2l_sdk/group.rb', line 19

def remove_user_from_group(org_unit_id, group_category_id, group_id, user_id)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/#{group_id}/enrollments/#{user_id}"
  _delete(path)
end

#restore_recycled_org_unit(org_unit_id) ⇒ Object

Restores a recycled org unit. This is done by referencing the org unit by its id in the recycling bin and then appending ‘/restore’. This is then used in a post method that performs the restoring process.



196
197
198
199
# File 'lib/d2l_sdk/org_unit.rb', line 196

def restore_recycled_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/recyclebin/#{org_unit_id}/restore"
    _post(path, {})
end

#subscribe_to_carrier_notification(carrier_id, message_type_id) ⇒ Object



345
346
347
348
# File 'lib/d2l_sdk/user.rb', line 345

def subscribe_to_carrier_notification(carrier_id, message_type_id)
  path = "/d2l/api/lp/#{$lp_ver}/notifications/instant/carriers/#{carrier_id}/subscriptions/#{message_type_id}"
  _put(path,{})
end

#unzip(file_path, csv_filter = //) ⇒ Object

Unzip the file, applying a regex filter to the CSV if the file is Enrollments data.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/d2l_sdk/datahub.rb', line 139

def unzip(file_path, csv_filter = //)
  puts "Unzipping file: #{file_path}"
  # Unzip the file
  Zip::File.open(file_path) { |zip_file|
    # for each file in the zip file
     zip_file.each { |f|
     # create file path of export_jobs/#{f.name}
     f_path=File.join("export_jobs", f.name)
     # make the directory if not already made
     FileUtils.mkdir_p(File.dirname(f_path))
     # extract the file unless the file already exists
     zip_file.extract(f, f_path) unless File.exist?(f_path)
     # if the file is CSV and Enrollments, apply filters and proper
     # CSV formatting to the file, writing it as base f.name  + filtered.csv
     if (f.name.include? ".csv") && (f.name.include? "Enrollments")
       filter_formatted_enrollments("export_jobs/#{f.name}", csv_filter, "export_jobs/instr.csv")
     end
   }
  }
end

#update_course_data(course_id, new_data) ⇒ Object

Update the course based upon the first argument. This course object is first referenced via the first argument and its data formatted via merging it with a predefined payload. Then, a PUT http method is executed using the new payload. Utilize the second argument and perform a PUT action to replace the old data



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/d2l_sdk/course.rb', line 175

def update_course_data(course_id, new_data)
    # Define a valid, empty payload and merge! with the new data.
    payload = { 'Name' => '', # String
                'Code' => 'off_SEMESTERCODE_STARNUM', # String
                'StartDate' => nil, # String: UTCDateTime | nil
                'EndDate' => nil, # String: UTCDateTime | nil
                'IsActive' => false # bool
              }.merge!(new_data)
    check_updated_course_data_validity(payload)
    # ap payload
    # Define a path referencing the courses path
    path = "/d2l/api/lp/#{$lp_ver}/courses/" + course_id.to_s
    _put(path, payload)
    # requires: CourseOfferingInfo JSON block
    puts '[+] Course update completed successfully'.green
    # Define a path referencing the course data using the course_id
    # Perform the put action that replaces the old data
    # Provide feedback that the update was successful
end

#update_course_template(org_unit_id, new_data) ⇒ Object

This is the primary method utilized to update course templates. As only the Name and the Code can be changed in an update, they are pre-defined to conform to the required update data. The update is then performed via a PUT http method that is executed using a path referencing the course template. /d2l/api/lp/(version)/coursetemplates/(orgUnitId) [PUT]



138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/d2l_sdk/course_template.rb', line 138

def update_course_template(org_unit_id, new_data)
    # Define a valid, empty payload and merge! with the new data.
    payload = { 'Name' => '', # String
                'Code' => 'off_SEMESTERCODE_STARNUM', # String
              }.merge!(new_data)
    puts "Updating course template #{org_unit_id}"
    check_course_template_updated_data_validity(payload)
    # ap payload
    # requires: CourseTemplateInfo JSON block
    # Define a path referencing the courses path
    path = "/d2l/api/lp/#{$lp_ver}/coursetemplates/" + org_unit_id.to_s
    _put(path, payload)
    puts '[+] Course template update completed successfully'.green
end

#update_module(org_unit_id, module_id) ⇒ Object

Update a particular module for an org unit. INPUT: ContentObjectData of type Module NOTE: Cannot use this action to affect a module’s existing Structure property.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/d2l_sdk/course_content.rb', line 160

def update_module(org_unit_id, module_id) # PUT
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/modules/#{module_id}"
  payload = {
    "Title" => "",
    "ShortTitle" => "",
    "Type" => 0,
    "ModuleStartDate" => nil, #<string:UTCDateTime>|null
    "ModuleEndDate" => nil, #<string:UTCDateTime>|null
    "ModuleDueDate" => nil, #<string:UTCDateTime>|null
    "IsHidden" => false,
    "IsLocked" => false,
    "Description" => nil, #{ <composite:RichTextInput> }|null --Added with LE v1.10 API
    "Duration" => nil #  <number>|null --Added in LE's +unstable+ contract as of LE v10.6.8
  }.merge!(content_module)
  check_content_module_validity(payload)
  _put(query_string, payload)
end

#update_org_unit(org_unit_id, org_unit_data) ⇒ Object



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
# File 'lib/d2l_sdk/org_unit.rb', line 263

def update_org_unit(org_unit_id, org_unit_data)
    previous_data = get_org_unit_properties(org_unit_id)
    payload = { # Can only update NAME, CODE, and PATH variables
        'Identifier' => org_unit_id.to_s, # String: D2LID // DO NOT CHANGE
        'Name' => previous_data['Name'], # String
        # String #YearNUM where NUM{sp:01,su:06,fl:08}  | nil
        'Code' => previous_data['Code'],
        # String: /content/enforced/IDENTIFIER-CODE/
        'Path' => "/content/enforced/#{org_unit_id}-#{previous_data['Code']}/",
        'Type' => previous_data['Type']
        # example:
        # { # DO NOT CHANGE THESE
        #    'Id' => 5, # <number:D2LID>
        #    'Code' => 'Semester', # <string>
        #    'Name' => 'Semester', # <string>
        # }
    }.merge!(org_unit_data)
    check_org_unit_updated_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}"
    puts '[-] Attempting put request (updating orgunit)...'
    # requires: OrgUnitProperties JSON block
    _put(path, payload)
    puts '[+] Semester update completed successfully'.green
    # returns: OrgUnitProperties JSON data block
end

#update_org_unit_group(org_unit_id, group_category_id, group_id, group_data) ⇒ Object

Update a particular group for an org unit



157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/d2l_sdk/group.rb', line 157

def update_org_unit_group(org_unit_id, group_category_id, group_id, group_data)
  payload = {
    "Name" => "string",
    "Code" => "string",
    "Description" => {}
  }.merge!(group_data)
  # Requires: JSON block of GroupData
  validate_group_data(payload)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_id}/groups/#{group_id}"
  # returns a GroupData JSON block, in the Fetch form, of the updated group.
  _put(path, payload)
end

#update_org_unit_group_category(org_unit_id, group_category_id, group_category_data) ⇒ Object

update a particular group category for an org unit



214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/d2l_sdk/group.rb', line 214

def update_org_unit_group_category(org_unit_id, group_category_id, group_category_data)

  payload = { 'Name' => '', # String
              'Description' => {}, # RichTextInput
              'AutoEnroll' => false, # bool
              'RandomizeEnrollments' => false, # bool
            }.merge!(group_category_data)
  # Requires: JSON block of GroupCategoryData
  validate_update_group_category_data(payload)
  path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/groupcategories/#{group_category_data}"
  _put(path, payload)
  # Returns a GroupCategoryData JSON block, in the Fetch form, of updated grp. cat.
end

#update_org_unit_section_info(org_unit_id, section_id, section_data) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/d2l_sdk/section.rb', line 196

def (org_unit_id, section_id, section_data)
    payload = { 'Name' => '', # String
                'Code' => '', # String
                'Description' => {}, # RichTextInput -- e.g. {'Content'=>'x', 'Type'=>'y'}
              }.merge!(section_data)
    # Check the validity of the SectionData that is passed as a payload
    check_section_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/section_id"
    # JSON param: SectionData
    _put(path, payload)
    # returns the SectionData JSON block, in its Fetch form
end

#update_org_unit_section_properties(org_unit_id, section_property_data) ⇒ Object

Update the section properties for an org unit.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/d2l_sdk/section.rb', line 180

def update_org_unit_section_properties(org_unit_id, section_property_data)
    payload = {
        'EnrollmentStyle' => 0,
        'EnrollmentQuantity' => 0,
        'AutoEnroll' => false,
        'RandomizeEnrollments' => false
    }.merge!(section_property_data)
    # Check the validity of the SectionPropertyData that is passed as a payload
    check_section_property_data_validity(payload)
    path = "/d2l/api/lp/#{$lp_ver}/#{org_unit_id}/sections/settings"
    # JSON param: SectionPropertyData
    _put(path, payload)
    # returns the SectionPropertyData JSON block, in its Fetch form,
    # for the org unit’s updated section properties.
end

#update_outype(outype_id, create_org_unit_type_data) ⇒ Object

update a particular org unit type (with POST for some reason)



350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/d2l_sdk/org_unit.rb', line 350

def update_outype(outype_id, create_org_unit_type_data)
  payload =
  {
    'Code' => '',
    'Name' => '',
    'Description' => '',
    'SortOrder' => 0
  }.merge!(create_org_unit_type_data)
  #validate schema
  check_create_org_unit_type_data_validity(payload)
  path = "/d2l/api/lp/#{$lp_ver}/outypes/#{outype_id}"
  _post(path, payload)
  # returns OrgUnitType JSON data block
end

#update_semester_data(org_unit_id, semester_data) ⇒ Object

Updates a semester’s data via merging a preformatted payload with the new semester data. The ‘path’ is then initialized using a defined org_unit_id and the semester is then updated via the newly defined payload and the path.



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
# File 'lib/d2l_sdk/semester.rb', line 111

def update_semester_data(org_unit_id, semester_data)
    # Define a valid, empty payload and merge! with the semester_data. Print it.
    payload = { # Can only update NAME, CODE, and PATH variables
        'Identifier' => org_unit_id.to_s, # String: D2LID // DO NOT CHANGE
        'Name' => 'NAME', # String
        # String #YearNUM where NUM{sp:01,su:06,fl:08}  | nil
        'Code' => 'REQUIRED',
        # String: /content/enforced/IDENTIFIER-CODE/
        'Path' => create_semester_formatted_path(org_unit_id.to_s, 'YEAR01'),
        'Type' => { # DO NOT CHANGE THESE
            'Id' => 5, # <number:D2LID>
            'Code' => 'Semester', # <string>
            'Name' => 'Semester', # <string>
        }
    }.merge!(semester_data)
    check_semester_updated_data_validity(payload)
    # print out the projected new data
    # puts '[-] New Semester Data:'.yellow
    # ap payload
    # Define a path referencing the course data using the course_id
    path = "/d2l/api/lp/#{$lp_ver}/orgstructure/#{org_unit_id}"
    puts '[-] Attempting put request (updating orgunit)...'
    _put(path, payload)
    puts '[+] Semester update completed successfully'.green
end

#update_topic(org_unit_id, topic_id, content_topic) ⇒ Object

Update a particular topic for an org unit. INPUT: ContentObjectData of type Topic Returns underlying file for a file content topic



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/d2l_sdk/course_content.rb', line 181

def update_topic(org_unit_id, topic_id, content_topic) # GET
  query_string = "/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/topics/#{topic_id}"
  payload = {
      'Title' => "",
      'ShortTitle' => "",
      'Type' => 0,
      'TopicType' => 0,
      'StartDate' => nil,
      'EndDate' => nil,
      'DueDate' => nil,
      'IsHidden' => nil,
      'IsLocked' => false,
      'OpenAsExternalResource' => nil, # Added with LE v1.6 API
      'Description' => nil,
      'MajorUpdate' => nil, # Added with LE v1.12 API
      'MajorUpdateText' => "", #Added with LE v1.12 API
      'ResetCompletionTracking' => nil #Added with LE v1.12 API
  }.merge!(content_topic)
  check_content_topic_validity(content_topic)
  _put(query_string, payload)
end

#update_user_data(user_id, new_data) ⇒ Object

Updates the user’s data (identified by user_id) By merging input, named new_data, with a payload, the user_data is guarenteed to at least be formatted correctly. The data, itself, depends upon the api user. Once this is merged, a put http method is utilized to update the user data.



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/d2l_sdk/user.rb', line 239

def update_user_data(user_id, new_data)
    # Define a valid, empty payload and merge! with the user_data. Print it.
    payload = {
        'OrgDefinedId' => '',
        'FirstName' => '',
        'MiddleName' => '',
        'LastName' => '',
        'ExternalEmail' => nil, # Predefines user data, in the case that
        'UserName' => '',       # there is are variables left out in the JSON
        'Activation' => {
            'IsActive' => false
        }
    }.merge!(new_data)
    # Requires: UpdateUserData JSON block
    check_updated_user_data_validity(payload)
    # Define a path referencing the user data using the user_id
    path = "/d2l/api/lp/#{$lp_ver}/users/" + user_id.to_s
    _put(path, payload)
    puts '[+] User data updated successfully'.green
    # Returns a UserData JSON block of the updated user's data
end

#validate_create_export_job_data(create_export_job_data) ⇒ Object

assures that the CreateExportJobData JSON block is valid based off of a specified JSON schema. filter names: startDate, endDate, roles, and parentOrgUnitId — startDate and EndDate must be UTC dates — parentOrgUnitId and roles are integers corresponding to an ou_id & role_id



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
# File 'lib/d2l_sdk/datahub.rb', line 41

def validate_create_export_job_data(create_export_job_data)
    schema = {
        'type' => 'object',
        # 'title'=>'the CreateExportJobData JSON block',
        'required' => %w(DataSetId Filters),
        'properties' => {
            'DataSetId' => { 'type' => 'string' },
            'Filters' => { # define the filter array
                # 'description' => 'The array of filters for CreateExportJobData',
                'type' => 'array',
                'items' =>
                  {
                      'type' => "object",
                      "properties" => {
                        "Name" => {'type'=>"string"},
                        "Value" => {'type'=>"string"}
                      }
                  }
            }
        }
    }
    #ap schema
    JSON::Validator.validate!(schema, create_export_job_data, validate_schema: true)
    # returns true if the CreateExportJobData JSON block is valid
end

#validate_create_group_category_data(group_category_data) ⇒ Object



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
# File 'lib/d2l_sdk/group.rb', line 51

def validate_create_group_category_data(group_category_data)
  schema = {
      'type' => 'object',
      'required' => %w(Name Description EnrollmentStyle
                      EnrollmentQuality AutoEnroll RandomizeEnrollments
                      NumberOfGroups MaxUsersPerGroup AllocateAfterExpiry
                      SelfEnrollmentExpiryDate GroupPrefix),
      'properties' => {
          'Name' => { 'type' => 'string' },
          'Description' =>
          {
            'type' => 'object',
            'properties'=>{
              "Content" => "string",
              "Type" => "string" #"Text|HTML"
            }
          }, #RichTextInput
          # if set to SingleUserMemberSpecificGroup, values set for NumberOfGroups
          # and MaxUsersPerGroup are IGNORED
          # ----------------------------------
          # GPRENROLL_T integer value meanings
          # 0 = NumberOfGrupsNoEnrollment ^
          # 1 = PeoplePerGroupAutoEnrollment
          # 2 = NumerOfGroupsAutoEnrollment
          # 3 = PeoplePerGroupSelfEnrollment
          # 4 = SelfEnrollmentNumberOfGroups
          # 5 = PeoplePerNumberOfGroupsSelfEnrollment
          # ----------------------------------
          'EnrollmentStyle' => { 'type' => 'integer' }, #num GRPENROLL_T
           # if non-nil, values for NumberOfGroups and MaxUsersPerGroup are IGNORED
          'EnrollmentQuantity' => { 'type' => %w(integer null) },
          'AutoEnroll' => { 'type' => 'boolean'},
          'RandomizeEnrollments' => { 'type' => 'boolean' },
          'NumberOfGroups' => { 'type' => %w(integer null) }, #nil, 0, 1, 3, 5
          'MaxUsersPerGroup' => { 'type' => %w(integer null) }, #1, 3, 5
          # if MaxUsersPerGroup has a value, then set this to true.
          'AllocateAfterExpiry' => { 'type' => 'boolean' },
          'SelfEnrollmentExpiryDate' => { 'type' => %w(string null) }, #UTCDATETIME
          # Prepends group prefix to GroupName and GroupCode
          'GroupPrefix' => { 'type' => %w(string null) }
      }
  }
  JSON::Validator.validate!(schema, group_category_data, validate_schema: true)
end

#validate_group_data(group_data) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/d2l_sdk/group.rb', line 119

def validate_group_data(group_data)
  schema =
  {
      'type' => 'object',
      'required' => %w(Name Code Description),
      'properties' =>
      {
          'Name' => { 'type' => 'string' },
          "Code" => {'type' => 'string'},
          'Description' =>
          {
            'type' => 'object',
            'properties'=>
            {
              "Content" => "string",
              "Type" => "string" #"Text|HTML"
            }
          }
      }
  }
  JSON::Validator.validate!(schema, group_data, validate_schema: true)
end

#validate_group_enrollment_data(group_enrollment_data) ⇒ Object



170
171
172
173
174
175
176
177
178
179
# File 'lib/d2l_sdk/group.rb', line 170

def validate_group_enrollment_data(group_enrollment_data)
  schema = {
      'type' => 'object',
      'required' => %w(UserId),
      'properties' => {
          'UserId' => { 'type' => 'integer' }
      }
  }
  JSON::Validator.validate!(schema, course_data, validate_schema: true)
end

#validate_isbn_association_data(isbn_association_data) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/d2l_sdk/course_content.rb', line 256

def validate_isbn_association_data(isbn_association_data)
  schema = {
      'type' => 'object',
      'required' => %w(OrgUnitId Isbn),
      'properties' => {
          'OrgUnitId' => { 'type' => 'integer' },
          'Isbn' => { 'type' => 'string' },
          'IsRequired' => { 'type' => 'boolean' },
      }
  }
  JSON::Validator.validate!(schema, isbn_association_data, validate_schema: true)
end

#validate_update_group_category_data(group_category_data) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/d2l_sdk/group.rb', line 192

def validate_update_group_category_data(group_category_data)
  schema = {
      'type' => 'object',
      'required' => %w(Name Description AutoEnroll RandomizeEnrollments),
      'properties' => {
          'Name' => { 'type' => 'string' },
          'Description' =>
          {
            'type' => 'object',
            'properties'=>{
              "Content" => "string",
              "Type" => "string" #"Text|HTML"
            }
          },
          'AutoEnroll' => { 'type' => 'boolean'},
          'RandomizeEnrollments' => { 'type' => 'boolean' }
      }
  }
  JSON::Validator.validate!(schema, group_category_data, validate_schema: true)
end