Пример #1
0
    def get(self):
        logger.debug("Getting instances")
        auth_response = authenticate(self, [Permissions.READ_SURVEY])

        survey_id = self.get_argument("survey_id", None)
        status = self.get_argument("status", None)

        if auth_response["valid"]:

            owner_id = auth_response["owner_id"]

            if status is not None:
                instances = InstanceService.get_by_owner(owner_id, survey_id, Status.CREATED_START)
            else:
                instances = InstanceService.get_by_owner(owner_id, survey_id)

            instance_ids = [instance.id for instance in instances]

            self.set_status(200)

            response = {
                "status": "success",
                "ids": instance_ids
            }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id):
        logger.debug("Getting metadata about an enrollment")
        auth_response = authenticate(self, [Permissions.READ_ENROLLMENT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment.owner_id == owner.id:

                enrollment_dict = {
                    "id": enrollment.id,
                    "open_date": enrollment.open_date.strftime('%Y-%m-%d'),
                    "close_date": enrollment.close_date.strftime('%Y-%m-%d'),
                    "expiry_date": enrollment.expiry_date.strftime('%Y-%m-%d')
                }

                response = {"status": "success", "enrollment": enrollment_dict}
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def delete(self, enrollment_id):
        logger.debug("Removing an enrollment")
        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response['valid']:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment is None or owner.id == enrollment.owner_id:
                if enrollment is not None:  # DELETE is idempotent
                    EnrollmentService.delete_enrollment(enrollment_id)

                self.set_status(200)
                response = {"status": "success"}
            else:
                self.set_status(401)
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #4
0
    def get(self, plugin_url):
        logger.debug("Requesting permissions of an unregistered plugin")

        r = requests.get(plugin_url + "/info")

        if r.status_code != 200:
            self.set_status(400)
            response = {
                "status": "error",
                "message": "Something went wrong in the request to the plugin"
            }
        else:
            try:
                r = r.json()

                permissions = r["permissions"]

                self.set_status(200)
                response = {"status": "success", "permissions": permissions}
            except ValueError:
                self.set_status(400)
                response = {
                    "status": "error",
                    "message": "Plugin did not respond to request as expected"
                }

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #5
0
    def get(self):
        logger.debug("Querying for tasks")
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth["valid"]:
            surveys = SurveyService.get_surveys_by_owner(auth["owner_id"])

            surveys_tasks = {}

            for survey in surveys:
                surveys_tasks[survey] = TaskService.get_tasks_by_survey_id(
                    survey.id)

            tasks = []

            for survey, task_list in surveys_tasks.items():
                for task in task_list:
                    tasks.append({
                        "id":
                        task.id,
                        "name":
                        task.name,
                        "protocol_name":
                        ProtocolService.get_protocol(survey.protocol_id).name,
                        "enrollment_name":
                        EnrollmentService.get(survey.enrollment_id).name
                    })

            response = {"status": "success", "tasks": tasks}
            self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #6
0
            def save_update(self):

                instr = ''
                for key in self.model.columns:
                    instr += key + " = " + self.parse_value(
                        self.__dict__[key]) + ', '

                instr = instr[:-2]

                sql = "UPDATE " + self.model.table_name + " SET " + instr + " WHERE id = %s"
                logger.debug(sql)

                connection = Model.dao.get_connection()

                try:
                    with connection.cursor() as cursor:
                        cursor.execute(sql, self.__dict__['id'])

                        logger.debug("Executing sql: %s", sql)

                        connection.commit()
                        updated_row_id = cursor.lastrowid
                finally:
                    connection.close()

                return self.model.select(
                    Where(self.model.id, Where.EQUAL, updated_row_id))
Пример #7
0
    def delete(self, task_id):
        logger.debug("Trying to delete a task")
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth['valid']:
            task = TaskService.get_task(int(task_id))
            survey = SurveyService.get_survey(task.survey_id)

            if survey.owner_id == int(auth['owner_id']):
                TaskService.delete_task(task.id)

                self.set_status(200)

                response = {"status": "success"}
            else:
                response = {
                    "status": "error",
                    "message":
                    "Plugin is not registered by survey administrator"
                }
                self.set_status(403)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #8
0
    def get(self):
        logger.debug("Querying for plugins")
        auth = authenticate(self, [Permissions.READ_PLUGIN])

        permissions = self.get_argument("permissions")

        if auth["valid"]:
            plugins = PluginService.get_plugins_with_at_least_permissions(
                permissions)

            plugin_list = []

            for plugin in plugins:
                plugin_dict = {
                    "id": plugin.id,
                    "name": plugin.name,
                    "url": plugin.url,
                    "icon": plugin.icon,
                    "permissions": plugin.permissions
                }

                plugin_list.append(plugin_dict)

            response = {"status": "success", "plugins": plugin_list}
            self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id):
        logger.debug("Getting list of enrolled participants")
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.READ_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                participants = ParticipantService.get_participants_in_enrollment(
                    enrollment.id)

                response = {
                    "status":
                    "success",
                    "participant_ids":
                    [participant.id for participant in participants]
                }
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id, participant_id):
        logger.debug("Retrieving participant info")
        auth_response = authenticate(
            self,
            [[Permissions.READ_ENROLLMENT, Permissions.READ_PARTICIPANT]])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                try:
                    participant = ParticipantService.get_participant(
                        participant_id)
                except SecurityException as e:
                    response = {"status": "error", "message": e.message}
                    self.set_status(410)
                else:
                    if participant is None:
                        response = {
                            "status": "error",
                            "message": "Participant does not exist"
                        }

                        self.set_status(410)
                    elif participant.enrollment_id == enrollment_id:
                        participant_dict = {
                            "participant_id": participant.id,
                            "plugin_id": participant.plugin_id,
                            "plugin_scratch": participant.plugin_scratch,
                            "enrollment_id": participant.enrollment_id
                        }

                        response = {
                            "status": "success",
                            "participant": participant_dict
                        }

                        self.set_status(200)
                    else:
                        response = {
                            "status": "error",
                            "message":
                            "Participant does not belong to enrollment"
                        }
                        self.set_status(400)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer enrollment"
                }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def post(self, enrollment_id):
        logger.debug("Adding participant to enrollment")
        plugin_id = self.get_argument("plugin_id")
        plugin_name = self.get_argument("plugin_name")
        plugin_scratch = self.get_argument("plugin_scratch")
        ParticipantDetails.participantEnrollment.append(enrollment_id)
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.WRITE_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])

            if PluginService.is_owned_by(plugin_id, owner.id):
                enrollment = EnrollmentService.get(int(enrollment_id))

                if owner.id == enrollment.owner_id:
                    try:
                        ParticipantService.register_participant(
                            enrollment.id, plugin_id, plugin_scratch,
                            owner.name, owner.domain)

                        participants = ParticipantService.get_participants_in_enrollment(
                            enrollment_id)
                        for participant in participants:
                            lastparticipantid = participant.id
                        ParticipantDetails.participantEnrollment.append(
                            lastparticipantid)
                        ParticipantDetails.participantEnrollment.append(
                            plugin_name)
                        ParticipantDetails.participantEnrollment.append(
                            plugin_scratch)
                        ParticipantDetails.get_enrollment()
                    except SecurityException as e:
                        response = {"status": "error", "message": e.message}
                    else:
                        response = {"status": "success"}
                else:
                    response = {
                        "status":
                        "error",
                        "message":
                        "Owner does not have authorization to administer this enrollment"
                    }
            else:
                response = {
                    "status": "error",
                    "message":
                    "Participant's plugin is not registered with owner"
                }

                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self):
        logger.debug("User attempting to retrieve all enrollments")
        auth_response = authenticate(self, [Permissions.READ_ENROLLMENT])

        if auth_response["valid"]:
            enrollments = EnrollmentService.get_by_owner(
                auth_response["owner_id"])

            enrollments_list = []

            for enrollment in enrollments:
                enrollment_dict = {
                    "id":
                    enrollment.id,
                    "name":
                    enrollment.name,
                    "participants":
                    EnrollmentService.participant_count(enrollment.id)
                }

                if enrollment.open_date is not None:
                    enrollment_dict[
                        "open_date"] = enrollment.open_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["open_date"] = None

                if enrollment.close_date is not None:
                    enrollment_dict[
                        "close_date"] = enrollment.close_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["close_date"] = None

                if enrollment.expiry_date is not None:
                    enrollment_dict[
                        "expiry_date"] = enrollment.expiry_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["expiry_date"] = None

                enrollments_list.append(enrollment_dict)

            response = {"status": "success", "enrollments": enrollments_list}
            self.set_status(200)
        else:
            response = {
                "status": "error",
                "message": "Do not have authorization to make this request"
            }
            self.set_status(401)

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #13
0
    def get(self, plugin_id):
        logger.debug("Requesting permissions from a registered plugin")
        plugin = PluginService.get_plugin(plugin_id)

        if plugin is None:
            self.set_status(410)

            response = {"status": "error", "message": "invalid plugin id"}
        else:
            self.set_status(200)
            response = {"status": "success", "permissions": plugin.permissions}

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #14
0
        def select(self, param1=None, param2=None, force_list=False):

            inner_join = None
            where = None

            if isinstance(param1, Where):
                where = param1
            elif isinstance(param1, InnerJoin):
                inner_join = param1

            if isinstance(param2, Where):
                where = param2
            elif isinstance(param2, InnerJoin):
                inner_join = param2

            sql = "SELECT * FROM " + self.table_name
            connection = Model.dao.get_connection()

            try:
                with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                    if inner_join is not None:
                        sql += " INNER JOIN " + inner_join.build()

                    if where is not None:
                        sql += " WHERE " + where.build()

                    cursor.execute(sql)

                    logger.debug("Executing sql: %s", sql)

                    results = cursor.fetchall()

                    if len(results) == 1 and not force_list:
                        return self.__ModelInstance.from_dict(self, results[0])
                    elif len(results) > 1 or force_list:
                        instances = []

                        for result in results:
                            instances.append(
                                self.__ModelInstance.from_dict(self, result))

                        return instances

                    return [] if force_list else None
            finally:
                connection.close()
