Esempio n. 1
0
def delete_measurement(system_uid, measurement, time):
    if not can_user_edit_system(system_uid):
        return jsonify(status='error',
                       message='no rights to delete this entry')

    timestamp = __timestamp_from_time_str(time)
    measurement_dao = MeasurementDAO(current_app)
    measurement_dao.delete_measurement(system_uid, timestamp, measurement)
    return jsonify(status='ok')
Esempio n. 2
0
def update_measurement(system_uid, measurement, time):
    """Action connected to the measurement form"""
    if not can_user_edit_system(system_uid):
        return render_template('no_access.html')
    value = request.form['value']
    timestamp = __timestamp_from_time_str(time)
    measurement_dao = MeasurementDAO(current_app)
    measurement_dao.update_measurement(system_uid, timestamp, measurement,
                                       value)
    # go back to history
    return redirect(
        url_for('frontend.sys_data',
                system_uid=system_uid,
                measurement=measurement))
Esempio n. 3
0
def sys_data(system_uid, measurement):
    default_page = 1
    dav_api = AnalyticsAPI(current_app)
    metadata = json.loads(services.get_system(system_uid))
    readings = json.loads(
        dav_api.get_all_data_for_system_and_measurement(
            system_uid, measurement, default_page))
    measurements = readings['data']
    measurement_dao = MeasurementDAO(current_app)
    measurement_types = {
        mt['name']: (mt['full_name'], mt['unit'])
        for mt in measurement_dao.measurement_types()
    }
    measurement_name = measurement_types[measurement][0]
    measurement_unit = measurement_types[measurement][1]
    return render_template('sys_data.html', **locals())
Esempio n. 4
0
def upload_measurements(system_uid):
    """Action connected to the measurement form"""
    current_app.logger.info("upload_measurements()")
    if not can_user_edit_system(system_uid):
        return render_template('no_access.html')
    try:
        import_file = request.files['importfile']
        measurement_dao = MeasurementDAO(current_app)
        # we are using a NamedTemporaryFile because our web server can'th
        # handle TemporaryFile in combination with pandas
        with tempfile.TemporaryFile() as outfile:
            import_file.save(outfile)
            outfile.seek(0)
            df = pandas.read_csv(outfile, sep='\t', index_col=None, header=0)
            measurements = []
            for i, row in df.iterrows():
                for col in df.columns:
                    try:
                        prefix = UPLOAD_MT_MAP[col]
                        if prefix == 'time':
                            mtime = parse_time(row[col])
                        else:
                            value = parse_value(row[col])
                            if not np.isnan(value):
                                measurements.append((prefix, value))

                    except KeyError:
                        flash("not found: '%s'" % col, 'error')
                # all columns processed, now store
                if measurements > 0:
                    current_app.logger.info('storing for system %s',
                                            system_uid)
                    try:
                        measurement_dao.store_measurements(
                            system_uid, mtime, measurements)
                    except:
                        flash(
                            'errors during import, you are likely trying to add values that already exist (%s)'
                            % (str(mtime)), 'error')

        ## standard message
        flash('Uploaded values were stored.')
    except BadRequestKeyError:
        flash('Please provide an upload file', 'error')
    except:  ## pandas.io.common.CParserError our old server can not handle it
        flash('Please provide a valid tsv file', 'error')
    return redirect(url_for('frontend.view_system', system_uid=system_uid))
Esempio n. 5
0
def sys_edit_data(system_uid, measurement, created_at):
    dav_api = AnalyticsAPI(current_app)
    metadata = json.loads(services.get_system(system_uid))
    data = json.loads(
        dav_api.get_measurement_by_created_at(system_uid, measurement,
                                              created_at))

    measurement_dao = MeasurementDAO(current_app)
    measurement_types = {
        mt['name']: (mt['full_name'], mt['unit'])
        for mt in measurement_dao.measurement_types()
    }
    measurement_name = measurement_types[measurement][0]
    measurement_unit = measurement_types[measurement][1]
    if measurement_unit == 'celsius':
        measurement_unit = '°C'
    return render_template('edit_data.html', **locals())
