예제 #1
0
    def post(reg_id):
        """POST method handler, restarts processing of a request."""
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            reg_details = RegDetails.get_by_id(reg_id)
            # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1)
            failed_status_id = Status.get_status_id('Failed')
            processing_failed = reg_details.processing_status in [failed_status_id]
            report_failed = reg_details.report_status in [failed_status_id]
            # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed
            processing_required = processing_failed or report_failed

            if processing_required:  # pragma: no cover
                reg_device = RegDevice.get_device_by_registration_id(reg_details.id)
                Device.create(reg_details, reg_device.id)
                response = {'message': 'Request performed successfully.'}
            else:
                response = app.json_encoder.encode({'message': _('This request cannot be processed')})

            return Response(json.dumps(response), status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message': _('failed to restart process')
            }

            return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
예제 #2
0
def create_dummy_devices(data,
                         request_type,
                         request,
                         db=None,
                         file_path=None,
                         file_content=None):
    """Helper method to create a dummy request with devices and assign it to a dummy reviewer.
    based on request_type.
    """
    if request_type == 'Registration':
        data.update({'reg_details_id': request.id})
        device = RegDevice.create(data)
        device.technologies = DeviceTechnology.create(device.id,
                                                      data.get('technologies'))
        Device.create(RegDetails.get_by_id(request.id), device.id)
    else:  # De-registration
        # creating sample file
        if not os.path.exists(os.path.dirname(file_path)):
            os.makedirs(os.path.dirname(file_path))
        with open(file_path, 'w') as f:
            for content in file_content:
                f.write(content)
                f.write('\n')

        data = DeRegDevice.curate_args(data, request)
        imei_tac_map = Utilities.extract_imeis_tac_map(data, request)
        created = DeRegDevice.bulk_create(data, request)
        device_id_tac_map = Utilities.get_id_tac_map(created)
        for device in device_id_tac_map:
            device_imeis = imei_tac_map.get(device.get('tac'))
            dereg_imei_list = DeRegImei.get_deregimei_list(
                device.get('id'), device_imeis)
            db.session.execute(DeRegImei.__table__.insert(), dereg_imei_list)
    return request
    def put():
        """PUT method handler, updates a device."""
        reg_id = request.form.to_dict().get('reg_id', None)
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            args = request.form.to_dict()
            schema = DeviceDetailsUpdateSchema()
            reg_details = RegDetails.get_by_id(reg_id)
            reg_device = RegDevice.get_device_by_registration_id(reg_id)

            if reg_details:
                args.update({
                    'reg_details_id': reg_details.id,
                    'status': reg_details.status
                })
            else:
                args.update({'reg_details_id': ''})
            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1)
            processing_failed = reg_details.processing_status in [
                Status.get_status_id('Failed'),
                Status.get_status_id('New Request')
            ]
            report_failed = reg_details.report_status == Status.get_status_id(
                'Failed')
            # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed
            processing_required = processing_failed or report_failed

            reg_device = RegDevice.update(reg_device, args)
            response = schema.dump(reg_device, many=False).data
            response['reg_details_id'] = reg_details.id
            if processing_required:
                Device.create(reg_details, reg_device.id)

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {'message': _('request device addition failed')}

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))

        finally:
            db.session.close()
예제 #4
0
    def index_device(self, conn):
        """Method to index the Registration Device table."""

        try:
            Device.create_index(conn)
            return "Registration Device indexed successfully"
        except SQLAlchemyError as e:
            raise e
