Initial import of existing codebase.

This commit is contained in:
2013-11-11 20:22:27 +00:00
parent 0ff053c2b4
commit 00ab27312c
21 changed files with 736 additions and 0 deletions

1
evesde/__init__.py Normal file
View File

@@ -0,0 +1 @@
__version__ = '0.0.1'

13
evesde/app_defines.py Normal file
View File

@@ -0,0 +1,13 @@
# Distance units, in meters (EVE Units, aka heavily rounded)
DISTANCE_METER = 1
DISTANCE_KILOMETER = 1000
DISTANCE_ASTRONOMICAL_UNIT = 149598000000
DISTANCE_LIGHT_YEAR = 9460000000000000
# Important Type Groups we need to filter on
TYPEGROUP_TOWERS = [365]
TYPEGROUP_FUEL = [1136, 423]
# Important attributes types
ATTRIBUTE_MAX_STRUCTURE_DISTANCE = 650

View File

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,27 @@
from django.core.management.base import BaseCommand
from django.db import transaction
from evesde.models.locations import Station
from eveapi import EVEAPIConnection
class Command(BaseCommand):
help = 'Imports outposts from the EVE API.'
def handle(self, *args, **options):
api = EVEAPIConnection()
stations = Station.objects.all()
objs = []
for station in api.eve.ConquerableStationList().outposts:
print "Importing %s" % station.stationName
try:
obj = stations.get(pk=station.stationID)
except Station.DoesNotExist:
obj = Station(pk=station.stationID)
obj.name = station.stationName
obj.system_id = station.solarSystemID
objs.append(obj)
with transaction.atomic():
for obj in objs:
obj.save()

View File

@@ -0,0 +1,93 @@
import sqlite3
from django.core.management.base import BaseCommand
from django.db import transaction, connection
from evesde.models import *
class Command(BaseCommand):
help = 'Extracts data from the sqlite version of the SDE to the database.'
def handle(self, *args, **options):
dbfile = args[0]
try:
conn = sqlite3.connect(dbfile)
except:
print("Unable to open the SDE file at %s" % dbfile)
print "Emptying existing tables..."
with transaction.atomic():
cursor = connection.cursor()
for mdl in [Region, Constellation, System]:
cursor.execute('DELETE FROM "{0}"'.format(mdl._meta.db_table))
objs = []
# eveUnits
print "Importing eveUnits..."
conn.execute("""SELECT unitID, unitName, displayName FROM eveUnits""")
for row in conn.fetchall():
objs.append(UnitType(pk=row[0], name=row[1], display_name=row[2] or ''))
# dgmAttributeTypes
print "Importing dgmAttributeTypes..."
conn.execute("""SELECT attributeID, attributeName, displayName, unitID FROM dgmAttributeTypes""")
for row in conn.fetchall():
objs.append(AttributeType(pk=row[0], name=row[1], display_name=row[2] or '', unit_id=row[3]))
# invCategories
print "Importing invCategories..."
conn.execute("""SELECT categoryID, categoryName FROM invCategories""")
for row in conn.fetchall():
objs.append(TypeCategory(pk=row[0], name=row[1]))
# invGroups
print "Importing invGroups..."
conn.execute("""SELECT groupID, groupName, categoryID FROM invGroups""")
for row in conn.fetchall():
objs.append(TypeGroup(pk=row[0], name=row[1], category_id=row[2]))
# invTypes
print "Importing invTypes..."
conn.execute("""SELECT typeID, typeName, capacity, groupID FROM invTypes""")
for row in conn.fetchall():
objs.append(Type(pk=row[0], name="".join(i for i in row[1] if ord(i)<128), capacity=row[2], group_id=row[3]))
# dgmTypeAttributes
print "Importing dgmTypeAttributes..."
conn.execute("""SELECT typeID, attributeID, valueInt, valueFloat FROM dgmTypeAttributes""")
for row in conn.fetchall():
objs.append(TypeAttribute(type_id=row[0], attribute_id=row[1], valueint=row[2], valuefloat=row[3]))
# mapDenormalized
print "Importing mapDenormalize..."
conn.execute("""SELECT itemID, typeID, groupID, solarSystemID, constellationID, regionID, orbitID, x, y, z, itemName FROM mapDenormalize WHERE typeID in (3, 4, 5, 14) OR groupID = 7""")
for row in conn.fetchall():
id, type, group, solarid, constellationid, regionid, orbitid, x, y, z, name = row
if int(type) == 3:
objs.append(Region(pk=id, name=name, x=0, y=0, z=0))
elif int(type) == 4:
objs.append(Constellation(pk=id, name=name, region_id=regionid, x=0, y=0, z=0))
elif int(type) == 5:
objs.append(System(pk=id, name=name, constellation_id=constellationid, x=0, y=0, z=0))
elif int(group) == 7:
objs.append(Planet(pk=id, name=name, system_id=solarid, x=x, y=y, z=z))
elif int(type) == 14:
objs.append(Moon(pk=id, name=name, planet_id=orbitid, x=x, y=y, z=z))
print "Done"
# mapSolarSystemJumps
print "Importing Jumps..."
with transaction.atomic():
for row in conn.execute("""SELECT fromSolarSystemID, toSolarSystemID FROM mapSolarSystemJumps"""):
frm, to = row
objs.append(SystemJump(to_system_id=to, from_system_id=frm))
print 'Processing %d objects... ' % len(objs)
with transaction.atomic():
for i, x in enumerate(objs, start=1):
if i % 1000 == 0: print "%d/%d (%d%%)" % (i, len(objs), round(i/len(objs) * 100))
x.save()
print 'Commited'

