Beispiel #1
0
def login(request):
    res = json.loads(DEFAULT_RESPONSE)

    ## session check ##
    if request.user:
        res['msg'] = 'session active.'
        res['status'] = True
        res['data'] = {
            'email': request.user.email,
            'subscription_type': request.user.subscription_type,
            'subscription_zones': request.user.subscription_zones,
            'is_active': request.user.is_active
        }
        # userzones
        res['data']['userzones'] = [[
            uz.uzid, uz.polygon
        ] for uz in userzone.objects(email=request.user.email)]
        # projects
        res['data']['projects'] = [[z.zid, z.polygon]
                                   for z in zone.objects(ztype='project')]
        return HttpResponse(json.dumps(res, default=default))

    ## jugaad ##
    if '_auth_user_id' in request.session:
        request.session.pop('_auth_user_id')

    email = request.GET.get('email', '')
    password = request.GET.get('password', '')

    user = auth.authenticate(request=request,
                             username=email,
                             password=password)
    if user:
        auth.login(request, user)
        res['msg'] = 'login successful.'
        res['status'] = True
        res['data'] = {
            'email': email,
            'subscription_type': user.subscription_type,
            'subscription_zones': user.subscription_zones,
            'is_active': user.is_active
        }
        # userzones
        res['data']['userzones'] = [[
            uz.uzid, uz.polygon
        ] for uz in userzone.objects(email=request.user.email)]
        # projects
        res['data']['projects'] = [[z.zid, z.polygon]
                                   for z in zone.objects(ztype='project')]
    else:
        res['msg'] = 'email/password does not match.'
        res['status'] = False
    return HttpResponse(json.dumps(res, default=default))
Beispiel #2
0
def visualisation(request):
    res = json.loads(DEFAULT_RESPONSE)
    data = request.GET.get('data', 'waveheight')

    try:
        data = []
        for z in zone.objects():
            data.append([z.zid, z.triangles])
        res['data'] = data
        res['status'] = True
        res['msg'] = 'success'
    except Exception, e:
        print e
        res['status'] = False
        res['msg'] = 'Someting went wrong.'
Beispiel #3
0
def getZoneData(request):
    res = json.loads(DEFAULT_RESPONSE)
    zid = request.GET.get('zid', None)
    month = request.GET.get('month', None)
    day = request.GET.get('day', None)
    try:
        if zid and month and day:  # zone
            tri = REDIS.get(zid + '_' + month)
            if tri:
                ztype, tri = tri.split('$')
                tri = json.loads(tri)
            else:
                z = zonedata.objects(zid=zid, month=month).first()
                tri = z.triangles
                ztype = z.ztype
                if ztype == 'zone':
                    REDIS.set(zid + '_' + month,
                              '{}${}'.format(z.ztype, json.dumps(tri)))

            if ztype == 'zone':
                for i in range(len(tri)):
                    for j in range(len(tri[i])):
                        if isinstance(tri[i][j], dict):
                            if day in tri[i][j]:
                                tri[i][j] = tri[i][j][day]
                            else:
                                tri[i][j] = None
            if tri:
                res['triangles'] = tri
                res['status'] = True
                res['msg'] = 'success'
        elif zid:  # bathymetry
            z = zone.objects(zid=zid).first()
            tri = z.triangles

            if tri:
                res['triangles'] = tri
                res['status'] = True
                res['msg'] = 'success'
    except Exception, e:
        print e
        res['status'] = False
        res['msg'] = 'Someting went wrong.'
Beispiel #4
0
def getZone(request):
    res = json.loads(DEFAULT_RESPONSE)
    try:
        zones = []
        bathymetry = []
        shorelines = []

        for z in zone.objects().exclude('triangles'):
            if z.ztype == 'zone':
                #zones.append({'type':'Feature', 'properties':{'zid':z.zid, 'name':z.name}, 'geometry':z.polygon})
                zones.append({
                    'zid': z.zid,
                    'name': z.name,
                    'polygon': z.polygon
                })
            elif z.ztype == 'bathymetry':
                #bathymetry.append({'type':'Feature', 'properties':{'zid':z.zid, 'name':z.name}, 'geometry':z.polygon})
                bathymetry.append({
                    'zid': z.zid,
                    'name': z.name,
                    'polygon': z.polygon
                })

        for s in shoreline.objects():
            shorelines.append({
                'lid': s.lid,
                'name': s.name,
                'line': s.line,
                'date': s.date.strftime('%Y-%m-%d')
            })

        res['zones'] = zones
        res['bathymetry'] = bathymetry
        res['shoreline'] = []
        res['status'] = True
        res['msg'] = 'success'
    except Exception, e:
        print e
        res['status'] = False
        res['msg'] = 'Someting went wrong.'