Esempio n. 6
0
def record_measurements(system_uid):
    """Action connected to the measurement form"""
    if not can_user_edit_system(system_uid):
        return render_template('no_access.html')

    sys_uid = request.form['system-uid']
    measure_date = request.form['measure-date']
    measure_time = request.form['measure-time']
    mtime = utils.get_form_time(measure_date, measure_time)
    measurement_dao = MeasurementDAO(current_app)
    measurement_types = [
        mt['name'] for mt in measurement_dao.measurement_types()
    ]
    measurements = []
    for prefix in measurement_types:
        if prefix + '-use' in request.form:
            value = float(request.form[prefix + '-value'])
            measurements.append((prefix, value))
    if measurements > 0:
        measurement_dao.store_measurements(system_uid, mtime, measurements)

    return redirect(url_for('frontend.view_system', system_uid=system_uid))
Esempio n. 7
0
 def __init__(self, app):
     self.systemDAO = SystemDAO(app)
     self.userDAO = UserDAO(app)
     self.metadataDAO = MetadataDAO(app)
     self.subscriptionDAO = SubscriptionDAO(app)
     self.measurementDAO = MeasurementDAO(app)
Esempio n. 8
0
class API:
    def __init__(self, app):
        self.systemDAO = SystemDAO(app)
        self.userDAO = UserDAO(app)
        self.metadataDAO = MetadataDAO(app)
        self.subscriptionDAO = SubscriptionDAO(app)
        self.measurementDAO = MeasurementDAO(app)

    ###########################################################################
    # SystemAPI
    ###########################################################################

    def get_system(self, systemUID):

        result = self.systemDAO.get_system(systemUID)
        systemID = result[0]
        # Get the crops
        results = self.systemDAO.crops_for_system(systemID)
        crops = []
        for crop in results:
            crops.append({'id': crop[0], 'name': crop[1], 'count': crop[2]})
        # Get the grow bed media
        results = self.systemDAO.getGrowBedMediaForSystem(systemID)
        media = []
        for medium in results:
            media.append({'name': medium[0], 'count': medium[1]})
        # Get the organisms
        results = self.systemDAO.organisms_for_system(systemID)
        organisms = []
        for organism in results:
            organisms.append({
                'id': organism[0],
                'name': organism[1],
                'count': organism[2]
            })
        # Get the status
        status = self.systemDAO.getStatusForSystem(systemUID)[0]
        # Recompile the system
        return {
            'ID': result[0],
            'UID': result[1],
            'user': result[2],
            'name': result[3],
            'creationTime': str(result[4]),
            'startDate': str(result[5]),
            'location': {
                'lat': str(result[6]),
                'lng': str(result[7])
            },
            'technique': result[8],
            'status': status,
            'gbMedia': media,
            'crops': crops,
            'organisms': organisms,
        }

    def getSystemsForUser(self, userID):
        systems = []
        results = self.systemDAO.getSystemsForUser(userID)
        for result in results:
            systems.append({
                'ID': result[0],
                'UID': result[1],
                'name': result[2]
            })
        return json.dumps(systems)

    def create_system(self, system):
        """this is just a delegation to the DAO, no JSON serialization
        because it reduces reusability"""
        return self.systemDAO.create_system(system)

    def update_system(self, system):
        """this is just a delegation to the DAO, no JSON serialization
        because it reduces reusability"""
        return self.systemDAO.update_system(system)

    ###########################################################################
    # UserAPI
    ###########################################################################

    def getUserID(self, googleID):
        userID = self.userDAO.getUserID(googleID)
        return json.dumps({'userID': userID})

    def hasUser(self, googleID):
        count = self.userDAO.hasUser(googleID)
        return json.dumps({'hasUser': count == 1})

    def createUser(self, googleProfile):
        userID = self.userDAO.createUser(googleProfile)
        return json.dumps({'userID': userID})

    ###########################################################################
    # MetadataAPI
    ###########################################################################

    def catalogs(self):
        results = self.metadataDAO.catalogs()
        enums = defaultdict(list)
        for result in results:
            table = result[0]
            if not enums[table]:
                enums[table] = []
            enums[table].append({'ID': result[1], 'name': result[2]})
        return enums

    def subscribe(self, email):
        subscriptionID = self.subscriptionDAO.subscribe(email)
        return {'status': 'ok', 'subscriptionID': subscriptionID}

    def measurement_types(self):
        return json.dumps(self.measurementDAO.measurement_types())
