def __init__(self, domain_id):
     try:
         self.domain = TNLDomains.objects.get(id=domain_id)
         # Domain specific encryption information
         tnl_enc_password = self.domain.password
         tnl_enc_salt = salt_convert(self.domain.salt)
         tnl_enc_iterations = 22
         self.encryptor = PBEWithMD5AndDES(tnl_enc_password, tnl_enc_salt, tnl_enc_iterations)
         self.request = WebRequest(self.domain.base_url, 'success', True, 'message')
     except:
         raise Exception('This domain is invalid')
class TNLInstance:
    def __init__(self, domain_id):
        try:
            self.domain = TNLDomains.objects.get(id=domain_id)
            # Domain specific encryption information
            tnl_enc_password = self.domain.password
            tnl_enc_salt = salt_convert(self.domain.salt)
            tnl_enc_iterations = 22
            self.encryptor = PBEWithMD5AndDES(tnl_enc_password, tnl_enc_salt, tnl_enc_iterations)
            self.request = WebRequest(self.domain.base_url, 'success', True, 'message')
        except:
            raise Exception('This domain is invalid')

    def get_person(self, user):
        """
        This gets the TNL personid
        """
        # getPersonId endpoint
        endpoint = 'ia/app/webservices/person/getPersonId'
        # Parameters needed for this request
        data = {'adminid': self.domain.admin_id,
                'email': user.email}

        try:
            # Need to encrypt the data we send to TNL. Encryption adds a trailing newline, so get rid of it.
            response = self.request.do_request(endpoint, 'post', self.encryptor.encrypt(json.dumps(data)).rstrip("\n"))
            return response['personid']
        except:
            return False

    def get_grade(self, percent):
        """
        Matches our grade with the gradeid data from TNL
        """
        # Get the percent value from the decimal grade.
        grade = round(percent * 100)
        grade_out = 1
        # Compare our percent grade to the list of values for this TNL setup and return the matched value.
        for gradeid, grades in self.domain.grades:
            if grade in grades:
                grade_out = gradeid

        return grade_out

    def register_completion(self, user, course_id, percent):
        """
        This registers a competed course for a particular user with TNL
        """

        # Registered course.
        course = tnl_get_course(course_id)
        # markComplete endpoint.
        endpoint = 'ia/app/webservices/section/markComplete'
        # Get the TNL user id.
        personid = self.get_person(user)
        if personid:
            # Assign needed parameters.
            data = {'adminid': self.domain.admin_id,
                    'personid': personid,
                    'sectionid': course.section_id,
                    'gradeid': self.get_grade(percent),
                    'sectionrosterid': ''}

            try:
                # Need to encrypt the data we send to TNL. Encryption adds a trailing newline, so get rid of it.
                self.request.do_request(endpoint, 'post', self.encryptor.encrypt(json.dumps(data)).rstrip("\n"))
                # Store the completion locally for tracking, with the date.
                track = TNLCompletionTrack(user=user,
                                           course=course,
                                           registered=1,
                                           registration_date=datetime.datetime.utcnow())
            except:
                # If the TNL completion registration failed, we still want to store that we tried so we can follow up.
                track = TNLCompletionTrack(user=user, course=course, registered=0)

            track.save()
            return True
        else:
            return False

    def register_course(self, course):
        """
        This registers the course with TNL
        """
        # createSDLCourse endpoint (SDL seems the best fit for our courses)
        endpoint = 'ia/app/webservices/course/createSDLCourse'

        # Parameters needed for the request
        data = {'adminid': self.domain.admin_id,
                'title': course.display_name_with_default,
                'number': course.display_number_with_default,
                'externalid': course.id,
                'providerid': self.domain.provider_id,
                'edagencyid': self.domain.edagency_id,
                'coursetypeid': 1,
                'creditareaid': self.domain.credit_area_id,
                'creditvaluetypeid': self.domain.credit_value_type_id,
                'creditvalue': self.domain.credit_value,
                'needsapproval': False,
                'selfpaced': True}

        try:
            # Need to encrypt the data we send to TNL. Encryption adds a trailing newline, so get rid of it.
            response = self.request.do_request(endpoint, 'post', self.encryptor.encrypt(json.dumps(data)).rstrip("\n"))
            # Build the registration info for the local table.
            course_entry = TNLCourses(course=course.id,
                                      domain=self.domain,
                                      tnl_id=response['courseid'],
                                      section_id=response['sectionid'],
                                      registered=1,
                                      registration_date=datetime.datetime.utcnow())
        except:
            response = {'success': False}
            # If the registration with TNL failed, we still want to track it locally so we can follow up.
            course_entry = TNLCourses(course=course.id, registered=0)

        course_entry.save()
        return response