Пример #1
0
def root(request):
    scan_date = UpdateDate.get_latest(Asset)
    if scan_date == '<no data>':
        return render_to_response('ecm/assets/assets_no_data.html',
                                  Ctx(request))

    my_corp = Corporation.objects.mine()
    all_hangars = Hangar.objects.all().order_by('hangarID')
    for hangar in all_hangars:
        hangar.name = hangar.get_name(my_corp)

    try:
        divisions_str = request.GET['divisions']
        divisions = [int(div) for div in divisions_str.split(',')]
        for h in all_hangars:
            h.checked = h.hangar_id in divisions
    except:
        divisions, divisions_str = None, None
        for h in all_hangars:
            h.checked = True

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    data = {
        'show_in_space': show_in_space,
        'show_in_stations': show_in_stations,
        'divisions_str': divisions_str,
        'hangars': all_hangars,
        'scan_date': scan_date
    }

    return render_to_response('ecm/assets/assets.html', data, Ctx(request))
Пример #2
0
def get_dates(request):

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    divisions = extract_divisions(request)

    since_weeks = int(request.GET.get('since_weeks', '8'))
    to_weeks = int(request.GET.get('to_weeks', '0'))

    oldest_date = timezone.now() - timedelta(weeks=since_weeks)
    newest_date = timezone.now() - timedelta(weeks=to_weeks)

    query = AssetDiff.objects.all()
    query = query.filter(date__gte=oldest_date)
    query = query.filter(date__lte=newest_date)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)
    if divisions is not None:
        query = query.filter(hangarID__in=divisions)

    dates = []
    for date in query.values_list('date',
                                  flat=True).distinct().order_by('-date'):
        dates.append({
            'value': datetime.strftime(date, DATE_PATTERN),
            'show': print_time_min(date),
        })

    return HttpResponse(json.dumps(dates))
Пример #3
0
def search_items(request, date_str):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    search_string = request.GET.get('search_string', None)

    query = AssetDiff.objects.filter(eve_type__typeName__icontains=search_string)
    query = query.filter(date__range=(date, next_date))

    if divisions is not None:
        query = query.filter(hangarID__in=divisions)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)


    json_data = []

    for item in query:
        nodeid = '#%d_' % item.solarSystemID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.stationID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.hangarID
        json_data.append(nodeid)

    return HttpResponse(json.dumps(json_data))
Пример #4
0
def root(request):
    scan_date = UpdateDate.get_latest(Asset)
    if scan_date == '<no data>':
        return render_to_response('ecm/assets/assets_no_data.html', Ctx(request))

    my_corp = Corporation.objects.mine()
    all_hangars = Hangar.objects.all().order_by('hangarID')
    for hangar in all_hangars:
        hangar.name = hangar.get_name(my_corp)

    try:
        divisions_str = request.GET['divisions']
        divisions = [ int(div) for div in divisions_str.split(',') ]
        for h in all_hangars:
            h.checked = h.hangar_id in divisions
    except:
        divisions, divisions_str = None, None
        for h in all_hangars:
            h.checked = True

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    data = { 'show_in_space' : show_in_space,
          'show_in_stations' : show_in_stations,
             'divisions_str' : divisions_str,
                   'hangars' : all_hangars,
                 'scan_date' : scan_date }

    return render_to_response('ecm/assets/assets.html', data, Ctx(request))
Пример #5
0
def get_systems_data(request, date_str):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        s = ('%s,' * len(divisions))[:-1]
        where.append('"hangarID" IN (%s)' % s)
    # TODO: fix this sql into an object
    sql = 'SELECT "solarSystemID", COUNT(*) AS "items", SUM("volume") AS "volume" '
    sql += 'FROM "assets_assetdiff" '
    sql += 'WHERE date >= %s AND date < %s '
    if where: sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "solarSystemID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor()  #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [date, next_date])
    else:
        cursor.execute(sql, [date, next_date] + list(divisions))

    jstree_data = []
    for solarSystemID, items, volume in cursor:
        try:
            system = CelestialObject.objects.get(itemID=solarSystemID)
        except CelestialObject.DoesNotExist:
            system = CelestialObject(itemID=solarSystemID,
                                     itemName=str(solarSystemID),
                                     security=0)
        if system.security > 0.5:
            color = 'hisec'
        elif system.security > 0:
            color = 'lowsec'
        else:
            color = 'nullsec'
        jstree_data.append({
            'data':
            HTML_ITEM_SPAN %
            (system.itemName, items, pluralize(items), volume),
            'attr': {
                'id': '%d_' % solarSystemID,
                'rel': 'system',
                'sort_key': system.itemName.lower(),
                'class': 'system-%s-row' % color
            },
            'state':
            'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #6
0
def search_items(request, date_str):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    search_string = request.GET.get('search_string', None)

    query = AssetDiff.objects.filter(
        eve_type__typeName__icontains=search_string)
    query = query.filter(date__range=(date, next_date))

    if divisions is not None:
        query = query.filter(hangarID__in=divisions)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)

    json_data = []

    for item in query:
        nodeid = '#%d_' % item.solarSystemID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.stationID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.hangarID
        json_data.append(nodeid)

    return HttpResponse(json.dumps(json_data))
Пример #7
0
def get_dates(request):

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    divisions = extract_divisions(request)

    since_weeks = int(request.GET.get('since_weeks', '8'))
    to_weeks = int(request.GET.get('to_weeks', '0'))

    oldest_date = timezone.now() - timedelta(weeks=since_weeks)
    newest_date = timezone.now() - timedelta(weeks=to_weeks)

    query = AssetDiff.objects.all()
    query = query.filter(date__gte=oldest_date)
    query = query.filter(date__lte=newest_date)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)
    if divisions is not None:
        query = query.filter(hangarID__in=divisions)

    dates = []
    for date in query.values_list('date', flat=True).distinct().order_by('-date'):
        dates.append({
            'value' : datetime.strftime(date, DATE_PATTERN),
            'show' : print_time_min(date),
        })

    return HttpResponse(json.dumps(dates))
