models.py 6.8 KB

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