Пример #15
0
    def post(self):

        logger.debug("Attempt to login")

        data = json_decode(self.request.body)
        username = data["username"]
        password = data["password"]
        print(username)

        splitter = username.find('@')
        print(splitter)

        if splitter == -1:
            self.set_status(401)

            response = {"status": "error", "reason": "Invalid username"}
        else:
            owner_name = username[:splitter]
            owner_domain = username[splitter + 1:]

            if OwnerService.validate_password(owner_name, owner_domain,
                                              password):
                # Generate a session
                session = secure.create_session(
                    OwnerService.get(owner_name, owner_domain).id)

                self.set_status(200)

                response = {
                    "status": "success",
                    "session_id": session.id,
                    "username": username
                }

            else:
                self.set_status(401)

                response = {
                    "status": "error",
                    "reason": "Username and password do not match"
                }

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #16
0
    def post(self):
        data = json_decode(self.request.body)

        session_id = data["session_id"]

        logger.debug("Logging out session %s", session_id)

        secure.delete_session(session_id)

        response = {"status": "success"}

        self.set_status(200)

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
    def post(self, enrollment_id):
        logger.debug("Updating metadata about an enrollment")

        name = self.get_argument("name", None)
        open_date = self.get_argument("open_date", None)
        close_date = self.get_argument("close_date", None)
        expiry_date = self.get_argument("expiry_date", None)

        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response['valid']:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment.owner_id == owner.id:

                if name is not None:
                    enrollment.name = name

                if open_date is not None:
                    enrollment.open_date = parser.parse(open_date)

                if close_date is not None:
                    enrollment.close_date = parser.parse(close_date)

                if expiry_date is not None:
                    enrollment.expiry_date = parser.parse(expiry_date)

                enrollment.save()

                response = {"status": "success"}
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #18
0
    def get(self, instance_id):
        auth_response = authenticate(self, [Permissions.READ_QUESTION])

        if auth_response["valid"]:
            instance = InstanceService.get_instance(instance_id)
            state = StateService.get_next_state_in_instance(instance, Status.AWAITING_USER_RESPONSE)

            if state is None:
                self.set_status(410)
                response = {
                    "status": "error",
                    "message": "No response was expected for this survey"
                }
            else:
                survey = SurveyService.get_survey(instance.survey_id)
                if str(survey.owner_id) == auth_response['owner_id']:
                    question_service = QuestionService()
                    question = question_service.get(survey.protocol_id, state.question_number)

                    if question is not None:
                        self.set_status(200)

                        response = {
                            "status": "success",
                            "question_number": state.question_number,
                            "question_text": question.question_text,
                            "survey_end": question.final
                        }
                    else:
                        self.set_status(410)
                        response = {
                            "status": "error",
                            "message": "No more questions in this survey"
                        }
                else:
                    self.set_status(403)
                    response = {
                        "status": "error",
                        "message": "Owner has not registered plugin"
                    }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #19
