models.py 7.4 KB

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