Пример #8
0
def root(request, date_str):

    my_corp = Corporation.objects.mine()
    all_hangars = Hangar.objects.all().order_by('hangarID')
    for hangar in all_hangars:
        hangar.name = hangar.get_name(my_corp)

    try:
        divisions_str = request.GET['divisions']
        divisions = [ int(div) for div in divisions_str.split(',') ]
        for h in all_hangars:
            h.checked = h.hangar_id in divisions
    except:
        divisions, divisions_str = None, None
        for h in all_hangars:
            h.checked = True

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    since_weeks = int(request.GET.get('since_weeks', '8'))
    to_weeks = int(request.GET.get('to_weeks', '0'))

    oldest_date = timezone.now() - timedelta(weeks=since_weeks)
    newest_date = timezone.now() - timedelta(weeks=to_weeks)

    query = AssetDiff.objects.values_list('date', flat=True).distinct().order_by('-date')
    query = query.filter(date__gte=oldest_date)
    query = query.filter(date__lte=newest_date)

    dates = []
    for date in query:
        dates.append({
            'value' : datetime.strftime(date, DATE_PATTERN),
            'show' : date
        })

    data = { 'show_in_space' : show_in_space,
          'show_in_stations' : show_in_stations,
             'divisions_str' : divisions_str,
                   'hangars' : all_hangars,
                 'scan_date' : UpdateDate.get_latest(Asset),
               'since_weeks' : since_weeks,
                  'to_weeks' : to_weeks,
                  'date_str' : date_str,
                     'dates' : dates }

    try:
        date_asked = datetime.strptime(date_str, DATE_PATTERN)
        date_asked = timezone.make_aware(date_asked, timezone.utc)
        next_date = date_asked + timedelta(seconds=1)
    except ValueError:
        return redirect('/assets/changes/')

    if AssetDiff.objects.filter(date__range=(date_asked, next_date)).exists():
        data['date'] = date_asked
        return render_to_response('ecm/assets/assets_diff.html', data, Ctx(request))
    else:
        return render_to_response('ecm/assets/assets_no_data.html', {}, Ctx(request))
