class Object

Public Instance Methods

_delete(path) click to toggle source

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

# File lib/d2l_api/requests.rb, line 48
def _delete(path)
    auth_uri = create_authenticated_uri(path, 'DELETE')
    RestClient.delete(auth_uri, content_type: :json)
end
_get(path) click to toggle source

performs a get request on a particular path of the host. To do this, a uniform resource identifier string is created using the path and specifying that this is a get request. Then, the RestClient get method is used to retrieve the data and parse it as a JSON. Then, the parsed response is returned. Otherwise, nothing is returned and the response code is printed

returns: JSON parsed response.

# File lib/d2l_api/requests.rb, line 14
def _get(path)
    uri_string = create_authenticated_uri(path, 'GET')
    RestClient.get(uri_string) do |response, _request, _result|
        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)
        end
    end
end
_get_string(path, http_method) click to toggle source

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

# File lib/d2l_api/auth.rb, line 80
def _get_string(path, http_method)
    timestamp = Time.now.to_i
    signature = format_signature(path, http_method, timestamp)
    build_authenticated_uri_query_string(signature, timestamp)
end
_post(path, payload) click to toggle source

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.

# File lib/d2l_api/requests.rb, line 31
def _post(path, payload)
    auth_uri = create_authenticated_uri(path, 'POST')
    RestClient.post(auth_uri, payload.to_json, content_type: :json)
end
_put(path, payload) click to toggle source

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.

# File lib/d2l_api/requests.rb, line 40
def _put(path, payload)
    auth_uri = create_authenticated_uri(path, 'PUT')
    # 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) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 96
def add_child_org_unit(org_unit_id, child_org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/children/"
    _post(path, child_org_unit_id)
end
add_parent_to_org_unit(parent_ou_id, child_ou_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 30
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/#{$version}/orgstructure/#{child_ou_id}/parents/"
    _post(path, parent_ou_id)
    # return json of org_unit parents
end
build_authenticated_uri_query_string(signature, timestamp) click to toggle source

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'

# File lib/d2l_api/auth.rb, line 47
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}"
end
create_authenticated_uri(path, http_method) click to toggle source

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

# File lib/d2l_api/auth.rb, line 31
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
end
create_course_data(course_data) click to toggle source

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

# File lib/d2l_api/course.rb, line 11
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.
    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)
    #ap payload
    path = "/d2l/api/lp/#{$version}/courses/"
    _post(path, payload)
    puts '[+] Course creation completed successfully'.green
end
create_course_template(course_template_data) click to toggle source

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]

# File lib/d2l_api/course_template.rb, line 12
def create_course_template(course_template_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.
    payload = { 'Name' => '', # String
                'Code' => 'off_SEMESTERCODE_STARNUM', # String
                'Path' => '', # String
                'ParentOrgUnitIds' => [99_989], # number: D2L_ID
              }.merge!(course_template_data)
    puts "Creating Course Template:"
    ap payload
    # Define a path referencing the courses path
    path = "/d2l/api/lp/#{$version}/coursetemplates/"
    _post(path, payload)
    puts '[+] Course template creation completed successfully'.green
end
create_custom_org_unit(org_unit_data) click to toggle source

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

# File lib/d2l_api/org_unit.rb, line 126
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)
    path = "/d2l/api/lp/#{$version}/orgstructure/"
    _post(path, payload)
end
create_range(min, max) click to toggle source

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

# File lib/d2l_api/user.rb, line 48
def create_range(min, max)
    (min..max)
end
create_semester_data(semester_data) click to toggle source

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.

# File lib/d2l_api/semester.rb, line 9
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
    path = "/d2l/api/lp/#{$version}/orgstructure/"
    _post(path, payload)
    puts '[+] Semester creation completed successfully'.green
end
create_semester_formatted_path(org_id, code) click to toggle source

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

# File lib/d2l_api/semester.rb, line 66
def create_semester_formatted_path(org_id, code)
    "/content/enforced/#{org_id}-#{code}/"
end
create_user_data(user_data) click to toggle source

USERS:################

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.

# File lib/d2l_api/user.rb, line 13
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)
    #ap payload
    # Define a path referencing the course data using the course_id
    path = "/d2l/api/lp/#{$version}/users/"
    _post(path, payload)
    puts '[+] User creation completed successfully'.green
