models.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.db import models
  4. from django.core.validators import MaxValueValidator
  5. from django.core.exceptions import ValidationError
  6. from coin.members.models import count_active_members
  7. from coin.offers.models import count_active_subscriptions
  8. # API version, see http://db.ffdn.org/format
  9. API_VERSION = 0.1
  10. TECHNOLOGIES = (('ftth', 'FTTH'),
  11. ('dsl', '*DSL'),
  12. ('wifi', 'WiFi'))
  13. class SingleInstanceMixin(object):
  14. """Makes sure that no more than one instance of a given model is created."""
  15. def clean(self):
  16. model = self.__class__
  17. if (model.objects.count() > 0 and self.id != model.objects.get().id):
  18. raise ValidationError("Can only create 1 instance of %s" % model.__name__)
  19. super(SingleInstanceMixin, self).clean()
  20. class ISPInfo(SingleInstanceMixin, models.Model):
  21. """http://db.ffdn.org/format
  22. The naming convention is different from Python/django so that it
  23. matches exactly the format (which uses CamelCase...)
  24. """
  25. name = models.CharField(max_length=512,
  26. help_text="The ISP's name")
  27. # Length required by the spec
  28. shortname = models.CharField(max_length=15, blank=True,
  29. help_text="Shorter name")
  30. description = models.TextField(blank=True,
  31. help_text="Short text describing the project")
  32. logoURL = models.URLField(blank=True,
  33. verbose_name="logo URL",
  34. help_text="HTTP(S) URL of the ISP's logo")
  35. website = models.URLField(blank=True,
  36. help_text='URL to the official website')
  37. email = models.EmailField(max_length=254,
  38. help_text="Contact email address")
  39. mainMailingList = models.EmailField(max_length=254, blank=True,
  40. verbose_name="main mailing list",
  41. help_text="Main public mailing-list")
  42. creationDate = models.DateField(blank=True, null=True,
  43. verbose_name="creation date",
  44. help_text="Date of creation for legal structure")
  45. ffdnMemberSince = models.DateField(blank=True, null=True,
  46. verbose_name="FFDN member since",
  47. help_text="Date at wich the ISP joined the Federation")
  48. # TODO: choice field
  49. progressStatus = models.PositiveSmallIntegerField(
  50. validators=[MaxValueValidator(7)],
  51. blank=True, null=True, verbose_name='progress status',
  52. help_text="Progression status of the ISP")
  53. # TODO: better model for coordinates
  54. latitude = models.FloatField(blank=True, null=True,
  55. help_text="Coordinates of the registered office (latitude)")
  56. longitude = models.FloatField(blank=True, null=True,
  57. help_text="Coordinates of the registered office (longitude)")
  58. # Uncomment this if you want to manage these counters by hand.
  59. #member_count = models.PositiveIntegerField(help_text="Number of members")
  60. #subscriber_count = models.PositiveIntegerField(
  61. # help_text="Number of subscribers to an internet access")
  62. @property
  63. def memberCount(self):
  64. """Number of members"""
  65. return count_active_members()
  66. @property
  67. def subscriberCount(self):
  68. """Number of subscribers to an internet access"""
  69. return count_active_subscriptions()
  70. @property
  71. def version(self):
  72. """Version of the API"""
  73. return API_VERSION
  74. def get_absolute_url(self):
  75. return '/isp.json'
  76. def to_dict(self):
  77. data = dict()
  78. # These are required
  79. for f in ('version', 'name', 'email', 'memberCount', 'subscriberCount'):
  80. data[f] = getattr(self, f)
  81. # These are optional
  82. for f in ('shortname', 'description', 'logoURL', 'website',
  83. 'mainMailingList', 'progressStatus'):
  84. if getattr(self, f):
  85. data[f] = getattr(self, f)
  86. # Dates
  87. for d in ('creationDate', 'ffdnMemberSince'):
  88. if getattr(self, d):
  89. data[d] = getattr(self, d).isoformat()
  90. # Hackish for now
  91. if self.latitude or self.longitude:
  92. data['coordinates'] = { "latitude": self.latitude,
  93. "longitude": self.longitude }
  94. # Related objects
  95. data['coveredAreas'] = [c.to_dict() for c in self.coveredarea_set.all()]
  96. otherwebsites = self.otherwebsite_set.all()
  97. if otherwebsites:
  98. data['otherWebsites'] = { site.name: site.url for site in otherwebsites }
  99. chatrooms = self.chatroom_set.all()
  100. if chatrooms:
  101. data['chatrooms'] = [chatroom.url for chatroom in chatrooms]
  102. if hasattr(self, 'registeredoffice'):
  103. data['registeredOffice'] = self.registeredoffice.to_dict()
  104. return data
  105. def __unicode__(self):
  106. return self.name
  107. class OtherWebsite(models.Model):
  108. name = models.CharField(max_length=512)
  109. url = models.URLField(verbose_name="URL")
  110. isp = models.ForeignKey(ISPInfo)
  111. class RegisteredOffice(models.Model):
  112. """ http://json-schema.org/address """
  113. post_office_box = models.CharField(max_length=512, blank=True)
  114. extended_address = models.CharField(max_length=512, blank=True)
  115. street_address = models.CharField(max_length=512, blank=True)
  116. locality = models.CharField(max_length=512)
  117. region = models.CharField(max_length=512)
  118. postal_code = models.CharField(max_length=512, blank=True)
  119. country_name = models.CharField(max_length=512)
  120. isp = models.OneToOneField(ISPInfo)
  121. def to_dict(self):
  122. d = dict()
  123. for field in ('post_office_box', 'extended_address', 'street_address',
  124. 'locality', 'region', 'postal_code', 'country_name'):
  125. if getattr(self, field):
  126. key = field.replace('_', '-')
  127. d[key] = getattr(self, field)
  128. return d
  129. class ChatRoom(models.Model):
  130. url = models.CharField(verbose_name="URL", max_length=256)
  131. isp = models.ForeignKey(ISPInfo)
  132. class CoveredArea(models.Model):
  133. name = models.CharField(max_length=512)
  134. # TODO: we must allow multiple values
  135. technologies = models.CharField(choices=TECHNOLOGIES, max_length=16)
  136. # TODO: find a geojson library
  137. #area =
  138. isp = models.ForeignKey(ISPInfo)
  139. def to_dict(self):
  140. return {"name": self.name,
  141. "technologies": [self.technologies]}