# Path: bidb/keys/models.py
# class Key(models.Model):
#     uid = models.CharField(max_length=255, unique=True)
# 
#     name = models.TextField()
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('-created',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d uid=%r name=%r" % (
#             self.pk,
#             self.uid,
#             self.name,
#         )
# 
#     def save(self, *args, **kwargs):
#         created = not self.pk
# 
#         super(Key, self).save(*args, **kwargs)
# 
#         if created:
#             from .tasks import update_or_create_key
# 
#             transaction.on_commit(lambda: update_or_create_key.delay(self.uid))
# 
# Path: bidb/packages/models.py
# class Source(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'packages:source', (self.name,)
# 
# class Architecture(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
# class Binary(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'packages:binary', (self.name,)
# 
# Path: bidb/buildinfo/models.py
# class Buildinfo(models.Model):
#     sha1 = models.CharField(max_length=40, unique=True)
# 
#     source = models.ForeignKey(
#         'packages.Source',
#         related_name='buildinfos',
#     )
# 
#     architecture = models.ForeignKey(
#         'packages.Architecture',
#         related_name='buildinfos',
#     )
#     version = models.CharField(max_length=200)
# 
#     build_path = models.CharField(max_length=512)
#     build_date = models.DateTimeField(null=True)
#     build_origin = models.ForeignKey('Origin', null=True)
#     build_architecture = models.ForeignKey(
#         'packages.Architecture',
#         related_name='buildinfos_build',
#     )
# 
#     environment = models.TextField()
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('-created',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d source=%r version=%r" % (
#             self.pk,
#             self.source,
#             self.version,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'buildinfo:view', (self.sha1, self.get_filename())
# 
#     @models.permalink
#     def get_absolute_raw_url(self):
#         return 'buildinfo:raw-text', (self.sha1, self.get_filename())
# 
#     def get_filename(self):
#         return '{}_{}_{}'.format(
#             self.source.name,
#             self.version,
#             self.architecture.name.split(' ')[0],
#         )
# 
#     def get_storage_name(self):
#         return 'buildinfo.Buildinfo/{}/{}/{}'.format(
#             self.sha1[:2],
#             self.sha1[2:4],
#             self.sha1,
#         )
# 
# class Origin(models.Model):
#     name = models.CharField(max_length=255)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )


import re
import hashlib
from debian import deb822
from dateutil.parser import parse
from django.db import transaction, IntegrityError
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from bidb.keys.models import Key
from bidb.packages.models import Source, Architecture, Binary
from bidb.buildinfo.models import Buildinfo, Origin

    ## Parse new .buildinfo ###################################################

    def get_or_create(model, field):
        try:
            return model.objects.get_or_create(name=data[field])[0]
        except KeyError:
            raise InvalidSubmission("Missing required field: {}".format(field))

    if data.get('Format') not in SUPPORTED_FORMATS:
        raise InvalidSubmission(
            "Only {} 'Format:'  versions are supported".format(
                ', '.join(sorted(SUPPORTED_FORMATS)),
            )
        )

    sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest()

    try:
        with transaction.atomic():
            buildinfo = Buildinfo.objects.create(
                sha1=sha1,

                source=get_or_create(Source, 'Source'),
                architecture=get_or_create(Architecture, 'Architecture'),
                version=data['version'],

                build_path=data.get('Build-Path', ''),
                build_date=parse(data.get('Build-Date', '')),
                build_origin=get_or_create(Origin, 'Build-Origin'),

# Path: bidb/keys/models.py
# class Key(models.Model):
#     uid = models.CharField(max_length=255, unique=True)
# 
#     name = models.TextField()
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('-created',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d uid=%r name=%r" % (
#             self.pk,
#             self.uid,
#             self.name,
#         )
# 
#     def save(self, *args, **kwargs):
#         created = not self.pk
# 
#         super(Key, self).save(*args, **kwargs)
# 
#         if created:
#             from .tasks import update_or_create_key
# 
#             transaction.on_commit(lambda: update_or_create_key.delay(self.uid))
# 
# Path: bidb/packages/models.py
# class Source(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'packages:source', (self.name,)
# 
# class Architecture(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
# class Binary(models.Model):
#     name = models.CharField(max_length=200, unique=True)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'packages:binary', (self.name,)
# 
# Path: bidb/buildinfo/models.py
# class Buildinfo(models.Model):
#     sha1 = models.CharField(max_length=40, unique=True)
# 
#     source = models.ForeignKey(
#         'packages.Source',
#         related_name='buildinfos',
#     )
# 
#     architecture = models.ForeignKey(
#         'packages.Architecture',
#         related_name='buildinfos',
#     )
#     version = models.CharField(max_length=200)
# 
#     build_path = models.CharField(max_length=512)
#     build_date = models.DateTimeField(null=True)
#     build_origin = models.ForeignKey('Origin', null=True)
#     build_architecture = models.ForeignKey(
#         'packages.Architecture',
#         related_name='buildinfos_build',
#     )
# 
#     environment = models.TextField()
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('-created',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d source=%r version=%r" % (
#             self.pk,
#             self.source,
#             self.version,
#         )
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'buildinfo:view', (self.sha1, self.get_filename())
# 
#     @models.permalink
#     def get_absolute_raw_url(self):
#         return 'buildinfo:raw-text', (self.sha1, self.get_filename())
# 
#     def get_filename(self):
#         return '{}_{}_{}'.format(
#             self.source.name,
#             self.version,
#             self.architecture.name.split(' ')[0],
#         )
# 
#     def get_storage_name(self):
#         return 'buildinfo.Buildinfo/{}/{}/{}'.format(
#             self.sha1[:2],
#             self.sha1[2:4],
#             self.sha1,
#         )
# 
# class Origin(models.Model):
#     name = models.CharField(max_length=255)
# 
#     created = models.DateTimeField(default=datetime.datetime.utcnow)
# 
#     class Meta:
#         ordering = ('name',)
#         get_latest_by = 'created'
# 
#     def __unicode__(self):
#         return u"pk=%d name=%r" % (
#             self.pk,
#             self.name,
#         )


# Path: bidb/api/utils.py
import re
import hashlib
from debian import deb822
from dateutil.parser import parse
from django.db import transaction, IntegrityError
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from bidb.keys.models import Key
from bidb.packages.models import Source, Architecture, Binary
from bidb.buildinfo.models import Buildinfo, Origin


    ## Parse new .buildinfo ###################################################

    def get_or_create(model, field):
        try:
            return model.objects.get_or_create(name=data[field])[0]
        except KeyError:
            raise InvalidSubmission("Missing required field: {}".format(field))

    if data.get('Format') not in SUPPORTED_FORMATS:
        raise InvalidSubmission(
            "Only {} 'Format:'  versions are supported".format(
                ', '.join(sorted(SUPPORTED_FORMATS)),
            )
        )

    sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest()

    try:
        with transaction.atomic():
            buildinfo = Buildinfo.objects.create(
                sha1=sha1,

                source=get_or_create(Source, 'Source'),
                architecture=get_or_create(Architecture, 'Architecture'),
                version=data['version'],

                build_path=data.get('Build-Path', ''),
                build_date=parse(data.get('Build-Date', '')),
                build_origin=get_or_create(Origin, 'Build-Origin'),

                build_architecture=get_or_create(Architecture, 'Build-Architecture'),