0
    def get(self, task_id):
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth['valid']:
            task = TaskService.get_task(int(task_id))
            survey = SurveyService.get_survey(task.survey_id)

            if survey.owner_id == int(auth['owner_id']):
                time_rule = TimeRuleService().get(survey.id, task.time_rule_id)
                date_times = time_rule.get_date_times()

                dts = []

                for dt in date_times:

                    hour_str = str(
                        dt.hour) if dt.hour > 9 else '0' + str(dt.hour)
                    minute_str = str(
                        dt.minute) if dt.minute > 9 else '0' + str(dt.minute)

                    dts.append({
                        "year": dt.year,
                        "month": dt.month,
                        "day": dt.day,
                        "time": hour_str + ":" + minute_str
                    })

                response = {"status": "success", "run_times": dts}
                self.set_status(200)
            else:
                response = {
                    "status": "error",
                    "message":
                    "Plugin is not registered by survey administrator"
                }
                self.set_status(403)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self):
        logger.debug("GET /protocol - retrieving owner's protocols")
        auth = authenticate(self, [Permissions.READ_PROTOCOL])

        if auth['valid']:
            protocol_objects = ProtocolService.get_protocols_owned_by(auth['owner_id'])

            protocols = []

            for protocol_object in protocol_objects:
                protocol = {
                    "id": protocol_object.id,
                    "name": protocol_object.name
                }

                protocols.append(protocol)

            response = {
                "status": "success",
                "protocols": protocols
            }

            response_json = json.dumps(response)
            logger.debug(response_json)

            self.set_status(200)
            self.write(response_json)
            self.flush()

        else:
            logger.debug('Request failed - could not authenticate')
