Ejemplo n.º 1
0
 def handle_logo(self, data):
     logo = data.get('logo')
     logo_dark = data.get('logoDark')
     if logo is not None:
         if logo < 1:
             data.pop('logo')
         else:
             upload_info = UploadInfo.query \
                 .join(User, User.id == UploadInfo.userIntID) \
                 .filter(UploadInfo.id == logo,
                         User.tenantID == g.tenant_uid) \
                 .first()
             if not upload_info:
                 raise DataNotFound(field='logo')
     if logo_dark is not None:
         if logo_dark < 1:
             data.pop('logoDark')
         else:
             upload_info = UploadInfo.query \
                 .join(User, User.id == UploadInfo.userIntID) \
                 .filter(UploadInfo.id == logo_dark,
                         User.tenantID == g.tenant_uid) \
                 .first()
             if not upload_info:
                 raise DataNotFound(field='logoDark')
Ejemplo n.º 2
0
    def validate_from(self, data):
        product_uid = data.get('productID')
        product = db.session \
            .query(Product.cloudProtocol) \
            .filter_tenant(tenant_uid=g.tenant_uid) \
            .filter(Product.productID == product_uid) \
            .first()
        if not product:
            raise DataNotFound(field='productID')

        device_uid = data.get('deviceID')
        # device_uid can be '+' or deviceID of device
        if device_uid != '+':
            device = db.session \
                .query(Device.id) \
                .filter_tenant(tenant_uid=g.tenant_uid) \
                .filter(Device.productID == product_uid, Device.deviceID == device_uid) \
                .first()
            if not device:
                raise DataNotFound(field='deviceID')

        topic = data.get('topic')
        # If the protocol is LwM2M,the fixed value of topic is 'ad/#'
        if product.cloudProtocol == 3 and topic != 'ad/#':
            raise DataNotFound(field='topic')
        else:
            data_stream = db.session \
                .query(DataStream.topic) \
                .filter_tenant(tenant_uid=g.tenant_uid) \
                .filter(DataStream.productID == product_uid, DataStream.topic == topic) \
                .first()
            if not data_stream:
                raise DataNotFound(field='topic')
Ejemplo n.º 3
0
 def validate_uplink_system(self, data):
     uplink_system = data.get('upLinkSystem')
     if uplink_system == 1:
         data['parentDevice'], data['gateway'] = None, None
     elif uplink_system == 2 and isinstance(data.get('parentDevice'), int):
         parent_device = data['parentDevice']
         end_device_id = EndDevice.query \
             .filter_tenant(tenant_uid=g.tenant_uid) \
             .filter(EndDevice.id == parent_device) \
             .with_entities(EndDevice.id).first()
         if not end_device_id:
             raise DataNotFound(field='parentDevice')
         data['parentDevice'], data['gateway'] = end_device_id, None
     elif uplink_system == 3 and isinstance(data.get('gateway'), int):
         gateway = data['gateway']
         gateway_id = Gateway.query \
             .filter_tenant(tenant_uid=g.tenant_uid) \
             .filter(Gateway.id == gateway) \
             .with_entities(Gateway.id).first()
         if not gateway_id:
             raise DataNotFound(field='gateway')
         data['parentDevice'], data['gateway'] = None, gateway_id
     else:
         raise FormInvalid(field='upLinkSystem')
     return data
Ejemplo n.º 4
0
    def many(self, limit: int = None, allow_none=True, expect_result: int = None):
        query = self.filter_tenant()
        if limit:
            query = query.limit(limit)
        result = query.all()

        if not allow_none and not result:
            raise DataNotFound(field='url')
        if not allow_none and len(result) != expect_result:
            raise DataNotFound(field='url')
        return result
Ejemplo n.º 5
0
 def validate_data(self, in_data):
     tenant_uid = in_data.get('tenantID')
     rule = db.session.query(Rule.id) \
         .filter(Rule.id == in_data.get('ruleIntID'),
                 Rule.tenantID == tenant_uid) \
         .first()
     if not rule:
         raise DataNotFound(field='ruleIntID')
     device = db.session.query(Device.id) \
         .filter(Device.tenantID == tenant_uid,
                 Device.deviceID == in_data.get('deviceID')) \
         .first()
     if not device:
         raise DataNotFound(field='deviceID')
Ejemplo n.º 6
0
def backend_callback():
    request_dict = request.get_json()
    request_dict['callback_date'] = datetime.now()
    if not request_dict:
        raise DataNotFound()
    callback_action = request_dict.get('action')
    handle_action_funcs = {
        'client_connected': client_connected_callback,
        'client_disconnected': client_disconnected_callback,
        'message_acked': message_acked_callback,
    }
    if not handle_action_funcs.get(callback_action):
        raise DataNotFound()
    handle_action = handle_action_funcs[callback_action]
    handle_action(request_dict)
    return '', 201