View File

@@ -0,0 +1,3 @@
from locations import Location, Region, Constellation, System, SystemJump, Planet, Moon, Station
from objects import InSpaceObject
from types import TypeCategory, TypeGroup, Type, UnitType, AttributeType, TypeAttribute

169
evesde/models/locations.py Normal file
View File

@@ -0,0 +1,169 @@
from django.db import models
from .utils import InheritanceQuerySet
class LocationManager(models.Manager):
def all_subclassed(self):
return InheritanceQuerySet(model=self.model).select_subclasses()
class Location(models.Model):
"""
Parent model for Locations
"""
id = models.BigIntegerField('Location ID', primary_key=True)
name = models.CharField('Name', max_length=255)
x = models.DecimalField('X', max_digits=22, decimal_places=0)
y = models.DecimalField('Y', max_digits=22, decimal_places=0)
z = models.DecimalField('Z', max_digits=22, decimal_places=0)
objects = LocationManager()
def __unicode__(self):
return u"%(name)s" % self.__dict__
class Meta:
app_label = 'evesde'
ordering = ['name']
class Region(Location):
"""
Represents a EVE region
"""
@property
def systems(self):
return System.objects.filter(constellation__in=self.constellations.all())
@property
def planets(self):
return Planet.objects.filter(system__constellation__in=self.constellations.all())
@property
def moons(self):
return Moon.objects.filter(planet__system__constellation__in=self.constellations.all())
class Meta:
app_label = 'evesde'
ordering = ['name']
class Constellation(Location):
"""
Represents a Constellation
"""
region = models.ForeignKey(Region, related_name='constellations')
@property
def planets(self):
return Planet.objects.filter(system__in=self.systems.all())
@property
def moons(self):
return Moon.objects.filter(planet__system__in=self.systems.all())
class Meta:
app_label = 'evesde'
ordering = ['name']
class System(Location):
"""
Represents a System
"""
SYSTEM_SECURITY_CLASS_HIGHSEC = 1
SYSTEM_SECURITY_CLASS_LOWSEC = 2
SYSTEM_SECURITY_CLASS_NULLSEC = 3
SYSTEM_SECURITY_CLASS_CHOICES = (
(SYSTEM_SECURITY_CLASS_HIGHSEC, 'Highsec'),
(SYSTEM_SECURITY_CLASS_LOWSEC, 'Lowsec'),
(SYSTEM_SECURITY_CLASS_NULLSEC, 'Nullsec'),
)
# http://blog.evepanel.net/eve-online/igb/colors-of-the-security-status.html
SYSTEM_SECURITY_CLASS_COLORS = dict([
(1.0, '#2FEFEF'),
(0.9, '#48F0C0'),
(0.8, '#00EF47'),
(0.7, '#00F000'),
(0.6, '#8FEF2F'),
(0.5, '#EFEF00'),
(0.4, '#D77700'),
(0.3, '#F06000'),
(0.2, '#F04800'),
(0.1, '#D73000'),
(0.0, '#F00000'),
])
constellation = models.ForeignKey(Constellation, related_name='systems')
jumps = models.ManyToManyField('self', through='SystemJump', symmetrical=False, related_name='+')
security = models.DecimalField('Security', max_digits=2, decimal_places=1)
@property
def security_class(self):
if self.security <= 0:
return self.SYSTEM_SECURITY_CLASS_NULLSEC
elif self.security <= 0.4:
return self.SYSTEM_SECURITY_CLASS_LOWSEC
return self.SYSTEM_SECURITY_CLASS_HIGHSEC
def get_security_class_display(self):
sec = self.security_class
for val, name in self.SYSTEM_SECURITY_CLASS_CHOICES:
if val == sec:
return name
return "Unknown"
def get_system_color(self):
if self.security < 0:
return self.SYSTEM_SECURITY_CLASS_COLORS[0.0]
else:
return self.SYSTEM_SECURITY_CLASS_COLORS[float(self.security)]
@property
def region(self):
return self.constellation.region
@property
def moons(self):
return Moon.objects.filter(planet__in=self.planets.all())
class Meta:
app_label = 'evesde'
ordering = ['name']
class Planet(Location):
system = models.ForeignKey(System, related_name='planets')
class Meta:
app_label = 'evesde'
class Moon(Location):
planet = models.ForeignKey(Planet, related_name='moons')
class Meta:
app_label = 'evesde'
class SystemJump(models.Model):
from_system = models.ForeignKey(System, related_name='+')
to_system = models.ForeignKey(System, related_name='+')
def __unicode__(self):
return u"%s to %s" % (self.from_system, self.to_system)
class Meta:
app_label = 'evesde'
class Station(Location):
system = models.ForeignKey(System, related_name='stations')
class Meta:
app_label = 'evesde'