Пример #21
0
    def delete(self):
        session_id = self.get_argument("session_id")
        plugin_id = self.get_argument("plugin_id")

        logger.debug(
            "Attempting to delete plugin registered to owner of session %s",
            session_id)
        owner_id = secure.get_session_owner_id(session_id)
        logger.debug("Owner of session is %s", owner_id)

        if owner_id is not None:
            if PluginService.is_owned_by(plugin_id, owner_id):
                PluginService.delete_plugin(plugin_id)

                self.set_status(200)
                response = {"status": "success"}
            else:
                self.set_status(401)

                response = {
                    "status": "error",
                    "message": "Plugin is not associated with owner"
                }
        else:
            self.set_status(401)

            response = {"status": "error", "message": "Invalid session"}

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #22
0
    def get(self):
        session_id = self.get_argument("session_id")
        logger.debug(
            "Attempting to get plugins registered to owner of session %s",
            session_id)
        owner_id = secure.get_session_owner_id(session_id)
        logger.debug("Owner of session is %s", owner_id)

        if owner_id is not None:
            p = PluginService.get_by_owner_id(owner_id)

            plugins = []

            for plugin in p:
                plugins.append({
                    'id': plugin.id,
                    'name': plugin.name,
                    'url': plugin.url,
                    'icon': plugin.icon
                })

            self.set_status(200)
            response = {"status": "success", "plugins": plugins}
        else:
            self.set_status(401)
            response = {"status": "error", "message": "No valid session"}

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
    def delete(self, enrollment_id, participant_id):
        logger.debug("Removing participant from enrollment")
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.WRITE_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                participant = ParticipantService.get_participant(
                    participant_id)

                if participant is None or participant.enrollment_id == enrollment.id:
                    if participant is not None:
                        ParticipantService.delete_participant(participant_id)

                    response = {
                        "status": "success",
                    }
                    self.set_status(200)
                else:
                    response = {
                        "status": "error",
                        "message": "Participant does not belong to enrollment"
                    }
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #24
0
            def save_new(self, id_override=None):
                columns, values = self.get_column_tuples()
                sql = "INSERT INTO " + self.model.table_name + " " + columns + " VALUES %s"

                connection = Model.dao.get_connection()

                try:
                    with connection.cursor() as cursor:
                        cursor.execute(sql, [values])

                        logger.debug("Executing sql: %s", sql)

                        connection.commit()
                        new_row_id = cursor.lastrowid
                finally:
                    connection.close()

                if id_override is None:
                    return self.model.select(
                        Where(self.model.id, Where.EQUAL, new_row_id))
                else:
                    return self.model.select(
                        Where(self.model.id, Where.E, id_override))
