<commit_before>from __future__ import unicode_literals

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _

from .apns import (apns_fetch_inactive_ids, apns_send_bulk_message,
					apns_send_message)
from .fields import HexIntegerField

SERVICE_GCM = 0
SERVICE_APNS = 1
SERVICE_INACTIVE = 2

SERVICES = (
	(SERVICE_GCM, "GCM"),
	(SERVICE_APNS, "APNS"),
	(SERVICE_INACTIVE, "Inactive"),
)


class DeviceManager(models.Manager):
	def get_queryset(self):
		return DeviceQuerySet(self.model)

	def invalidate(self, registration_ids):
		""" Called when some registration ids are deemed invalid. """
		self.filter(registration_id__in=registration_ids).update(service=SERVICE_INACTIVE)


class DeviceQuerySet(models.query.QuerySet):
	def send_message(self, message, **kwargs):
		if self:
			gcmDevices = []
			apnsDevices = []

			for device in self:
				if device.service == SERVICE_APNS:
					apnsDevices.append(device)
				elif device.service == SERVICE_GCM:
					gcmDevices.append(device)

			if apnsDevices:
				apns_send_bulk_message(
					devices=apnsDevices,
					alert=message,
					certificate=apnsDevices[0].APNS_CERTIFICATE,
					**kwargs
				)

			if gcmDevices:
				data = kwargs.pop("extra", {})
				if message is not None:
					data["message"] = message

				from .gcm import gcm_send_bulk_message
				return gcm_send_bulk_message(
					devices=gcmDevices,
					data=data,
					api_key=gcmDevices[0].GCM_API_KEY,
					**kwargs
				)
			return None


class BareDevice(models.Model):
	service = models.IntegerField(
		choices=SERVICES,
		verbose_name=_("Notification service"),
		default=SERVICE_INACTIVE
	)
	registration_id = models.TextField(
		blank=True,
		verbose_name=_("Registration ID")
	)

	objects = DeviceManager()
	APNS_CERTIFICATE = settings.PUSH_NOTIFICATIONS_SETTINGS.get("APNS_CERTIFICATE", None) if hasattr(settings, 'PUSH_NOTIFICATIONS_SETTINGS') else None
	GCM_API_KEY = settings.PUSH_NOTIFICATIONS_SETTINGS.get("GCM_API_KEY", None) if hasattr(settings, 'PUSH_NOTIFICATIONS_SETTINGS') else None

	class Meta:
		abstract = True

	@cached_property
	def active(self):
		return self.service != SERVICE_INACTIVE

	def save(self, *args, **kwargs):
		if (self.service != SERVICE_INACTIVE
			and not self.registration_id):
			self.invalidate()
		else:
			if (self.service == SERVICE_APNS
				and len(self.registration_id) > 64):
				raise ValidationError("APNS registration_id's max length is 64.")
			super(BareDevice, self).save(*args, **kwargs)

	def send_message(self, message, **kwargs):
		if self.active:
			if self.service == SERVICE_APNS:
				return apns_send_message(
					device=self,
					alert=message,
					certificate=self.APNS_CERTIFICATE,
					**kwargs
				)
			else:
				data = kwargs.pop("extra", {})
				if message is not None:
					data["message"] = message
				from .gcm import gcm_send_message
				return gcm_send_message(
					device=self,
					data=data,
					api_key=self.GCM_API_KEY,
					**kwargs
				)

	def invalidate(self):
		""" Called when the registration_id is deemed invalid. """
		self.service = SERVICE_INACTIVE
		self.save()

	def __unicode__(self):
		return "{service}: {registration_id}".format(
			service=self.get_service_display(),
			registration_id=self.registration_id
		)


class SimpleDevice(BareDevice):
	pass


class Device(models.Model):
	name = models.CharField(max_length=255, verbose_name=_("Name"), blank=True, null=True)<commit_msg>BareDevice.invalidate optional save argument added.<commit_after>from __future__ import unicode_literals

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _

from .apns import (apns_fetch_inactive_ids, apns_send_bulk_message,
					apns_send_message)