Ejemplo n.º 7
0
 def validate_devices(self, value):
     devices_count = Device.query \
         .filter_tenant(tenant_uid=g.tenant_uid) \
         .filter(Device.deviceID.in_(set(value))) \
         .count()
     if devices_count != len(value):
         raise DataNotFound(field='devices')
Ejemplo n.º 8
0
def handle_action_config(record=None):
    cache = Cache()
    dict_code = cache.dict_code
    action_config = record.get('config')
    action_type = record.get('actionType')
    record['actionTypeLabel'] = dict_code.get('actionType').get(action_type) \
        .get(f'{g.language}Label')

    if action_type == 1:
        alert_severity = action_config.get('alertSeverity')
        severity_label = dict_code.get('alertSeverity').get(alert_severity) \
            .get(f'{g.language}Label')
        action_config['alertSeverityLabel'] = severity_label
    elif action_type == 3 and action_config.get('token'):
        ...
    elif action_type == 4:
        device_uid = action_config.get('deviceID')
        device = db.session.query(Device.deviceName) \
            .filter_tenant(tenant_uid=g.tenant_uid) \
            .filter(Device.deviceID == device_uid) \
            .first()
        if not device:
            raise DataNotFound(field='deviceID')
        action_config['deviceName'] = device.deviceName
    else:
        pass
    return record
Ejemplo n.º 9
0
def export_devices():
    device_count = db.session.query(func.count(Device.id)) \
        .filter(Device.tenantID == g.tenant_uid).scalar()
    if device_count and device_count > 10000:
        raise ResourceLimited(field='devices')
    if device_count == 0:
        raise DataNotFound(field='devices')
    export_url = current_app.config.get('EXPORT_EXCEL_TASK_URL')
    request_json = {
        'tenantID': g.tenant_uid,
        'language': g.language
    }
    with SyncHttp() as sync_http:
        response = sync_http.post(export_url, json=request_json)
    handled_response = handle_task_scheduler_response(response)
    if handled_response.get('status') == 3:
        query_status_url = url_for('base.get_task_scheduler_status')[7:]
        task_id = handled_response['taskID']
        record = {
            'status': 3,
            'taskID': task_id,
            'message': 'Devices export is in progress',
            'result': {
                'statusUrl': f"{query_status_url}?taskID={task_id}"
            }
        }
    else:
        record = {
            'status': 4,
            'message': handled_response.get('error') or 'Devices export failed',
        }
    return jsonify(record)
Ejemplo n.º 10
0
def backend():
    file_type = request.args.get('fileType', None, type=str)
    filename = request.args.get('filename', None, type=str)
    if file_type != 'image':
        raise DataNotFound(field='url')
    dst_path = current_app.config.get('LOGOS_PATH')
    return send_from_directory(dst_path, filename)
Ejemplo n.º 11
0
 def validate_region(self, value):
     if value is None:
         return
     cache = Cache()
     dict_code_cache = cache.dict_code
     region_cache = dict_code_cache['region']
     if value not in region_cache.keys():
         raise DataNotFound(field='region')
Ejemplo n.º 12
0
 def validate_fcnt_check(self, value):
     if value is None:
         return
     cache = Cache()
     dict_code_cache = cache.dict_code
     fcnt_check_cache = dict_code_cache['fcntCheck']
     if value not in fcnt_check_cache.keys():
         raise DataNotFound(field='fcntCheck')
Ejemplo n.º 13
0
def message_acked_callback(request_dict) -> None:
    """ Update the publish status when the device receives the publish message """

    device_id = request_dict.get('client_id')
    payload = request_dict.get('payload')
    if not device_id or not payload:
        raise DataNotFound()
    try:
        load_payload = json.loads(payload)
    except Exception:
        raise DataNotFound()
    task_id = load_payload.get('task_id')
    if not task_id:
        raise DataNotFound()
    publish_log = PublishLog.query.filter(PublishLog.taskID == task_id).first_or_404()
    publish_log.publishStatus = 2
    publish_log.update()
Ejemplo n.º 14
0
def view_tenant(tenant_id):
    if g.role_id != 1:
        raise DataNotFound(field='url')

    query = db.session.query(Tenant,
                             func.coalesce(Tenant.company, User.username).label('tenantName')) \
        .outerjoin(User) \
        .filter(Tenant.id == tenant_id)

    record = query.to_dict(code_list=['tenantType'])
    return jsonify(record)
Ejemplo n.º 15
0
 def handle_app_groups(self, in_data):
     groups_uid = in_data.get('groups')
     if not groups_uid:
         return in_data
     groups = Group.query \
         .filter_tenant(tenant_uid=g.tenant_uid) \
         .filter(Group.groupID.in_(set(groups_uid))).all()
     if len(groups_uid) != len(groups):
         raise DataNotFound(field='groups')
     in_data['groups'] = groups
     return in_data