Пример #25
0
    def post(self):

        logger.debug("Attempting to verify a session")

        data = json_decode(self.request.body)

        username = data["username"]
        session_id = data["session_id"]

        splitter = username.find('@')

        if splitter == -1:
            self.set_status(401)

            response = {"status": "error", "reason": "Invalid username"}
        else:
            owner_name = username[:splitter]
            owner_domain = username[splitter + 1:]

            if secure.session_valid(
                    OwnerService.get(owner_name, owner_domain).id, session_id):
                self.set_status(200)

                response = {"status": "success"}
            else:
                self.set_status(401)

                response = {
                    "status": "error",
                    "reason": "Invalid or out of date session"
                }

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
    def post(self):
        logger.debug("Adding new enrollment")

        name = self.get_argument("name")
        open_date = self.get_argument("open_date", None)
        close_date = self.get_argument("close_date", None)
        expiry_date = self.get_argument("expiry_date", None)

        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response["valid"]:
            if open_date is not None:
                open_date = parser.parse(open_date)

            if close_date is not None:
                close_date = parser.parse(close_date)

            if expiry_date is not None:
                expiry_date = parser.parse(expiry_date)

            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.add_enrollment(
                name, owner.id, open_date, close_date, expiry_date)
            response = {"status": "success", "enrollment_id": enrollment.id}
            self.set_status(200)
        else:
            response = {
                "status": "error",
                "message": "Do not have authorization to make this request"
            }
            self.set_status(401)

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Пример #27
0
    def post(self):
        logger.debug("Posting new task")

        task_name = self.get_argument("name")
        protocol_id = int(self.get_argument("protocol_id"))
        enrollment_id = int(self.get_argument("enrollment_id"))
        time_rule = json.loads(self.get_argument("time_rule"))
        enable_notes = self.get_argument("enable_notes", False)
        timeout = int(self.get_argument("timeout"), 20)
        enable_warnings = self.get_argument("enable_warnings", True)
        enable_notes = 1 if enable_notes else 0
        enable_warnings = 1 if enable_warnings else 0

        all_run_times = []
        all_run_dates = []
        local_tz = pytz.timezone(time_rule['timezone'])
        date_conversion = time_rule["run_date"]
        time_conversion = time_rule["run_times"]
        for several_run_time in time_conversion:
            datetime_without_tz = datetime.strptime(
                str(date_conversion) + " " + str(several_run_time),
                "%Y-%m-%d %H:%M")
            datetime_with_tz = local_tz.localize(
                datetime_without_tz, is_dst=True)  # No daylight saving time
            datetime_in_utc = datetime_with_tz.astimezone(pytz.utc)
            str_utc_time = datetime_in_utc.strftime('%Y-%m-%d %H:%M %Z')
            all_run_dates.append(str_utc_time[:10])
            all_run_times.append(str_utc_time[11:16])

        time_rule["run_date"] = str_utc_time[:10]
        time_rule["run_times"] = all_run_times

        auth = authenticate(self,
                            [Permissions.WRITE_TASK, Permissions.WRITE_SURVEY])

        if auth["valid"]:
            owner_id = int(auth['owner_id'])
            response = None

            if ProtocolService.is_owned_by(protocol_id, int(auth['owner_id'])):
                if EnrollmentService.is_owned_by(enrollment_id, owner_id):
                    params = time_rule["params"]
                    run_time_values = time_rule["run_times"]

                    run_times = []

                    for run_time_value in run_time_values:
                        rtv = run_time_value.split(":")
                        hour = int(rtv[0])
                        minute = int(rtv[1])
                        run_times.append(
                            datetime.now(tz=pytz.utc).replace(hour=hour,
                                                              minute=minute,
                                                              second=0))
                    until = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    run_date = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    last_date = datetime.strptime(time_rule["run_date"],
                                                  "%Y-%m-%d")
                    start_date = datetime.strptime(time_rule["run_date"],
                                                   "%Y-%m-%d")
                    intervalcount = 'no_repeat'
                    every = 0
                    if time_rule["type"] == 'no_repeat':
                        intervalcount = 'no_repeat'
                        time_rule = NoRepeat(run_date, run_times)
                    elif time_rule["type"] == 'daily':
                        intervalcount = 'daily'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        last_date = datetime.strptime(time_rule['until'],
                                                      "%Y-%m-%d")
                        time_rule = RepeatsDaily(run_date, every, until,
                                                 run_times)
                    elif time_rule["type"] == 'weekly':
                        intervalcount = 'weekly'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsWeekly(every, params['days'],
                                                  run_times, run_date, until)
                    elif time_rule["type"] == 'monthly_date':
                        intervalcount = 'monthly_date'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDate(every, params['dates'],
                                                       until, run_times)
                    elif time_rule["type"] == 'monthly_day':
                        intervalcount = 'monthly_day'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDay(every, params['param1'],
                                                      params['days'], until,
                                                      run_times)
                    else:
                        response = {
                            "status":
                            "error",
                            "message":
                            time_rule['type'] + " is not a valid time rule"
                        }
                        self.set_status(400)

                    for daysNo in range((last_date - start_date).days + 1):
                        DataManagement.dataStorage.append(enrollment_id)
                        listParticipants = []
                        participants = ParticipantService.get_participants_in_enrollment(
                            enrollment_id)
                        for participant in participants:
                            listParticipants.append(participant.id)
                        DataManagement.dataStorage.append(listParticipants)
                        DataManagement.dataStorage.append(start_date)
                        DataManagement.dataStorage.append(run_time_values)
                        DataManagement.dataStorage.append("cig_ecig")
                        DataManagement.dataStorage.append(until)
                        DataManagement.dataStorage.append(intervalcount)
                        DataManagement.dataStorage.append(protocol_id)
                        DataManagement.dataStorage.append("scheduled")
                        DataManagement.get_schedule()
                        start_date = start_date + timedelta(days=every)
                else:
                    response = {
                        "status": "error",
                        "message": "Enrollment not owned by account"
                    }
                    self.set_status(401)
            else:
                response = {
                    "status": "error",
                    "message": "Protocol not owned by account"
                }
                self.set_status(401)

            if response is None:
                survey = SurveyService.create_survey(owner_id, protocol_id,
                                                     enrollment_id,
                                                     enable_notes, timeout,
                                                     enable_warnings)
                time_rule_id = TimeRuleService().insert(survey.id, time_rule)
                TaskService.create_task(task_name, survey.id, time_rule_id)
                DataManagement.getSurveyid(survey.id)
                response = {"status": "success"}
                self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #28