end
delete_all_course_templates_with_name(name) click to toggle source

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.

# File lib/d2l_api/course_template.rb, line 124
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) click to toggle source

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.

# File lib/d2l_api/course.rb, line 104
def delete_course_by_id(org_unit_id)
    path = "/d2l/api/lp/#{$version}/courses/#{org_unit_id}" # setup user path
    ap path
    _delete(path)
    puts '[+] Course data deleted successfully'.green
end
delete_course_template(org_unit_id) click to toggle source

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]

# File lib/d2l_api/course_template.rb, line 113
def delete_course_template(org_unit_id)
    path = "/d2l/api/lp/#{$version}/coursetemplates/" + org_unit_id.to_s
    _delete(path)
    puts '[+] Course template data deleted successfully'.green
end
delete_course_templates_by_regex(regex) click to toggle source

TO DO:

# File lib/d2l_api/course_template.rb, line 133
def delete_course_templates_by_regex(regex)
  
end
delete_recycled_org_unit(org_unit_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 115
def delete_recycled_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/recyclebin/#{org_unit_id}"
    _delete(path)
end
delete_relationship_of_child_with_parent(parent_ou_id, child_ou_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 69
def delete_relationship_of_child_with_parent(parent_ou_id, child_ou_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{parent_ou_id}/children/#{child_ou_id}"
    _delete(path)
end
delete_relationship_of_parent_with_child(parent_ou_id, child_ou_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 74
def delete_relationship_of_parent_with_child(parent_ou_id, child_ou_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{child_ou_id}/parents/#{parent_ou_id}"
    _delete(path)
end
delete_user_data(user_id) click to toggle source

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.

# File lib/d2l_api/user.rb, line 167
def delete_user_data(user_id)
    # Define a path referencing the user data using the user_id
    path = "/d2l/api/lp/#{$version}/users/" + user_id.to_s # setup user path
    _delete(path)
    puts '[+] User data deleted successfully'.green
end
display_response_code(code) click to toggle source

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.

# File lib/d2l_api/requests.rb, line 60
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) click to toggle source

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

# File lib/d2l_api/user.rb, line 54
def does_user_exist(username)
    if get_user_by_username(username.to_s) != nil
      return true
    else
      return false
    end
end
format_signature(path, http_method, timestamp) click to toggle source

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

returns: String::signature

# File lib/d2l_api/auth.rb, line 59
def format_signature(path, http_method, timestamp)
    http_method.upcase + '&' + path.encode('UTF-8') + '&' + timestamp.to_s
end
get_all_childless_org_units() click to toggle source
# File lib/d2l_api/org_unit.rb, line 79
def get_all_childless_org_units
    path = "/d2l/api/lp/#{$version}/orgstructure/childless/"
    _get(path)
    # ONLY RETRIEVES FIRST 100
end
get_all_course_templates() click to toggle source

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

# File lib/d2l_api/course_template.rb, line 49
def get_all_course_templates
  path = "/d2l/api/lp/#{$version}/orgstructure/6606/descendants/?ouTypeId=2"
  _get(path)
end
get_all_org_units_by_type_id(outype_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 168
def get_all_org_units_by_type_id(outype_id)
  path = "/d2l/api/lp/#{$version}/orgstructure/6606/children/?ouTypeId=#{outype_id}"
  _get(path)
end
get_all_orphans() click to toggle source
# File lib/d2l_api/org_unit.rb, line 85
def get_all_orphans
    path = "/d2l/api/lp/#{$version}/orgstructure/orphans/"
    _get(path)
end
get_all_outypes() click to toggle source

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

# File lib/d2l_api/org_unit.rb, line 182
def get_all_outypes
    path = "/d2l/api/lp/#{$version}/outypes/"
    _get(path)
end
get_all_semesters() click to toggle source

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

# File lib/d2l_api/semester.rb, line 26
def get_all_semesters
  path = "/d2l/api/lp/#{$version}/orgstructure/6606/children/?ouTypeId=5"
  _get(path)
end
get_base64_hash_string(key, signature) click to toggle source

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

# File lib/d2l_api/auth.rb, line 69
def get_base64_hash_string(key, signature)
    hash = OpenSSL::HMAC.digest('sha256', key, signature)
    Base64.urlsafe_encode64(hash).delete('=')
end
get_course_by_id(org_unit_id) click to toggle source
# File lib/d2l_api/course.rb, line 44
def get_course_by_id(org_unit_id)
    path = "/d2l/api/lp/#{$version}/courses/#{org_unit_id}"
    _get(path)
end
get_course_template(org_unit_id) click to toggle source

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]

# File lib/d2l_api/course_template.rb, line 37
def get_course_template(org_unit_id)
    path = "/d2l/api/lp/#{$version}/coursetemplates/" + org_unit_id.to_s
    _get(path)
end
get_course_template_by_name(org_unit_name) click to toggle source

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

# File lib/d2l_api/course_template.rb, line 62
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
end
get_course_templates_schema() click to toggle source

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]

# File lib/d2l_api/course_template.rb, line 85
def get_course_templates_schema
    path = "/d2l/api/lp/#{$version}/coursetemplates/schema"
    _get(path)
end
get_courses_by_name(org_unit_name) click to toggle source

Retrieves all courses that have a particular string (org_unit_name) within their names. This is done by first defining that none are found yet and then searching through all course 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 data objects

# File lib/d2l_api/course.rb, line 55
def get_courses_by_name(org_unit_name)
    get_courses_by_property_by_string("Name", org_unit_name)
end
get_courses_by_property_by_string(property, search_string) click to toggle source
# File lib/d2l_api/course.rb, line 59
def get_courses_by_property_by_string(property, search_string)
  class_not_found = true
  puts "[+] Searching for courses using search string: #{search_string}".yellow +
        + " -- And property: #{property}"
  courses_results = []
  path = "/d2l/api/lp/#{$version}/orgstructure/6606/descendants/?ouTypeId=3"
  results = _get(path)
  results.each do |x|
      if x[property].downcase.include? search_string.downcase
          class_not_found = false
          courses_results.push(x)
      end
  end
  if class_not_found
      puts '[-] No courses could be found based upon the search string.'.yellow
  end
  courses_results
end
get_org_department_classes(org_unit_id) click to toggle source

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.

# File lib/d2l_api/course.rb, line 39
def get_org_department_classes(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/" + org_unit_id
    _get(path)
end
get_org_unit_ancestors(org_unit_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 39
def get_org_unit_ancestors(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/ancestors/"
    _get(path)
    # return json of org_unit parents
end
get_org_unit_children(org_unit_id) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 48
def get_org_unit_children(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/children/"
    _get(path)
    # return json of org_unit children
end
get_org_unit_descendants(org_unit_id) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 9
def get_org_unit_descendants(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/descendants/"
    _get(path)
    # return json of org_unit descendants
end
get_org_unit_parents(org_unit_id) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 24
def get_org_unit_parents(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/parents/"
    _get(path)
    # return json of org_unit parents
end
get_org_unit_properties(org_unit_id) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 63
def get_org_unit_properties(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}"
    _get(path)
    # return json of org_unit properties
end
get_organization_info() click to toggle source

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

# File lib/d2l_api/org_unit.rb, line 163
def get_organization_info
    path = "/d2l/api/lp/#{$version}/organization/info"
    _get(path)
end
get_outype(outype_id) click to toggle source

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

# File lib/d2l_api/org_unit.rb, line 175
def get_outype(outype_id)
    path = "/d2l/api/lp/#{$version}/outypes/#{outype_id}"
    _get(path)
end
get_paged_org_unit_children(org_unit_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 54
def get_paged_org_unit_children(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/children/paged/"
    _get(path)
    # return json of org_unit children
end
get_paged_org_unit_descendants(org_unit_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 15
def get_paged_org_unit_descendants(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}/descendants/paged/"
    _get(path)
    # return json of org_unit descendants
end
get_recycled_org_units() click to toggle source
# File lib/d2l_api/org_unit.rb, line 101
def get_recycled_org_units
    path = "/d2l/api/lp/#{$version}/orgstructure/recyclebin/"
    _get(path)
    # GETS ONLY FIRST 100
end
get_semester_by_id(org_unit_id) click to toggle source
# File lib/d2l_api/semester.rb, line 31
def get_semester_by_id(org_unit_id)
  path = "/d2l/api/lp/#{$version}/orgstructure/" + org_unit_id.to_s
  _get(path)
  # return json of org_unit properties
end
get_semester_by_name(search_string) click to toggle source

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)

# File lib/d2l_api/semester.rb, line 45
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_user_by_string(parameter, search_string, range) click to toggle source

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

# File lib/d2l_api/user.rb, line 110
def get_user_by_string(parameter, search_string, range)
    # 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/#{$version}/users/?bookmark=" + i.to_s
        response = _get(path)
        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|
            matching_names.push(user) if user[parameter].include? search_string
        end
        i = response['PagingInfo']['Bookmark']
    end
    matching_names
end
get_user_by_user_id(user_id) click to toggle source

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.

# File lib/d2l_api/user.rb, line 135
def get_user_by_user_id(user_id)
    path = "/d2l/api/lp/#{$version}/users/" + user_id.to_s
    _get(path)
end
get_user_by_username(username) click to toggle source

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

# File lib/d2l_api/user.rb, line 41
def get_user_by_username(username)
    path = "/d2l/api/lp/#{$version}/users/?userName=#{username}"
    _get(path)
end
get_whoami() click to toggle source

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

# File lib/d2l_api/user.rb, line 34
def get_whoami
    path = "/d2l/api/lp/#{$version}/users/whoami"
    _get(path)
end
prompt(*args) click to toggle source

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

returns: String::downcased_user_input

# File lib/d2l_api/auth.rb, line 16
def prompt(*args)
    print(*args)
    gets.chomp.downcase
end
recycle_org_unit(org_unit_id) click to toggle source

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.

# File lib/d2l_api/org_unit.rb, line 110
def recycle_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/recyclebin/#{org_unit_id}/recycle"
    _post(path, {})
end
recycle_semester_by_name(name) click to toggle source

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.

# File lib/d2l_api/semester.rb, line 113
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) click to toggle source

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

# File lib/d2l_api/semester.rb, line 101
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/#{$version}/orgstructure/recyclebin/" + org_unit_id.to_s + '/recycle' # setup user path
    _post(path, {})
    puts '[+] Semester data recycled successfully'.green
end
restore_recycled_org_unit(org_unit_id) click to toggle source
# File lib/d2l_api/org_unit.rb, line 120
def restore_recycled_org_unit(org_unit_id)
    path = "/d2l/api/lp/#{$version}/orgstructure/recyclebin/#{org_unit_id}/restore"
    _post(path, {})
end
update_course_data(course_id, new_data) click to toggle source

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

# File lib/d2l_api/course.rb, line 83
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)
    #ap payload
    # Define a path referencing the courses path
    path = "/d2l/api/lp/#{$version}/courses/" + course_id.to_s
    _put(path, payload)
    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) click to toggle source

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]

# File lib/d2l_api/course_template.rb, line 95
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}"
    #ap payload
    # Define a path referencing the courses path
    path = "/d2l/api/lp/#{$version}/coursetemplates/" + org_unit_id.to_s
    _put(path, payload)
    puts '[+] Course template update completed successfully'.green
end
update_org_unit(org_unit_id, org_unit_data) click to toggle source
# File lib/d2l_api/org_unit.rb, line 138
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)
    path = "/d2l/api/lp/#{$version}/orgstructure/#{org_unit_id}"
    puts '[-] Attempting put request (updating orgunit)...'
    _put(path, payload)
    puts '[+] Semester update completed successfully'.green
end
update_semester_data(org_unit_id, semester_data) click to toggle source

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.

# File lib/d2l_api/semester.rb, line 73
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)
    # 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/#{$version}/orgstructure/#{org_unit_id}"
    puts '[-] Attempting put request (updating orgunit)...'
    _put(path, payload)
    puts '[+] Semester update completed successfully'.green
end
update_user_data(user_id, new_data) click to toggle source

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.

# File lib/d2l_api/user.rb, line 145
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)
    # Define a path referencing the user data using the user_id
    path = "/d2l/api/lp/#{$version}/users/" + user_id.to_s
    _put(path, payload)
    puts '[+] User data updated successfully'.green
end