Ejemplo n.º 16
0
 def handle_data_points(self, data):
     product_uid = self.get_origin_obj('productID')
     data_point_ids = data.get('dataPoints')
     if not data_point_ids:
         return data
     data_points = DataPoint.query \
         .filter(DataPoint.productID == product_uid,
                 DataPoint.id.in_(set(data_point_ids))).all()
     if len(data_points) != len(data_point_ids):
         raise DataNotFound(field='dataPoints')
     data['data_points'] = data_points
     return data
Ejemplo n.º 17
0
 def convert_data_points(self, data):
     data_point_ids = data.get('dataPoints')
     if data_point_ids:
         data_points = DataPoint.query \
             .filter_tenant(tenant_uid=g.tenant_uid) \
             .filter(DataPoint.id.in_(set(data_point_ids))).all()
         if len(data_points) != len(data_point_ids):
             raise DataNotFound(field='dataPoints')
     else:
         data_points = []
     data['dataPoints'] = data_points
     return data
Ejemplo n.º 18
0
 def handle_load_data(self, data):
     product_uid: str = data.get('productID')
     if not isinstance(product_uid, str):
         raise FormInvalid(field='productID')
     product = Product.query. \
         filter_tenant(tenant_uid=g.tenant_uid) \
         .filter(Product.productID == product_uid).first()
     if not product:
         raise DataNotFound(field='productID')
     data['productID'] = product.productID
     data['cloudProtocol'] = product.cloudProtocol
     data = handle_extend_type_attr(data)
     return data
Ejemplo n.º 19
0
 def handle_origin_data(self, data):
     product_uid = data.get('productID')
     if not isinstance(product_uid, str):
         raise FormInvalid(field='productID')
     product = Product.query \
         .filter_tenant(tenant_uid=g.tenant_uid) \
         .filter(Product.productID == product_uid).first()
     if not product:
         raise DataNotFound(field='productID')
     data['productType'] = product.productType
     data['productID'] = product.productID
     data['cloudProtocol'] = product.cloudProtocol
     data['gatewayProtocol'] = product.gatewayProtocol
     return data
Ejemplo n.º 20
0
    def validate_product(self, value):
        if self._validate_obj('productID', value):
            return
        product = db.session.query(Product.id) \
            .filter(Product.userIntID == g.user_id, Product.productID == value) \
            .first()
        if not product:
            raise DataNotFound(field='productID')

        codec = db.session.query(Codec.id) \
            .filter(Codec.tenantID == g.tenant_uid, Codec.productID == value) \
            .first()
        if codec:
            raise DataExisted(field='productID')
Ejemplo n.º 21
0
 def handle_loads(self, data):
     group_id = request.view_args.get('group_id')
     devices_id = data['devices']
     group_devices_id = db.session.query(GroupDevice.c.deviceIntID) \
         .join(Group, Group.groupID == GroupDevice.c.groupID) \
         .filter(Group.id == group_id).all()
     add_devices_id = set(devices_id).difference(set(group_devices_id))
     if len(group_devices_id) + len(add_devices_id) > 1001:
         raise ResourceLimited(field='devices')
     devices = Device.query.filter_tenant(tenant_uid=g.tenant_uid) \
         .filter(Device.id.in_(add_devices_id)).all()
     if len(devices) != len(add_devices_id):
         raise DataNotFound(field='devices')
     data['devices'] = devices
     return data
Ejemplo n.º 22
0
def update_system_info():
    request_dict = request.get_json()
    if not request_dict:
        raise APIException()
    if g.tenant_uid:
        raise DataNotFound(field='url')
    system_info_list = SystemInfo.query.all()
    for system_info in system_info_list:
        new_value = request_dict.get(system_info.key)
        if not new_value:
            continue
        if isinstance(new_value, bytes):
            new_value = new_value.decode('utf-8')
        system_info.value = new_value
    db.session.commit()
    return ''
Ejemplo n.º 23
0
def update_tenant(tenant_id):
    if g.role_id != 1:
        raise DataNotFound(field='url')

    tenant = Tenant.filter(Tenant.id == tenant_id).first_or_404()
    request_dict = request.get_json()
    if not request_dict:
        raise APIException()
    enable = request_dict.get('enable')
    if enable not in [0, 1]:
        raise FormInvalid(field='enable')

    update_dict = {'enable': enable}
    updated_tenant = tenant.update(update_dict)
    record = updated_tenant.to_dict()
    return jsonify(record)