0
    def post(self):
        data = json_decode(self.request.body)

        session_id = data["session_id"]
        plugin_url = data["plugin_url"]

        logger.debug("Attempting to register plugin to owner of session %s",
                     session_id)
        owner_id = secure.get_session_owner_id(session_id)
        logger.debug("Owner of session is %s", owner_id)

        if owner_id is not None:

            r = requests.get(plugin_url + "/info")

            if r.status_code != 200:
                self.set_status(400)
                response = {
                    "status": "error",
                    "message":
                    "Something went wrong in the request to the plugin"
                }
            else:
                try:
                    r = r.json()

                    plugin_name = r["name"]
                    plugin_permissions = r["permissions"]
                    plugin_icon = r["icon"]

                    plugin, token = PluginService.register_plugin(
                        plugin_name, owner_id, plugin_url, plugin_icon,
                        plugin_permissions)

                    data = {
                        "owner_id": owner_id,
                        "plugin_id": plugin.id,
                        "token": token,
                        "url": os.environ.get("SYSTEM_URL")
                    }

                    post = requests.post(plugin_url + "/register/", json=data)

                    p = post.json()

                    if post.status_code == 200 and "status" in p and p[
                            "status"] == "success":
                        self.set_status(200)
                        response = {"status": "success"}
                    elif post.status_code != 200:
                        self.set_status(400)
                        response = {
                            "status": "error",
                            "message": "Plugin raised error on registration"
                        }
                    else:
                        self.set_status(400)
                        response = {
                            "status":
                            "error",
                            "message":
                            "Plugin did not respond to request as expected"
                        }
                except ValueError:
                    self.set_status(400)
                    response = {
                        "status": "error",
                        "message":
                        "Plugin did not respond to request as expected"
                    }
        else:
            self.set_status(401)
            response = {"status": "error", "message": "Invalid session"}

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()