Beispiel #5
0
def pointData(request):
    res = json.loads(DEFAULT_RESPONSE)
    point = request.GET.get('point', None)
    data = request.GET.get('data', None)
    if request.GET.get('warmup', None):
        request.user = User.objects(email='*****@*****.**').first()
    month = request.GET.get('month', '5')
    from_date, to_date = monthToDate(month)

    try:
        point = json.loads(point)

        if request.user and point and data in [
                'waveheight', 'wavedirection', 'waveperiod', 'bathymetry',
                'tide', 'current', 'currentdirection'
        ]:
            intersection_zones = [
                z.zid for z in zone.objects(polygon__geo_intersects=point,
                                            ztype__in=['zone', 'project'
                                                       ]).exclude('triangles')
            ]
            subscribed_zones = request.user.subscription_zones + request.user.projects

            if intersection_zones and not list(
                    set(intersection_zones) -
                    set(subscribed_zones)):  # subscribed zone check
                if data in [
                        'waveheight', 'wavedirection', 'waveperiod', 'tide',
                        'current', 'currentdirection'
                ]:
                    datapoints = []
                    model = wave
                    if data == 'wavedirection':
                        model = wavedirection
                    elif data == 'waveperiod':
                        model = waveperiod
                    elif data == 'tide':
                        model = tide
                    elif data == 'current':
                        model = current
                    elif data == 'currentdirection':
                        model = currentdirection

                    p = model.objects(loc__near=point).first()
                    if p:
                        values = p.values
                        while from_date <= to_date:
                            day = str(from_date.timetuple().tm_yday)
                            try:
                                for h in sorted([
                                        int(i)
                                        for i in values.get(day, {}).keys()
                                ]):
                                    if data == 'current' or data == 'currentdirection':
                                        h = int(h)
                                        hour = str(h / 60)
                                        mins = str(h % 60)
                                        v = values[day][str(h)]
                                        if not isnan(v) and not v == -99:
                                            datapoints.append({
                                                'd':
                                                from_date.strftime('%Y-%m-%d')
                                                + '-' + hour + '-' + mins,
                                                'v':
                                                v
                                            })
                                    elif data == 'tide':
                                        h = int(h)
                                        hour = str(h / 60)
                                        mins = str(h % 60)
                                        v = values[day][str(h)]
                                        if not isnan(v) and not v == -99:
                                            datapoints.append({
                                                'd':
                                                from_date.strftime('%Y-%m-%d')
                                                + '-' + hour + '-' + mins,
                                                'v':
                                                v
                                            })
                                    else:
                                        h = str(h)
                                        datapoints.append({
                                            'd':
                                            from_date.strftime('%Y-%m-%d') +
                                            '-' + h + '-0',
                                            'v':
                                            values[day][h]
                                        })
                            except:
                                pass
                            from_date += timedelta(days=1)
                        res['lat'] = p.loc['coordinates'][1]
                        res['lng'] = p.loc['coordinates'][0]
                    res['status'] = True
                    res['msg'] = 'success'
                    res['data'] = datapoints
                elif data == 'bathymetry':
                    data = []
                    p = bathymetry.objects(loc__near=point).first()
                    if p:
                        try:
                            data = p.depth
                        except:
                            pass
                        res['lat'] = p.loc['coordinates'][1]
                        res['lng'] = p.loc['coordinates'][0]
                    res['status'] = True
                    res['msg'] = 'success'
                    res['data'] = data
            else:
                res['status'] = False
                res['msg'] = 'Please click inside your subscribed zone.'
    except Exception, e:
        print e
        res['status'] = False
        res['msg'] = 'Someting went wrong.'