Ejemplo n.º 24
0
 def handle_user_auth_type(self, data):
     if 'user_id' not in g:
         data['userAuthType'] = 1
     groups_uid = self.get_request_data(key='groups')
     auth_type = data.get('userAuthType')
     if auth_type not in (1, 2):
         raise FormInvalid(field='userAuthType')
     if auth_type == 2 and groups_uid:
         groups = Group.query \
             .filter_tenant(tenant_uid=g.tenant_uid) \
             .filter(Group.groupID.in_(set(groups_uid))).all()
         if len(groups_uid) != len(groups):
             raise DataNotFound(field='groups')
         data['groups'] = groups
     else:
         data.pop('groups', None)
     return data
Ejemplo n.º 25
0
def list_tenants():
    if g.role_id != 1:
        raise DataNotFound(field='url')

    query = db.session.query(Tenant,
                             func.coalesce(Tenant.company, User.username).label('tenantName')) \
        .outerjoin(User)

    tenant_name = request.args.get('tenantName_like')
    if tenant_name:
        query = query \
            .filter(Tenant.company.ilike(u'%{0}%'.format(tenant_name)))
        person_tenant_query = db.session \
            .query(Tenant, func.coalesce(Tenant.company, User.username).label('tenantName')) \
            .join(User, User.tenantID == Tenant.tenantID) \
            .filter(User.username.ilike(u'%{0}%'.format(tenant_name)))
        query = query.union(person_tenant_query)

    records = query.pagination(code_list=['tenantType'])
    return jsonify(records)
Ejemplo n.º 26
0
def signup_invite_user(token):
    jwt = JWT(current_app.config['SECRET_KEY'])
    try:
        data = jwt.loads(token)
    except Exception:
        raise FormInvalid(field='token')

    if not data.get('invitation_id'):
        raise FormInvalid(field='invitation')
    invitation = Invitation.query \
        .join(Tenant, Tenant.tenantID == Invitation.tenantID) \
        .filter(Invitation.id == data.get('invitation_id'),
                Invitation.inviteStatus == 0, Tenant.enable == 1) \
        .first()
    if not invitation:
        raise DataNotFound(field='invitation')
    invitation.inviteStatus = 1
    invite_user = {
        'roleIntID': invitation.roleIntID,
        'tenantID': invitation.tenantID
    }
    return invite_user
Ejemplo n.º 27
0
 def first_or_404(self):
     query = self.filter_tenant()
     result = query.first()
     if result is None:
         raise DataNotFound()
     return result
Ejemplo n.º 28
0
def run_code():
    """
    codec api response
    {
       "error": {
          "decode:": "error message"
       },
       "output": {
          "status_code": 0,
          "result": {
             "data_type": "event",
             "data": {
                "humidity": {
                   "time": 1547660823,
                   "value": 34
                },
                "temperature": {
                   "time": 1547660823,
                   "value": -3.7
                }
             }
          }
       }
    }
    """
    request_json = CodeRunSchema.validate_request()
    analog_type = request_json.get('analogType')
    protocol = db.session.query(Product.cloudProtocol) \
        .filter(Product.productID == request_json.get('productID')) \
        .scalar()
    if protocol is None:
        raise DataNotFound(field='productID')
    request_url = f"http://{current_app.config['CODEC_NODE']}/api/v1/codec"
    with SyncHttp() as sync_http:
        response = sync_http.post(request_url, json=request_json)

    if response.responseCode != 200:
        try:
            errors = json.loads(response.responseContent)
        except Exception:
            errors = {
                'codec': response.responseContent
            }
        raise APIException(errors=errors)

    response_json = json.loads(response.responseContent)
    # return response if it has error
    if 'error' in response_json:
        return jsonify(response_json)

    output_data = response_json.get('output')
    status_code = output_data.get('status_code')
    # If status code is 1(ERROR)
    # or analog type is 2(encode)
    # return response without validate
    if status_code == 1 or analog_type == 2:
        return jsonify(response_json)

    result = output_data.get('result')
    error_dict = {}
    validate_data, validate_error = DecodeSchema().load(result)
    for key, value in validate_error.items():
        error_dict[key] = value[0][:-1]

    data_stream = DataStream.query \
        .filter(DataStream.productID == request_json.get('productID'),
                DataStream.tenantID == g.tenant_uid, DataStream.topic == request_json.get('topic'),
                DataStream.streamID == validate_data.get('stream_id')) \
        .first()
    if not data_stream:
        raise DataNotFound(field='data_stream')

    error, passed_data = validate_decode_response(data_stream, validate_data)
    error_dict.update(error)
    record = {
        'output': {
            'status_code': status_code,
            'result': passed_data
        }
    }
    if error_dict:
        record['error'] = error_dict
    return jsonify(record)
Ejemplo n.º 29
0
 def handle_not_found(error):
     if request.path.startswith('/api/'):
         return DataNotFound('url')
     return error