예제 #5
0
    def post():
        """POST method handler, creates a new device."""
        reg_id = request.form.to_dict().get('reg_id', None)
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(json.dumps(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            args = request.form.to_dict()
            schema = DeviceDetailsSchema()
            reg_details = RegDetails.get_by_id(reg_id)
            if reg_details:
                args.update({'reg_details_id': reg_details.id})
            else:
                args.update({'reg_details_id': ''})

            validation_errors = schema.validate(args)
            if validation_errors:
                response = Response(
                    json.dumps(validation_errors),
                    status=CODES.get("UNPROCESSABLE_ENTITY"),
                    mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                return response
            reg_device = RegDevice.create(args)
            reg_device.technologies = DeviceTechnology.create(
                reg_device.id, args.get('technologies'))
            response = schema.dump(reg_device, many=False).data
            response['reg_details_id'] = reg_details.id
            reg_details.update_status('Awaiting Documents')
            db.session.commit()
            Device.create(reg_details, reg_device.id)
            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:
            db.session.rollback()
            app.logger.exception(e)

            data = {'message': 'request device addition failed'}

            return Response(json.dumps(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
예제 #6
0
    def post(self):
        """POST method handler, creates registration requests."""
        tracking_id = uuid.uuid4()
        try:
            # get the posted data

            args = RegDetails.curate_args(request)

            # create Marshmallow object
            schema = RegistrationDetailsSchema()

            # validate CNIC number
            if not args['cnic'] or not args['cnic'].isdigit():
                messages = {
                    'from': 'DRS-USSD',
                    'to': args['msisdn'],
                    'content': "CNIC number is mandatory and must be digits only."
                }
                self.messages_list.append(messages.copy())

                print("Printing the jasmin message")
                print(messages)

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))

                return Response(app.json_encoder.encode({"message": "CNIC number is mandatory and must be digits only."}), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            # Multi SIM Validation
            response = ast.literal_eval(args['imeis'])

            message = DeviceDetailsRoutes.multi_sim_validate(response)
            if message is True:
                pass
            elif message is False:
                messages = {
                    'from': 'DRS-USSD',
                    'to': args['msisdn'],
                    'content': "Something went wrong, please try again later"
                }
                self.messages_list.append(messages.copy())

                print("Printing the jasmin message")
                print(self.messages_list)

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))

                data = {'message': "Something went wrong while checking multi sim check please try again later!"}
                return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                mimetype=MIME_TYPES.get('APPLICATION_JSON'))
            else:
                # create messages for user if any
                changed_msgs = []
                for key1, val1 in message.items():
                    for key2, val2 in val1.items():
                        val2 = Ussd_helper.check_forbidden_string(val2)
                        changed_dict = {key2:val2}
                        changed_msgs.append(changed_dict)
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': val2
                        }
                        self.messages_list.append(messages.copy())
                # message = changed_msgs

                print("Printing the jasmin message")
                print(self.messages_list)

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network'])
                app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))

                data = {'message': changed_msgs}
                return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                mimetype=MIME_TYPES.get('APPLICATION_JSON'))

            # validate posted data
            validation_errors = schema.validate(args)

            if validation_errors:
                for key, value in validation_errors.items():

                    str_val = ''
                    if key == "imeis":
                        if isinstance(value[0], dict):
                            for k_i, v_i in value[0].items():
                                str_val = str_val + str(v_i[0] + ' ' + args['imeis'][0][k_i])+". "
                        else:
                            print(validation_errors)
                            str_val = str_val + str(value[0])
                    else:
                        if key == "msisdn":
                            if isinstance(value, list):
                                str_val = str_val + str(value[0])

                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': key +':' + str(value[0]) if not dict else str(str_val)
                    }
                    self.messages_list.append(messages.copy())

                print("Printing the jasmin messages")
                print(self.messages_list)

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network'])
                app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))
                return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:

                # call KeyCloak for admin Token
                admin_token_data = Key_cloak.get_admin_token()

                # call KeyCloak with token for
                user_data = Key_cloak.check_user_get_data(args, admin_token_data)

                # if user is created, a password is set for it
                arguments = Ussd_helper.set_args_dict_for_regdetails(args, user_data)

                reg_response = RegDetails.create(arguments, tracking_id)

                db.session.commit()

                # get GSMA information and make device call. we get the device id
                if reg_response.id:
                    schema2 = rdSchema()
                    response = schema2.dump(reg_response, many=False).data

                    # Todo: add logging here or below after condition check
                    log = EsLog.new_request_serialize(response, 'USSD Registration', method='Post',
                                                imeis=arguments['imeis'])
                    EsLog.insert_log(log)

                    # get the tac from an imei in the dict and search for GSMA record
                    tac = arguments['imeis'][0][0][0:8]
                    gsma_url = str(app.config['CORE_BASE_URL']+app.config['API_VERSION'])+str('/tac/'+tac)

                    # get GSMA record against each TAC and match them with IMEIs count given in list
                    gsma_response = requests.get(gsma_url).json()

                    if gsma_response["gsma"] is None:
                        # GSMA record not found for the said TAC
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': "No record found for TAC:" + str(tac)
                        }
                        self.messages_list.append(messages.copy())

                        print("Printing the jasmin messages")
                        print(self.messages_list)

                        jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network'])
                        app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))

                        data = {'message': messages['content']}

                        return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                        mimetype=MIME_TYPES.get('APPLICATION_JSON'))

                    else:

                        # set device data args
                        device_arguments = Ussd_helper.set_args_dict_for_devicedetails(reg_response, arguments, gsma_response)

                        reg_details = RegDetails.get_by_id(reg_response.id)

                        if reg_details:
                            device_arguments.update({'reg_details_id': reg_details.id})
                        else:
                            device_arguments.update({'reg_details_id': ''})

                        device_arguments.update({'device_type': 'Smartphone'})

                        reg_device = RegDevice.create(device_arguments)

                        reg_device.technologies = DeviceTechnology.create(
                            reg_device.id, device_arguments.get('technologies'), True)

                        device_status = 'Pending Review'

                        reg_details.update_status(device_status)

                        DeviceQuotaModel.get_or_create(reg_response.user_id, 'ussd')

                        Utilities.create_directory(tracking_id)

                        db.session.commit()

                        device_schema = DeviceDetailsSchema()
                        device_serialize_data = device_schema.dump(reg_device, many=False).data
                        log = EsLog.new_device_serialize(device_serialize_data, request_type="USSD Device Registration",
                                                         regdetails=reg_details,
                                                         reg_status=device_status, method='Post')
                        EsLog.insert_log(log)

                        Device.create(reg_details, reg_device.id, ussd=True)

                        # delay the process 5 seconds to complete the process
                        time.sleep(5)

                        # get the device details
                        reg_details = RegDetails.get_by_id(reg_response.id)

                        status_msg = Ussd_helper.set_message_for_user_info(reg_details.status)

                        # if reg_details.status == 6:
                        status_msg = status_msg + " Your device tracking id is: " + str(reg_details.id)

                        # send user a details about device
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': status_msg
                        }
                        self.messages_list.append(messages.copy())

                        # send username and password to the new user
                        if 'password' in user_data:
                            messages = {
                                'from': 'DRS-USSD',
                                'to': args['msisdn'],
                                'content': "New user credentials are, username: "******" and password: "******"Jasmin API response: " + str(jasmin_send_response.status_code))
                        app.logger.info("Printing the message array in CLI mode.")
                        app.logger.info(self.messages_list)
                        response = {
                            'message': 'Device registration has been processed successfully.'
                        }

                        if status_msg:
                            response['status_response'] = status_msg
                        return Response(json.dumps(response), status=CODES.get("OK"),
                                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))

                else:
                    # error in regdetails
                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': "Registration request failed, check upload path or database connection"
                    }
                    self.messages_list.append(messages.copy())

                    jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network'])
                    app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code))

                    # response = schema.dump(response, many=False).data
                    data = {'message': [_('Device undergone the process. Please hold your breath.')]}
                    return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                    mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)
            data = {
                'message': [_('Registration request failed, check upload path or database connection')]
            }

            return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()