Пример #9
0
def get_stations_data(request, date_str, solarSystemID):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)
    solarSystemID = int(solarSystemID)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        s = ('%s,' * len(divisions))[:-1]
        where.append('"hangarID" IN (%s)' % s)

    sql = 'SELECT "stationID", MAX("flag") as "flag", COUNT(*) AS "items", SUM("volume") AS "volume" '
    sql += 'FROM "assets_assetdiff" '
    sql += 'WHERE "solarSystemID"=%s AND "date" >= %s AND "date" < %s '
    if where: sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "stationID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor()  #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [solarSystemID, date, next_date])
    else:
        cursor.execute(sql, [solarSystemID, date, next_date] + list(divisions))

    jstree_data = []
    for stationID, flag, items, volume in cursor:
        if stationID < constants.MAX_STATION_ID:
            # it's a real station
            try:
                name = CelestialObject.objects.get(itemID=stationID).itemName
            except CelestialObject.DoesNotExist:
                name = str(stationID)
            icon = 'station'
        else:
            # it is an inspace anchorable array
            name = Type.objects.get(typeID=flag).typeName
            icon = 'array'

        jstree_data.append({
            'data':
            HTML_ITEM_SPAN % (name, items, pluralize(items), volume),
            'attr': {
                'id': '%d_%d_' % (solarSystemID, stationID),
                'sort_key': stationID,
                'rel': icon,
                'class': '%s-row' % icon
            },
            'state':
            'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #10
0
def get_systems_data(request):

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        where.append('"hangarID" IN (%s)' % ', '.join(['%s'] * len(divisions)))

    sql = 'SELECT "solarSystemID", COUNT(*) AS "items", SUM("volume") AS "volume" '\
          'FROM "assets_asset" '
    if where: sql += ' WHERE ' + ' AND '.join(where)
    sql += ' GROUP BY "solarSystemID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor() #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql)
    else:
        cursor.execute(sql, divisions)

    exact_volumes = Setting.get('assets_show_exact_volumes')

    jstree_data = []
    for solarSystemID, items, volume in cursor:
        try:
            system = CelestialObject.objects.get(itemID=solarSystemID)
        except CelestialObject.DoesNotExist:
            system = CelestialObject(itemID=solarSystemID, itemName=str(solarSystemID), security=0)
        if system.security > 0.5:
            color = 'hisec'
        elif system.security > 0:
            color = 'lowsec'
        else:
            color = 'nullsec'

        if exact_volumes:
            volume = print_float(volume)
        else:
            volume = round_quantity(volume)

        jstree_data.append({
            'data' : HTML_ITEM_SPAN % (system.itemName, items, pluralize(items), volume),
            'attr' : {
                'id' : '%d_' % solarSystemID,
                'rel' : 'system',
                'sort_key' : system.itemName.lower(),
                'class' : 'system-%s-row' % color
            },
            'state' : 'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #11
0
def get_celestial_objects_data(request, solarSystemID):
    solarSystemID = int(solarSystemID)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        where.append('"hangarID" IN (%s)' % ', '.join(['%s'] * len(divisions)))

    sql = 'SELECT "closest_object_id", COUNT(*), SUM("volume") '\
          'FROM "assets_asset" '\
          'WHERE "solarSystemID"=%s '
    if where:
        sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "closest_object_id";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor() #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [solarSystemID])
    else:
        cursor.execute(sql, [solarSystemID] + list(divisions))

    exact_volumes = Setting.get('assets_show_exact_volumes')

    jstree_data = []
    for closest_object_id, items, volume in cursor:

        if closest_object_id != 0:
            try:
                name = CelestialObject.objects.get(itemID=closest_object_id).itemName
            except CelestialObject.DoesNotExist:
                name = str(closest_object_id)
        else:
            name = 'Stations'

        if exact_volumes:
            volume = print_float(volume)
        else:
            volume = round_quantity(volume)

        jstree_data.append({
            'data' : HTML_ITEM_SPAN % (name, items, pluralize(items), volume),
            'attr' : {
                'id' : '%d_%d_' % (solarSystemID, closest_object_id),
                'sort_key' : closest_object_id,
                'rel' : 'celestial',
                'class' : 'celestial-row',
            },
            'state' : 'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #12
0
def get_stations_data(request, date_str, solarSystemID):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)
    solarSystemID = int(solarSystemID)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        s = ('%s,' * len(divisions))[:-1]
        where.append('"hangarID" IN (%s)' % s)

    sql = 'SELECT "stationID", MAX("flag") as "flag", COUNT(*) AS "items", SUM("volume") AS "volume" '
    sql += 'FROM "assets_assetdiff" '
    sql += 'WHERE "solarSystemID"=%s AND "date" >= %s AND "date" < %s '
    if where: sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "stationID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor() #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [solarSystemID, date, next_date])
    else:
        cursor.execute(sql, [solarSystemID, date, next_date] + list(divisions))

    jstree_data = []
    for stationID, flag, items, volume in cursor:
        if stationID < constants.MAX_STATION_ID:
            # it's a real station
            try:
                name = CelestialObject.objects.get(itemID=stationID).itemName
            except CelestialObject.DoesNotExist:
                name = str(stationID)
            icon = 'station'
        else:
            # it is an inspace anchorable array
            name = Type.objects.get(typeID=flag).typeName
            icon = 'array'

        jstree_data.append({
            'data' : HTML_ITEM_SPAN % (name, items, pluralize(items), volume),
            'attr' : {
                'id' : '%d_%d_' % (solarSystemID, stationID),
                'sort_key' : stationID,
                'rel' : icon,
                'class' : '%s-row' % icon
            },
            'state' : 'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #13
0
def get_systems_data(request, date_str):
    date = datetime.strptime(date_str, DATE_PATTERN)
    date = timezone.make_aware(date, timezone.utc)
    next_date = date + timedelta(seconds=1)

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        s = ('%s,' * len(divisions))[:-1]
        where.append('"hangarID" IN (%s)' % s)
    # TODO: fix this sql into an object
    sql = 'SELECT "solarSystemID", COUNT(*) AS "items", SUM("volume") AS "volume" '
    sql += 'FROM "assets_assetdiff" '
    sql += 'WHERE date >= %s AND date < %s '
    if where: sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "solarSystemID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor() #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [date, next_date])
    else:
        cursor.execute(sql, [date, next_date] + list(divisions))

    jstree_data = []
    for solarSystemID, items, volume in cursor:
        try:
            system = CelestialObject.objects.get(itemID=solarSystemID)
        except CelestialObject.DoesNotExist:
            system = CelestialObject(itemID=solarSystemID, itemName=str(solarSystemID), security=0)
        if system.security > 0.5:
            color = 'hisec'
        elif system.security > 0:
            color = 'lowsec'
        else:
            color = 'nullsec'
        jstree_data.append({
            'data' : HTML_ITEM_SPAN % (system.itemName, items, pluralize(items), volume),
            'attr' : {
                'id' : '%d_' % solarSystemID,
                'rel' : 'system',
                'sort_key' : system.itemName.lower(),
                'class' : 'system-%s-row' % color
            },
            'state' : 'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #14
0
def update_one_corp(corp):

    my_corp = Corporation.objects.mine()

    auth_url = urlparse.urljoin(corp.ecm_url, '/corp/auth/startsession/')
    client = HttpClient()

    LOG.debug('Establishing secure data exchange with %r...' % corp.ecm_url)
    response = client.get(
        auth_url,
        headers={'Authorization': 'RSA %s' % my_corp.key_fingerprint})
    cipher_txt_in = response.read()

    # we decrypt the response with our private key
    session_secret = crypto.rsa_decrypt(my_corp.private_key, cipher_txt_in)
    # and encrypt it back with the corp's public key
    cipher_txt_out = crypto.rsa_encrypt(corp.public_key, session_secret)

    # then send it to the server
    client.post(auth_url, cipher_txt_out)

    LOG.debug('Fetching which data %r is sharing with us...' % corp)
    # now we fetch the urls we're allowed to pull from this corporation
    response = client.get(
        urlparse.urljoin(corp.ecm_url, '/corp/share/allowed/'))
    data = crypto.aes_decrypt(session_secret, response.read())
    allowed_urls = json.loads(data)

    if not allowed_urls:
        LOG.warning('%r is not sharing any data with us' %
                    corp.corporationName)
    for url in allowed_urls:
        try:
            shared_data = SharedData.objects.get(url=url)

            LOG.debug('Fetching shared data %r...' % url)
            response = client.get(
                urlparse.urljoin(corp.ecm_url, shared_data.url))

            raw_data = crypto.aes_decrypt(session_secret, response.read())

            if response.info().getheader(
                    'content-type') == 'application/gzip-compressed':
                raw_data = zlib.decompress(raw_data)

            shared_data.call_handler(corp, json.loads(raw_data))
        except SharedData.DoesNotExist:
            LOG.error('Unknown SharedData with url=%r' % url)
        except:
            LOG.exception('')

    LOG.debug('Ending secure session with %r...' % corp.ecm_url)
    # finally destroy our session info to be sure nobody will steal it :)
    client.get(urlparse.urljoin(corp.ecm_url, '/corp/auth/endsession/'))
Пример #15
0
def update_one_corp(corp):
    
    my_corp = Corporation.objects.mine()
    
    auth_url = urlparse.urljoin(corp.ecm_url, '/corp/auth/startsession/')
    client = HttpClient()
    
    LOG.debug('Establishing secure data exchange with %r...' % corp.ecm_url)
    response = client.get(auth_url, headers={'Authorization': 'RSA %s' % my_corp.key_fingerprint})
    cipher_txt_in = response.read()
    
    # we decrypt the response with our private key
    session_secret = crypto.rsa_decrypt(my_corp.private_key, cipher_txt_in)
    # and encrypt it back with the corp's public key
    cipher_txt_out = crypto.rsa_encrypt(corp.public_key, session_secret)
    
    # then send it to the server
    client.post(auth_url, cipher_txt_out)

    LOG.debug('Fetching which data %r is sharing with us...' % corp)
    # now we fetch the urls we're allowed to pull from this corporation
    response = client.get(urlparse.urljoin(corp.ecm_url, '/corp/share/allowed/'))
    data = crypto.aes_decrypt(session_secret, response.read())
    allowed_urls = json.loads(data)

    if not allowed_urls:
        LOG.warning('%r is not sharing any data with us' % corp.corporationName)
    for url in allowed_urls:
        try:
            shared_data = SharedData.objects.get(url=url)
            
            LOG.debug('Fetching shared data %r...' % url)
            response = client.get(urlparse.urljoin(corp.ecm_url, shared_data.url))
            
            raw_data = crypto.aes_decrypt(session_secret, response.read())
            
            if response.info().getheader('content-type') == 'application/gzip-compressed':
                raw_data = zlib.decompress(raw_data)
            
            shared_data.call_handler(corp, json.loads(raw_data))
        except SharedData.DoesNotExist:
            LOG.error('Unknown SharedData with url=%r' % url)
        except:
            LOG.exception('')
    
    LOG.debug('Ending secure session with %r...' % corp.ecm_url)
    # finally destroy our session info to be sure nobody will steal it :)
    client.get(urlparse.urljoin(corp.ecm_url, '/corp/auth/endsession/'))
Пример #16
0
def skilled_list(request):
    try:
        params = extract_datatable_params(request)
        corp_id = request.GET.get('corp')
        skills = json.loads(request.GET.get("skills", ""))
    except KeyError:
        return HttpResponseBadRequest()

    if corp_id:
        try:
            members = Corporation.objects.get(
                corporationID=int(corp_id)).members.all()
        except Corporation.DoesNotExist:
            members = Corporation.objects.mine().members.all()
        except ValueError:
            # corp_id cannot be casted to int, we take all corps
            members = Member.objects.exclude(corp=None)
    else:
        members = Corporation.objects.mine().members.all()

    query = members
    for skill in skills:
        query &= members.filter(skills__eve_type_id=skill['id'],
                                skills__level__gte=skill['lvl'])

    total_members,\
    filtered_members,\
    members = get_members(query=query.distinct(),
                          first_id=params.first_id,
                          last_id=params.last_id,
                          sort_by=params.column,
                          asc=params.asc)

    return datatable_ajax_data(members, params.sEcho, total_members,
                               filtered_members)
Пример #17
0
def skilled_list(request):
    try:
        params = extract_datatable_params(request)
        corp_id = request.GET.get('corp')
        skills = json.loads(request.GET.get("skills", ""))
    except KeyError:
        return HttpResponseBadRequest()

    if corp_id:
        try:
            members = Corporation.objects.get(corporationID=int(corp_id)).members.all()
        except Corporation.DoesNotExist:
            members = Corporation.objects.mine().members.all()
        except ValueError:
            # corp_id cannot be casted to int, we take all corps
            members = Member.objects.exclude(corp=None)
    else:
        members = Corporation.objects.mine().members.all()

    query = members
    for skill in skills:
        query &= members.filter(skills__eve_type_id=skill['id'], 
                                skills__level__gte=skill['lvl'])
    
    total_members,\
    filtered_members,\
    members = get_members(query=query.distinct(),
                          first_id=params.first_id,
                          last_id=params.last_id,
                          sort_by=params.column,
                          asc=params.asc)
    
    return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
Пример #18
0
def availability(request, item_id):
    """
    Serves URL /industry/catalog/items/<item_id>/availability/

    If request is POST:
        update the availability of the item
    return the json formatted availability
    """
    try:
        item = get_object_or_404(CatalogEntry, typeID=int(item_id))
    except ValueError:
        raise Http404()
    if request.method == 'POST':
        try:
            available = json.loads(request.POST['available'])
            if type(available) != type(True):
                return HttpResponseBadRequest('"available" parameter must be a boolean')
        except (KeyError, ValueError):
            return HttpResponseBadRequest('Missing "available" parameter')
        item.is_available = available
        item.save()
        logger.info('"%s" changed availability for item "%s" -> %s' % (request.user,
                                                                       item.typeName,
                                                                       available))
    return HttpResponse(json.dumps(item.is_available), mimetype=JSON)
Пример #19
0
def info(request, attr):
    """
    Serves URL /industry/catalog/blueprints/<attr>/

    must have "id" and "value" parameters in the request
    if request is POST:
        update bp.attr with value
    return the bp.attr as JSON
    """
    try:
        blueprint_id = getattr(request, request.method)['id']
        bp = get_object_or_404(OwnedBlueprint, id=int(blueprint_id))
        if not hasattr(bp, attr):
            # unknown attribute
            raise Http404()
    except KeyError:
        return HttpResponseBadRequest('Missing "id" parameter')
    except ValueError:
        raise Http404()

    if request.method == 'POST':
        try:
            value = json.loads(request.POST['value'])
            if type(value) == type(getattr(bp, attr)):
                setattr(bp, attr, value)
                bp.save()
                logger.info('"%s" changed "%s" #%d (%s -> %s)' % (request.user, bp.typeName,
                                                                  bp.id, attr, value))
        except KeyError:
            return HttpResponseBadRequest('Missing "value" parameter')
        except ValueError:
            return HttpResponseBadRequest('Cannot parse "value" parameter')

    return HttpResponse(json.dumps(getattr(bp, attr)))
Пример #20
0
def availability(request, item_id):
    """
    Serves URL /industry/catalog/items/<item_id>/availability/

    If request is POST:
        update the availability of the item
    return the json formatted availability
    """
    try:
        item = get_object_or_404(CatalogEntry, typeID=int(item_id))
    except ValueError:
        raise Http404()
    if request.method == 'POST':
        try:
            available = json.loads(request.POST['available'])
            if type(available) != type(True):
                return HttpResponseBadRequest(
                    '"available" parameter must be a boolean')
        except (KeyError, ValueError):
            return HttpResponseBadRequest('Missing "available" parameter')
        item.is_available = available
        item.save()
        logger.info('"%s" changed availability for item "%s" -> %s' %
                    (request.user, item.typeName, available))
    return HttpResponse(json.dumps(item.is_available), mimetype=JSON)
Пример #21
0
def post_feedback(request):
    fb = json.loads(request.body)
    key = fb.get('key_fingerprint')
    now = timezone.now()

    try:
        db_feedback = ECMInstanceFeedback.objects.get(key_fingerprint=key)
        if db_feedback.last_updated > now - timedelta(days=1):
            return HttpResponse(ecm.VERSION)
    except ECMInstanceFeedback.DoesNotExist:
        db_feedback = ECMInstanceFeedback(key_fingerprint=key)

    db_feedback.active_user_count = fb.get('active_user_count') or 0
    db_feedback.avg_last_visit_top10 = fb.get('avg_last_visit_top10') or 0
    db_feedback.avg_last_visit = fb.get('avg_last_visit') or 0
    db_feedback.country_code = fb.get('country_code')
    db_feedback.country_name = fb.get('country_name')
    db_feedback.city = fb.get('city')
    db_feedback.first_installed = fb.get('first_installed') or now
    db_feedback.version = fb.get('ecm_version')

    db_feedback.feedback_count += 1
    db_feedback.save()

    # remove outdated usage feedbacks (more than 2 weeks)
    two_weeks_ago = now - timedelta(days=14)
    ECMInstanceFeedback.objects.filter(last_updated__lt=two_weeks_ago).delete()

    return HttpResponse(ecm.VERSION)
Пример #22
0
def fetch_ecm_data():
    logger.debug('Fetching info from ECM...')
    base64string = base64.encodestring('%s:%s' % (ECM_USER, ECM_PASSWD)).replace('\n', '')

    request = urllib2.Request(ECM_URL + ECM_GROUPS)
    request.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(request)
    groups = json.loads(response.read())
    response.close()

    request = urllib2.Request(ECM_URL + ECM_USERS)
    request.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(request)
    users = json.loads(response.read())
    response.close()
    logger.info('Fetched %d groups and %d users from ECM' % (len(groups), len(users)))
    return groups, users
Пример #23
0
def send_feedback():
    """
    This function will collect basic non-critical data about the current server
    instance and send it to eve-corp-management.org official server for usage
    statistics feedback.
    """
    LOG.debug("Sending usage feedback to %r...", ECM_USAGE_FEEDBACK_URL)

    mycorp = Corporation.objects.mine()

    # fetch geolocalization info
    http_client = HttpClient()
    resp = http_client.get(url="http://freegeoip.net/json/")
    geoloc_info = json.loads(resp.read())
    resp.close()

    # we only consider users that are corp members
    users = get_members_group().user_set.order_by("-last_login")

    usage_data = {
        "key_fingerprint": mycorp.key_fingerprint,
        "active_user_count": users.count(),
        "avg_last_visit_top10": avg_last_login(users[:10]),
        "avg_last_visit": avg_last_login(users),
        "first_installed": find_oldest_entry(),
        "country_code": geoloc_info.get("country_code"),
        "country_name": geoloc_info.get("country_name"),
        "city": geoloc_info.get("city"),
        "ecm_version": ecm.VERSION,
    }

    # send the data to the server
    resp = http_client.post(ECM_USAGE_FEEDBACK_URL, json.dumps(usage_data))
    LOG.info("Usage feedback sent to %r. Thank you for your contribution.", ECM_USAGE_FEEDBACK_URL)

    new_version = resp.read().strip()
    old_version = ecm.VERSION

    if parse_version(new_version) > parse_version(old_version):
        LOG.info("New version of ecm is available: %r.", new_version)

        ctx_dict = {
            "host_name": settings.EXTERNAL_HOST_NAME,
            "use_https": settings.USE_HTTPS,
            "new_version": new_version,
            "old_version": old_version,
        }

        dummy_request = HttpRequest()
        dummy_request.user = AnonymousUser()

        subject = tr_lazy("ECM version %s is available" % new_version)
        msg = render_to_string("ecm/common/email/new_version.txt", ctx_dict, Ctx(dummy_request))
        html = render_to_string("ecm/common/email/new_version.html", ctx_dict, Ctx(dummy_request))

        mail_admins(subject=subject, message=msg, html_message=html)
Пример #24
0
def fetch_ecm_data():
    logger.debug('Fetching info from ECM...')
    base64string = base64.encodestring(
        '%s:%s' % (ECM_USER, ECM_PASSWD)).replace('\n', '')

    request = urllib2.Request(ECM_URL + ECM_GROUPS)
    request.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(request)
    groups = json.loads(response.read())
    response.close()

    request = urllib2.Request(ECM_URL + ECM_USERS)
    request.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(request)
    users = json.loads(response.read())
    response.close()
    logger.info('Fetched %d groups and %d users from ECM' %
                (len(groups), len(users)))
    return groups, users
Пример #25
0
def search_items(request):

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    search_string = request.GET.get('search_string', None)

    filter_args = Q(name__icontains=search_string)
    if search_string:
        filter_args |= Q(eve_type__typeName__icontains=search_string)

    query = Asset.objects.filter(filter_args)

    if divisions is not None:
        query = query.filter(hangarID__in=divisions)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)

    json_data = []

    for item in query:
        nodeid = '#%d_' % item.solarSystemID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.closest_object_id
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.stationID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.hangarID
        json_data.append(nodeid)
        if item.container1:
            nodeid = nodeid + '%d_' % item.container1
            json_data.append(nodeid)
            if item.container2:
                nodeid = nodeid + '%d_' % item.container2
                json_data.append(nodeid)

    return HttpResponse(json.dumps(json_data))
Пример #26
0
def search_items(request):

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))
    search_string = request.GET.get('search_string', None)

    filter_args = Q(name__icontains=search_string)
    if search_string:
        filter_args |= Q(eve_type__typeName__icontains=search_string)

    query = Asset.objects.filter(filter_args)

    if divisions is not None:
        query = query.filter(hangarID__in=divisions)
    if not show_in_space:
        query = query.filter(stationID__lt=constants.MAX_STATION_ID)
    if not show_in_stations:
        query = query.filter(stationID__gt=constants.MAX_STATION_ID)

    json_data = []

    for item in query:
        nodeid = '#%d_' % item.solarSystemID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.closest_object_id
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.stationID
        json_data.append(nodeid)
        nodeid = nodeid + '%d_' % item.hangarID
        json_data.append(nodeid)
        if item.container1:
            nodeid = nodeid + '%d_' % item.container1
            json_data.append(nodeid)
            if item.container2:
                nodeid = nodeid + '%d_' % item.container2
                json_data.append(nodeid)

    return HttpResponse(json.dumps(json_data))
Пример #27
0
def is_cyno_alt(request, characterID):
    """
    Serves /hr/members/<characterID>/is_cyno_alt/
    """
    member = get_object_or_404(Member, characterID=int(characterID))
    if not (request.user.is_superuser or request.user == member.owner
            or UrlPermission.user_has_access(request.user,
                                             request.get_full_path())):
        return HttpResponseForbidden(request)
    if request.method == 'POST':
        try:
            is_cyno_alt = bool(json.loads(request.POST.get('is_cyno_alt')))
        except (ValueError, TypeError), e:
            return HttpResponseBadRequest(str(e))
        member.is_cyno_alt = is_cyno_alt
        member.save()
        logger.info('"%s" Changed cyno alt status of "%s" -> %s' %
                    (request.user, member, is_cyno_alt))
Пример #28
0
def is_cyno_alt(request, characterID):
    """
    Serves /hr/members/<characterID>/is_cyno_alt/
    """
    member = get_object_or_404(Member, characterID=int(characterID))
    if not (
        request.user.is_superuser
        or request.user == member.owner
        or UrlPermission.user_has_access(request.user, request.get_full_path())
    ):
        return HttpResponseForbidden(request)
    if request.method == "POST":
        try:
            is_cyno_alt = bool(json.loads(request.POST.get("is_cyno_alt")))
        except (ValueError, TypeError), e:
            return HttpResponseBadRequest(str(e))
        member.is_cyno_alt = is_cyno_alt
        member.save()
        logger.info('"%s" Changed cyno alt status of "%s" -> %s' % (request.user, member, is_cyno_alt))
Пример #29
0
def info(request, attr):
    """
    Serves URL /industry/catalog/supplies/<attr>/

    must have "id" and "value" parameters in the request
    if request is POST:
        update supply.attr with value
    return the supply.attr as JSON
    """
    try:
        item_id = getattr(request, request.method)['id']
        supply = get_object_or_404(Supply, typeID=int(item_id))
        displayVal = getattr(supply, attr)
    except KeyError:
        return HttpResponseBadRequest('Missing "id" parameter')
    except (ValueError, AttributeError):
        raise Http404()

    if request.method == 'POST':
        try:
            value = json.loads(request.POST['value'])
            if type(value) == type(getattr(supply, attr)):
                if attr == 'price':
                    supply.update_price(value)
                    displayVal = print_float(value)
                else:
                    setattr(supply, attr, value)
                    supply.save()
                    displayVal = value
                logger.info('"%s" changed supply "%s" (%s -> %s)' % (request.user,
                                                                     supply.typeName,
                                                                     attr, displayVal))
        except KeyError:
            return HttpResponseBadRequest('Missing "value" parameter')
        except ValueError:
            return HttpResponseBadRequest('Cannot parse "value" parameter')

    return HttpResponse(str(displayVal))
Пример #30
0
def info(request, attr):
    """
    Serves URL /industry/catalog/blueprints/<attr>/

    must have "id" and "value" parameters in the request
    if request is POST:
        update bp.attr with value
    return the bp.attr as JSON
    """
    try:
        blueprint_id = getattr(request, request.method)['id']
        bp = get_object_or_404(OwnedBlueprint, id=int(blueprint_id))
        if not hasattr(bp, attr):
            # unknown attribute
            raise Http404()
    except KeyError:
        return HttpResponseBadRequest('Missing "id" parameter')
    except ValueError:
        raise Http404()

    if request.method == 'POST':
        try:
            value = json.loads(request.POST['value'])
            if type(value) == type(getattr(bp, attr)):
                setattr(bp, attr, value)
                bp.full_clean()
                bp.save()
                logger.info('"%s" changed "%s" #%d (%s -> %s)' %
                            (request.user, bp.typeName, bp.id, attr, value))
        except KeyError:
            return HttpResponseBadRequest('Missing "value" parameter')
        except ValueError:
            return HttpResponseBadRequest('Cannot parse "value" parameter')
        except ValidationError as e:
            return HttpResponseBadRequest(str(e))

    return HttpResponse(json.dumps(getattr(bp, attr)))
Пример #31
0
def root(request, date_str):

    my_corp = Corporation.objects.mine()
    all_hangars = Hangar.objects.all().order_by('hangarID')
    for hangar in all_hangars:
        hangar.name = hangar.get_name(my_corp)

    try:
        divisions_str = request.GET['divisions']
        divisions = [int(div) for div in divisions_str.split(',')]
        for h in all_hangars:
            h.checked = h.hangar_id in divisions
    except:
        divisions, divisions_str = None, None
        for h in all_hangars:
            h.checked = True

    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    since_weeks = int(request.GET.get('since_weeks', '8'))
    to_weeks = int(request.GET.get('to_weeks', '0'))

    oldest_date = timezone.now() - timedelta(weeks=since_weeks)
    newest_date = timezone.now() - timedelta(weeks=to_weeks)

    query = AssetDiff.objects.values_list(
        'date', flat=True).distinct().order_by('-date')
    query = query.filter(date__gte=oldest_date)
    query = query.filter(date__lte=newest_date)

    dates = []
    for date in query:
        dates.append({
            'value': datetime.strftime(date, DATE_PATTERN),
            'show': date
        })

    data = {
        'show_in_space': show_in_space,
        'show_in_stations': show_in_stations,
        'divisions_str': divisions_str,
        'hangars': all_hangars,
        'scan_date': UpdateDate.get_latest(Asset),
        'since_weeks': since_weeks,
        'to_weeks': to_weeks,
        'date_str': date_str,
        'dates': dates
    }

    try:
        date_asked = datetime.strptime(date_str, DATE_PATTERN)
        date_asked = timezone.make_aware(date_asked, timezone.utc)
        next_date = date_asked + timedelta(seconds=1)
    except ValueError:
        return redirect('/assets/changes/')

    if AssetDiff.objects.filter(date__range=(date_asked, next_date)).exists():
        data['date'] = date_asked
        return render_to_response('ecm/assets/assets_diff.html', data,
                                  Ctx(request))
    else:
        return render_to_response('ecm/assets/assets_no_data.html', {},
                                  Ctx(request))
Пример #32
0
def handle_contact(request):

    if request.method == 'POST':
        public_info = Corporation.objects.mine().get_public_info()

        try:
            corp_info = json.loads(request.body)
            ecm_url = corp_info['ecm_url']
            corporationID = corp_info['corporationID']
            corporationName = corp_info['corporationName']
            ticker = corp_info['ticker']
            public_key = corp_info['public_key']
            key_fingerprint = corp_info['key_fingerprint']
            try:
                alliance = Alliance.objects.get(
                    allianceID=corp_info['alliance'])
            except Alliance.DoesNotExist:
                alliance = Alliance()
                alliance.allianceID = corp_info['alliance']
                alliancesApi = api.connect().eve.AllianceList()
                for a in alliancesApi.alliances:
                    if a.allianceID == corp_info['alliance']:
                        alliance.shortName = a.shortName
                        alliance.name = a.name
                        alliance.save()
                        break
            new_request = False
            if Corporation.objects.filter(
                    corporationID=corporationID).exists():
                corp = Corporation.objects.get(corporationID=corporationID)
                if not corp.key_fingerprint:
                    # This corp was created by some internal task but we don't know their
                    # public info yet.
                    corp.corporationName = corporationName
                    corp.ticker = ticker
                    corp.alliance = alliance
                    corp.ecm_url = ecm_url
                    corp.public_key = public_key
                    corp.key_fingerprint = key_fingerprint
                    corp.is_trusted = False
                    new_request = True
                else:
                    if corp.key_fingerprint != key_fingerprint:
                        # tentative of hack? return an error
                        LOG.error(WRONG_FINGERPRINT_MSG %
                                  (corporationName, corporationID))
                        raise ValueError('wrong key_fingerprint')
            else:
                # create the corp in our db
                corp = Corporation(
                    corporationID=corporationID,
                    corporationName=corporationName,
                    ticker=ticker,
                    alliance=alliance,
                    ecm_url=ecm_url,
                    public_key=public_key,
                    key_fingerprint=key_fingerprint,
                    is_trusted=False,
                )
                new_request = True

            if new_request:
                corp.save()
                # notify the admins that a new corp tried to contact us
                subject = ugettext(
                    '%s wants to exchange data with us') % corp.corporationName
                ctx_dict = {
                    'host_name': settings.EXTERNAL_HOST_NAME,
                    'use_https': settings.USE_HTTPS,
                    'corp': corp,
                }
                txt_content = render_to_string(
                    'ecm/corp/email/notify_contact.txt', ctx_dict,
                    Ctx(request))
                html_content = render_to_string(
                    'ecm/corp/email/notify_contact.html', ctx_dict,
                    Ctx(request))
                mail_admins(subject, txt_content, html_message=html_content)

            # if everything went well, return back our public info
            return HttpResponse(json.dumps(public_info))

        except (ValueError, KeyError), e:
            # invalid field value
            return HttpResponseBadRequest(str(e))
Пример #33
0
def get_celestial_objects_data(request, solarSystemID):
    solarSystemID = int(solarSystemID)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        where.append('"hangarID" IN (%s)' % ', '.join(['%s'] * len(divisions)))

    sql = 'SELECT "closest_object_id", COUNT(*), SUM("volume") '\
          'FROM "assets_asset" '\
          'WHERE "solarSystemID"=%s '
    if where:
        sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "closest_object_id";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor()  #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [solarSystemID])
    else:
        cursor.execute(sql, [solarSystemID] + list(divisions))

    exact_volumes = Setting.get('assets_show_exact_volumes')

    jstree_data = []
    for closest_object_id, items, volume in cursor:

        if closest_object_id != 0:
            try:
                name = CelestialObject.objects.get(
                    itemID=closest_object_id).itemName
            except CelestialObject.DoesNotExist:
                name = str(closest_object_id)
        else:
            name = 'Stations'

        if exact_volumes:
            volume = print_float(volume)
        else:
            volume = round_quantity(volume)

        jstree_data.append({
            'data':
            HTML_ITEM_SPAN % (name, items, pluralize(items), volume),
            'attr': {
                'id': '%d_%d_' % (solarSystemID, closest_object_id),
                'sort_key': closest_object_id,
                'rel': 'celestial',
                'class': 'celestial-row',
            },
            'state':
            'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #34
0
def get_systems_data(request):

    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        where.append('"hangarID" IN (%s)' % ', '.join(['%s'] * len(divisions)))

    sql = 'SELECT "solarSystemID", COUNT(*) AS "items", SUM("volume") AS "volume" '\
          'FROM "assets_asset" '
    if where: sql += ' WHERE ' + ' AND '.join(where)
    sql += ' GROUP BY "solarSystemID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor()  #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql)
    else:
        cursor.execute(sql, divisions)

    exact_volumes = Setting.get('assets_show_exact_volumes')

    jstree_data = []
    for solarSystemID, items, volume in cursor:
        try:
            system = CelestialObject.objects.get(itemID=solarSystemID)
        except CelestialObject.DoesNotExist:
            system = CelestialObject(itemID=solarSystemID,
                                     itemName=str(solarSystemID),
                                     security=0)
        if system.security > 0.5:
            color = 'hisec'
        elif system.security > 0:
            color = 'lowsec'
        else:
            color = 'nullsec'

        if exact_volumes:
            volume = print_float(volume)
        else:
            volume = round_quantity(volume)

        jstree_data.append({
            'data':
            HTML_ITEM_SPAN %
            (system.itemName, items, pluralize(items), volume),
            'attr': {
                'id': '%d_' % solarSystemID,
                'rel': 'system',
                'sort_key': system.itemName.lower(),
                'class': 'system-%s-row' % color
            },
            'state':
            'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))
Пример #35
0
def get_stations_data(request, solarSystemID, closest_obj_id):
    solarSystemID = int(solarSystemID)
    closest_obj_id = int(closest_obj_id)
    divisions = extract_divisions(request)
    show_in_space = json.loads(request.GET.get('space', 'true'))
    show_in_stations = json.loads(request.GET.get('stations', 'true'))

    where = []
    if not show_in_space:
        where.append('"stationID" < %d' % constants.MAX_STATION_ID)
    if not show_in_stations:
        where.append('"stationID" > %d' % constants.MAX_STATION_ID)
    if divisions is not None:
        where.append('"hangarID" IN (%s)' % ', '.join(['%s'] * len(divisions)))

    sql = 'SELECT "stationID", MAX("name"), MAX("flag"), COUNT(*), SUM("volume") '\
          'FROM "assets_asset" '\
          'WHERE "solarSystemID"=%s AND "closest_object_id"=%s '
    if where: sql += ' AND ' + ' AND '.join(where)
    sql += ' GROUP BY "stationID";'
    sql = db.fix_mysql_quotes(sql)

    cursor = connection.cursor()  #@UndefinedVariable
    if divisions is None:
        cursor.execute(sql, [solarSystemID, closest_obj_id])
    else:
        cursor.execute(sql, [solarSystemID, closest_obj_id] + list(divisions))

    exact_volumes = Setting.get('assets_show_exact_volumes')

    jstree_data = []
    for stationID, item_name, flag, items, volume in cursor:
        if stationID < constants.MAX_STATION_ID:
            # it's a real station
            try:
                name = CelestialObject.objects.get(itemID=stationID).itemName
            except CelestialObject.DoesNotExist:
                name = str(stationID)
            icon = 'station'
        else:
            # it is an inspace anchorable array
            type_name = Type.objects.get(typeID=flag).typeName

            name = type_name
            if item_name and type_name != item_name:
                name += ' "%s"' % item_name

            if constants.CONTROL_TOWERS.has_key(flag):
                icon = 'pos'
            else:
                icon = 'array'

        if exact_volumes:
            volume = print_float(volume)
        else:
            volume = round_quantity(volume)

        jstree_data.append({
            'data':
            HTML_ITEM_SPAN % (name, items, pluralize(items), volume),
            'attr': {
                'id': '%d_%d_%d_' % (solarSystemID, closest_obj_id, stationID),
                'sort_key': stationID,
                'rel': icon,
                'class': '%s-row' % icon
            },
            'state':
            'closed'
        })
    cursor.close()
    return HttpResponse(json.dumps(jstree_data))