Esempio n. 9
0
def view_system(system_uid):
    user_sql_id = session.get('uid')
    system = System()
    system_neo4j = system.get_system_by_uid(system_uid)
    if not system_neo4j:
        abort(404)

    # otherwise continue
    logged_in_user = User(user_sql_id).find()
    created_date = convert_milliseconds_to_normal_date(
        system_neo4j[0][0]['creation_time'])
    system_location = get_address_from_lat_lng(
        system_neo4j[0][0]['location_lat'], system_neo4j[0][0]['location_lng'])
    system_mysql = system_neo4j
    user_privilege = system.get_user_privilege_for_system(
        user_sql_id, system_uid)
    system_admins = system.get_system_admins(system_uid)
    display_names = [a['user']['displayName'] for a in system_admins]
    system_admin_str = ', '.join(display_names)
    system_participants = system.get_system_participants(system_uid)
    system_subscribers = system.get_system_subscribers(system_uid)
    participants_pending_approval = system.get_participants_pending_approval(
        system_uid)
    subscribers_pending_approval = system.get_subscribers_pending_approval(
        system_uid)
    if user_privilege == "SYS_ADMIN" or user_privilege == "SYS_PARTICIPANT":
        privacy_options = [Privacy.PARTICIPANTS, Privacy.PUBLIC]
        privacy_default = Privacy.PARTICIPANTS
    else:
        privacy_options = [Privacy.PUBLIC]
        privacy_default = Privacy.PUBLIC

    privacy_info = Privacy(privacy_options, privacy_default, 'system_social',
                           user_sql_id)
    posts = system.get_system_recent_posts(system_uid)
    comments = system.get_system_recent_comments(system_uid)
    likes = system.get_system_recent_likes(system_uid)
    total_likes = system.get_total_likes_for_system_posts(system_uid)
    post_owners = system.get_system_post_owners(system_uid)

    dav_api = AnalyticsAPI(current_app)
    json_output_measurement = dav_api.get_system_measurements(system_uid)
    latest_measurements = None
    if "error" not in json_output_measurement:
        latest_measurements = json_output_measurement['measurements']

    # this is accessing the top level in order to access the system's meta information
    # the actual solution should be to move this view into the top level to
    # have a clear directed dependency
    general_api = API(current_app)
    system_metadata = general_api.get_system(system_uid)
    growbed_media_str = ', '.join(
        [m['name'] for m in system_metadata['gbMedia']])
    crops_str = ', '.join([
        '%s (%d)' % (c['name'], c['count']) for c in system_metadata['crops']
    ])
    aquatic_str = ', '.join([
        '%s (%d)' % (c['name'], c['count'])
        for c in system_metadata['organisms']
    ])

    strip_measurement_types = [
        'alkalinity', 'ammonium', 'chlorine', 'hardness', 'nitrate', 'nitrite',
        'ph'
    ]
    measurement_dao = MeasurementDAO(current_app)
    all_measurement_types = [
        mt['name'] for mt in measurement_dao.measurement_types()
    ]
    img_url = image_url(system_uid)
    return render_template("system_view.html", **locals())