Beispiel #6
0
def uploadData(request):
    res = json.loads(DEFAULT_RESPONSE)
    if request.user:
        data = request.POST.get('data-type', None)
        f = request.FILES.get('csv-file')
        name = request.POST.get('name', None)
        date = request.POST.get('date', None)  # iso format
        if data and f and name and date:
            try:
                if data == 'bathymetry':
                    date = dateutil.parser.parse(date)
                    if userzone.objects(
                            email=request.user.email,
                            name=name).first():  # unique name check
                        res['msg'] = name + ' ' + 'already exists. Please provide a unique zone name.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    points = []
                    points_geojson = []
                    for row in csv.reader(f.read().splitlines()):
                        try:
                            # remove empty cells
                            for i, r in enumerate(row):
                                row[i] = r.strip()
                            for i in range(len(row)):
                                if '' in row:
                                    row.remove('')
                            if len(row) != 3:
                                continue

                            longitude = float(row[1])
                            latitude = float(row[0])
                            value = float(row[2])
                            point = [longitude, latitude]
                            points.append(point)
                            points_geojson.append([{
                                'type': 'Point',
                                'coordinates': point
                            }, value])
                        except Exception, e:
                            res['msg'] = 'There is problem with your data. Please correct it and try again.'
                            res['status'] = False
                            return HttpResponse(
                                json.dumps(res, default=default))

                    chull = []
                    try:  # chull check
                        hull = ConvexHull(points)
                        for i in hull.vertices:
                            chull.append(points[i])
                        chull = chull + [chull[0]]
                        if not chull:
                            res['msg'] = 'Your data does not have a polygon boundary. Please correct it and try again.'
                            res['status'] = False
                            return HttpResponse(
                                json.dumps(res, default=default))
                    except Exception, e:
                        res['msg'] = 'Your data does not have a polygon boundary. Please correct it and try again.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    # subscribed zone check
                    intersection_zones = [
                        z.zid for z in
                        zone.objects(polygon__geo_intersects=[chull],
                                     ztype='zone').exclude('triangles')
                    ]
                    subscribed_zones = request.user.subscription_zones
                    if not intersection_zones or list(
                            set(intersection_zones) - set(subscribed_zones)):
                        res['msg'] = 'Some of your data is outside your subscribed zone. Please correct it and try again.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    # add to database
                    uz = userzone(uzid=str(uuid.uuid4()))
                    uz.email = request.user.email
                    uz.name = name
                    uz.ztype = 'bathymetry'
                    uz.polygon = {'type': 'Polygon', 'coordinates': [chull]}
                    uz.date = date
                    uz.save()

                    data = []
                    for p in points_geojson:
                        data.append(
                            userbathymetry(loc=p[0],
                                           depth=p[1],
                                           email=request.user.email,
                                           uzid=uz.uzid))
                    if data:
                        userbathymetry.objects.insert(data)

                    res['msg'] = 'Data uploaded successfully.'
                    res['status'] = True
                    return HttpResponse(json.dumps(res, default=default))

                elif data == 'shoreline':
                    date = dateutil.parser.parse(from_date)
                    if usershoreline.objects(
                            email=request.user.email,
                            name=name).first():  # unique name check
                        res['msg'] = name + ' ' + 'already exists. Please provide a unique shoreline name. eg: marina_beach_12/10/2017.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    points = []
                    for row in csv.reader(f.read().splitlines()):
                        try:
                            # remove empty cells
                            for i, r in enumerate(row):
                                row[i] = r.strip()
                            for i in range(len(row)):
                                if '' in row:
                                    row.remove('')
                            if len(row) != 2:
                                continue

                            longitude = float(row[1])
                            latitude = float(row[0])
                            point = (longitude, latitude)
                            points.append(point)
                        except Exception, e:
                            res['msg'] = 'There is problem with your data. Please correct it and try again.'
                            res['status'] = False
                            return HttpResponse(
                                json.dumps(res, default=default))

                    # validate linestring
                    try:
                        line = geojson.LineString(points)
                        if not line.is_valid:
                            res['msg'] = 'Your data does not form a line string. Please correct it and try again.'
                            res['status'] = False
                            return HttpResponse(
                                json.dumps(res, default=default))
                    except Exception, e:
                        res['msg'] = 'Your data does not form a line string. Please correct it and try again.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    # subscribed zone check
                    intersection_zones = [
                        z.zid for z in zone.objects(
                            polygon__geo_intersects=json.loads(
                                geojson.dumps(line)),
                            ztype='zone').exclude('triangles')
                    ]
                    subscribed_zones = request.user.subscription_zones
                    if not intersection_zones or list(
                            set(intersection_zones) - set(subscribed_zones)):
                        res['msg'] = 'Some of your data is outside your subscribed zone. Please correct it and try again.'
                        res['status'] = False
                        return HttpResponse(json.dumps(res, default=default))

                    # add to database
                    usl = usershoreline(lid=str(uuid.uuid4()))
                    usl.email = request.user.email
                    usl.name = name
                    usl.line = json.loads(geojson.dumps(line))
                    usl.date = date
                    usl.save()

                    res['msg'] = 'Data uploaded successfully.'
                    res['status'] = True
                    return HttpResponse(json.dumps(res, default=default))