from .fields import HexIntegerField

SERVICE_GCM = 0
SERVICE_APNS = 1
SERVICE_INACTIVE = 2

SERVICES = (
	(SERVICE_GCM, "GCM"),
	(SERVICE_APNS, "APNS"),
	(SERVICE_INACTIVE, "Inactive"),
)


class DeviceManager(models.Manager):
	def get_queryset(self):
		return DeviceQuerySet(self.model)

	def invalidate(self, registration_ids):
		""" Called when some registration ids are deemed invalid. """
		self.filter(registration_id__in=registration_ids).update(service=SERVICE_INACTIVE)


class DeviceQuerySet(models.query.QuerySet):
	def send_message(self, message, **kwargs):
		if self:
			gcmDevices = []
			apnsDevices = []

			for device in self:
				if device.service == SERVICE_APNS:
					apnsDevices.append(device)
				elif device.service == SERVICE_GCM:
					gcmDevices.append(device)

			if apnsDevices:
				apns_send_bulk_message(
					devices=apnsDevices,
					alert=message,
					certificate=apnsDevices[0].APNS_CERTIFICATE,
					**kwargs
				)

			if gcmDevices:
				data = kwargs.pop("extra", {})
				if message is not None:
					data["message"] = message

				from .gcm import gcm_send_bulk_message
				return gcm_send_bulk_message(
					devices=gcmDevices,
					data=data,
					api_key=gcmDevices[0].GCM_API_KEY,
					**kwargs
				)
			return None


class BareDevice(models.Model):
	service = models.IntegerField(
		choices=SERVICES,
		verbose_name=_("Notification service"),
		default=SERVICE_INACTIVE
	)
	registration_id = models.TextField(
		blank=True,
		verbose_name=_("Registration ID")
	)

	objects = DeviceManager()
	APNS_CERTIFICATE = settings.PUSH_NOTIFICATIONS_SETTINGS.get("APNS_CERTIFICATE", None) if hasattr(settings, 'PUSH_NOTIFICATIONS_SETTINGS') else None
	GCM_API_KEY = settings.PUSH_NOTIFICATIONS_SETTINGS.get("GCM_API_KEY", None) if hasattr(settings, 'PUSH_NOTIFICATIONS_SETTINGS') else None

	class Meta:
		abstract = True

	@cached_property
	def active(self):
		return self.service != SERVICE_INACTIVE

	def save(self, *args, **kwargs):
		if (self.service != SERVICE_INACTIVE
			and not self.registration_id):
			self.invalidate(save=False)
		if (self.service == SERVICE_APNS
			and len(self.registration_id) > 64):
			raise ValidationError("APNS registration_id's max length is 64.")
		super(BareDevice, self).save(*args, **kwargs)

	def send_message(self, message, **kwargs):
		if self.active:
			if self.service == SERVICE_APNS:
				return apns_send_message(
					device=self,
					alert=message,
					certificate=self.APNS_CERTIFICATE,
					**kwargs
				)
			else:
				data = kwargs.pop("extra", {})
				if message is not None:
					data["message"] = message
				from .gcm import gcm_send_message
				return gcm_send_message(
					device=self,
					data=data,
					api_key=self.GCM_API_KEY,
					**kwargs
				)

	def invalidate(self, save=True):
		""" Called when the registration_id is deemed invalid. """
		self.service = SERVICE_INACTIVE
		if save:
			self.save()

	def __unicode__(self):
		return "{service}: {registration_id}".format(
			service=self.get_service_display(),
			registration_id=self.registration_id
		)


class SimpleDevice(BareDevice):
	pass


class Device(models.Model):
	name = models.CharField(max_length=255, verbose_name=_("Name"), blank=True, null=True)
{'fraction_non_alphanumeric': 0.10275967272222992, 'fraction_numerical': 0.003328248509222022, 'mean_word_length': 4.5053435114503815, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2947327', 'n_tokens_mistral': 2852, 'n_tokens_neox': 2427, 'n_words': 507}