# Path: apps/core/models.py
# class ServiceMap(models.Model):
#     """
#     denotes single (user, service) pair
#     - sid:             unique mapping id
#     - user:            user object
#     - service:         service object
#     - register_time:   register time
#     - unregister_time: unregister time
#     """
#     sid = models.CharField(max_length=20, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE,
#                              related_name='services')
#     service = models.ForeignKey(Service, on_delete=models.CASCADE)
#     register_time = models.DateTimeField()
#     unregister_time = models.DateTimeField(null=True, blank=True)
# 
#     def __str__(self):
#         return f'{self.user} - {self.service}'


import hmac
import time
import requests
from secrets import token_hex
from django.utils import timezone
from apps.core.models import ServiceMap




# Register Service
def service_register(user, service):
    m = ServiceMap.objects.filter(user=user, service=service).first()
    if m and not m.unregister_time:
        return None
    elif m and m.unregister_time and \
            (timezone.now() - m.unregister_time).days < service.cooltime:
        return None
    elif m:
        m.delete()

    while True:
        sid = token_hex(10)
        if not ServiceMap.objects.filter(sid=sid).count():
            break


# Path: apps/core/models.py
# class ServiceMap(models.Model):
#     """
#     denotes single (user, service) pair
#     - sid:             unique mapping id
#     - user:            user object
#     - service:         service object
#     - register_time:   register time
#     - unregister_time: unregister time
#     """
#     sid = models.CharField(max_length=20, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE,
#                              related_name='services')
#     service = models.ForeignKey(Service, on_delete=models.CASCADE)
#     register_time = models.DateTimeField()
#     unregister_time = models.DateTimeField(null=True, blank=True)
# 
#     def __str__(self):
#         return f'{self.user} - {self.service}'


# Path: apps/core/backends/service.py
import hmac
import time
import requests
from secrets import token_hex
from django.utils import timezone
from apps.core.models import ServiceMap





# Register Service
def service_register(user, service):
    m = ServiceMap.objects.filter(user=user, service=service).first()
    if m and not m.unregister_time:
        return None
    elif m and m.unregister_time and \
            (timezone.now() - m.unregister_time).days < service.cooltime:
        return None
    elif m:
        m.delete()

    while True:
        sid = token_hex(10)
        if not ServiceMap.objects.filter(sid=sid).count():
            break


    m = ServiceMap(sid=sid, user=user, service=service,