21
evesde/models/objects.py Normal file
View File

@@ -0,0 +1,21 @@
from django.db import models
from evesde.app_defines import *
from .types import Type
from .locations import System, Moon
class InSpaceObject(models.Model):
"""Represents a object in space"""
id = models.BigIntegerField('Object ID', primary_key=True)
type = models.ForeignKey(Type, related_name='assets')
system = models.ForeignKey(System, related_name='assets')
x = models.BigIntegerField('X Location', null=True)
y = models.BigIntegerField('Y Location', null=True)
z = models.BigIntegerField('Z Location', null=True)
class Meta:
app_label = 'evesde'
def __unicode__(self):
return '%s (%s)' % (self.type.name, self.system.name)

112
evesde/models/types.py Normal file
View File

@@ -0,0 +1,112 @@
from django.conf import settings
from django.db import models
class TypeCategory(models.Model):
id = models.BigIntegerField('Type Category ID', primary_key=True)
name = models.CharField('Type Category Name', max_length=200)
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.name
class TypeGroup(models.Model):
id = models.BigIntegerField('Type Group ID', primary_key=True)
category = models.ForeignKey(TypeCategory, related_name='groups')
name = models.CharField('Type Group Name', max_length=200)
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.name
class Type(models.Model):
"""Represents a EVE InvType"""
id = models.BigIntegerField('Type ID', primary_key=True)
group = models.ForeignKey(TypeGroup, related_name='types')
name = models.CharField('Type Name', max_length=200)
capacity = models.BigIntegerField('Capacity')
@property
def image(self):
return '%s/Type/%s_%s.png' % (
getattr(settings, 'EVE_IMAGESERVER_URL', 'https://image.eveonline.com'),
self.pk,
getattr(settings, 'EVE_IMAGESERVER_TYPESIZE', 64)
)
def render(self, size):
if size % 32:
raise ValueError('Size isn\'t a multiple of 32')
if size > 512:
raise ValueError('Size is too large (max 512px)')
return '%s/Render/%s_%s.png' % (
getattr(settings, 'EVE_IMAGESERVER_URL', 'https://image.eveonline.com'),
self.pk,
size
)
@property
def attributes_list(self):
return [(attr.attribute.display_name or attr.attribute.name, attr.get_value_display()) for attr in self.attributes.all()]
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.name
class UnitType(models.Model):
id = models.BigIntegerField('Unit ID', primary_key=True)
name = models.CharField('Unit Name', max_length=200)
display_name = models.CharField('Display Name', max_length=200)
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.name
class AttributeType(models.Model):
id = models.BigIntegerField('Attribute ID', primary_key=True)
name = models.CharField('Attribute Name', max_length=200)
display_name = models.CharField('Display Name', max_length=200)
unit = models.ForeignKey(UnitType, related_name='+', null=True)
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.name
class TypeAttribute(models.Model):
type = models.ForeignKey(Type, related_name='attributes')
attribute = models.ForeignKey(AttributeType, related_name='+')
valueint = models.BigIntegerField('Int Value', null=True)
valuefloat = models.FloatField('Float Value', null=True)
@property
def value(self):
return self.valuefloat or self.valueint
def get_value_display(self):
if self.attribute.unit:
return u'%d%s' % (self.value, self.attribute.unit.display_name)
return self.value
class Meta:
app_label = 'evesde'
def __unicode__(self):
return self.attribute.name

30
evesde/models/utils.py Normal file
View File

@@ -0,0 +1,30 @@
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.db.models.query import QuerySet
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj]
yield obj[0]
else:
for obj in iter:
yield obj

16
evesde/tests.py Normal file
View File

@@ -0,0 +1,16 @@
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)

1
evesde/views.py Normal file
View File

@@ -0,0 +1 @@
# Create your views here.