# Path: pyas2/models.py
# DEFAULT_ENTRY = ('', "---------")
#     CONTENT_TYPE_CHOICES = (
#         ('application/EDI-X12', 'application/EDI-X12'),
#         ('application/EDIFACT', 'application/EDIFACT'),
#         ('application/edi-consent', 'application/edi-consent'),
#         ('application/XML', 'application/XML'),
#         ('text/CSV', 'text/CSV'),
#     )
#     ENCRYPT_ALG_CHOICES = (
#         ('des_ede3_cbc', '3DES'),
#         ('des_cbc', 'DES'),
#         ('aes_128_cbc', 'AES-128'),
#         ('aes_192_cbc', 'AES-192'),
#         ('aes_256_cbc', 'AES-256'),
#         ('rc2_40_cbc', 'RC2-40'),
#     )
#     SIGN_ALG_CHOICES = (
#         ('sha1', 'SHA-1'),
#     )
#     MDN_TYPE_CHOICES = (
#         ('SYNC', 'Synchronous'),
#         ('ASYNC', 'Asynchronous'),
#     )
#     DIRECTION_CHOICES = (
#         ('IN', _('Inbound')),
#         ('OUT', _('Outbound')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Success')),
#         ('E', _('Error')),
#         ('W', _('Warning')),
#         ('P', _('Pending')),
#         ('R', _('Retry')),
#         ('IP', _('In Process')),
#     )
#     MODE_CHOICES = (
#         ('SYNC', _('Synchronous')),
#         ('ASYNC', _('Asynchronous')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Success')),
#         ('E', _('Error')),
#         ('W', _('Warning')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Sent')),
#         ('R', _('Received')),
#         ('P', _('Pending')),
#     )
# def get_certificate_path(instance, filename):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
# def getorganizations():
# def getpartners():
# def check_odirs(sender, instance, created, **kwargs):
# def check_pdirs(sender, instance, created, **kwargs):
# def update_dirs():
# class PrivateCertificate(models.Model):
# class PublicCertificate(models.Model):
# class Organization(models.Model):
# class Partner(models.Model):
# class Message(models.Model):
# class Payload(models.Model):
# class Log(models.Model):
# class MDN(models.Model):
# 
# Path: pyas2/pyas2init.py
# def initialize():
# def initserverlogging(logname):
# 
# Path: pyas2/as2lib.py
# def decompress_message(message, payload):
# def save_message(message, payload, raw_payload):
# def build_mdn(message, status, **kwargs):
# def build_message(message):
# def send_message(message, payload):
# def save_mdn(message, mdn_content):
# def run_post_send(message):
# def run_post_receive(message, full_filename):
# 
# Path: pyas2/as2utils.py
# def senderrorreport(message, errortext):
# def txtexc(mention_exception_type=True):
# def safe_unicode(value):
#     def __init__(self, msg, *args, **kwargs):
#     def __unicode__(self):
#     def __str__(self):
# def join(*paths):
# def dirshouldbethere(path):
# def opendata(filename, mode, charset=None, errors='strict'):
# def readdata(filename, charset=None, errors='strict'):
# def storefile(targetdir, filename, content, archive):
# def unescape_as2name(ename):
# def escape_as2name(uename):
# def extractpayload(message, **kwargs):
# def mimetostring(msg, headerlen):
# def extractpayload_fromstring1(msg, boundary):
# def extractpayload_fromstring2(msg, boundary):
# def canonicalize2(msg):
# def canonicalize(msg):
# def compress_payload(payload):
# def decompress_payload(payload):
# def encrypt_payload(payload, key, cipher):
# def decrypt_payload(payload, key, passphrase):
# def sign_payload(data, key, passphrase):
# def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert):
# def get_key_passphrase(self):
# def check_binary_sig(signature, boundary, content):
# class AS2Error(Exception):
# class As2Exception(AS2Error):
# class As2DuplicateDocument(AS2Error):
# class As2PartnerNotFound(AS2Error):
# class As2InsufficientSecurity(AS2Error):
# class As2DecompressionFailed(AS2Error):
# class As2DecryptionFailed(AS2Error):
# class As2InvalidSignature(AS2Error):
# class CompressedDataAttr(univ.Sequence):
# class Content(univ.OctetString):
# class CompressedDataPayload(univ.Sequence):
# class CompressedData(univ.Sequence):
# class CompressedDataMain(univ.Sequence):


from django.core.management.base import BaseCommand
from django.utils.translation import ugettext as _
from pyas2 import models
from pyas2 import pyas2init
from pyas2 import as2lib
from pyas2 import as2utils

class Command(BaseCommand):
    help = _(u'Retrying all failed outbound communications')

    def handle(self, *args, **options):
        pyas2init.logger.info(_(u'Retrying all failed outbound messages'))

        # Get the list of all messages with status retry
        failed_msgs = models.Message.objects.filter(status='R', direction='OUT')

        for failed_msg in failed_msgs:
            # Increase the retry count
            if not failed_msg.retries:
                failed_msg.retries = 1
            else:
                failed_msg.retries += failed_msg.retries

            # if max retries has exceeded then mark message status as error
            if failed_msg.retries > pyas2init.gsettings['max_retries']:
                failed_msg.status = 'E'
                models.Log.objects.create(message=failed_msg,
                                          status='E',
                                          text=_(u'Message exceeded maximum retries, marked as error'))
                failed_msg.save()
                continue

            pyas2init.logger.info(_(u'Retrying send of message with ID %s' % failed_msg))
            try:
                # Build and resend the AS2 message
                payload = as2lib.build_message(failed_msg)

# Path: pyas2/models.py
# DEFAULT_ENTRY = ('', "---------")
#     CONTENT_TYPE_CHOICES = (
#         ('application/EDI-X12', 'application/EDI-X12'),
#         ('application/EDIFACT', 'application/EDIFACT'),
#         ('application/edi-consent', 'application/edi-consent'),
#         ('application/XML', 'application/XML'),
#         ('text/CSV', 'text/CSV'),
#     )
#     ENCRYPT_ALG_CHOICES = (
#         ('des_ede3_cbc', '3DES'),
#         ('des_cbc', 'DES'),
#         ('aes_128_cbc', 'AES-128'),
#         ('aes_192_cbc', 'AES-192'),
#         ('aes_256_cbc', 'AES-256'),
#         ('rc2_40_cbc', 'RC2-40'),
#     )
#     SIGN_ALG_CHOICES = (
#         ('sha1', 'SHA-1'),
#     )
#     MDN_TYPE_CHOICES = (
#         ('SYNC', 'Synchronous'),
#         ('ASYNC', 'Asynchronous'),
#     )
#     DIRECTION_CHOICES = (
#         ('IN', _('Inbound')),
#         ('OUT', _('Outbound')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Success')),
#         ('E', _('Error')),
#         ('W', _('Warning')),
#         ('P', _('Pending')),
#         ('R', _('Retry')),
#         ('IP', _('In Process')),
#     )
#     MODE_CHOICES = (
#         ('SYNC', _('Synchronous')),
#         ('ASYNC', _('Asynchronous')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Success')),
#         ('E', _('Error')),
#         ('W', _('Warning')),
#     )
#     STATUS_CHOICES = (
#         ('S', _('Sent')),
#         ('R', _('Received')),
#         ('P', _('Pending')),
#     )
# def get_certificate_path(instance, filename):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
#     def __str__(self):
# def getorganizations():
# def getpartners():
# def check_odirs(sender, instance, created, **kwargs):
# def check_pdirs(sender, instance, created, **kwargs):
# def update_dirs():
# class PrivateCertificate(models.Model):
# class PublicCertificate(models.Model):
# class Organization(models.Model):
# class Partner(models.Model):
# class Message(models.Model):
# class Payload(models.Model):
# class Log(models.Model):
# class MDN(models.Model):
# 
# Path: pyas2/pyas2init.py
# def initialize():
# def initserverlogging(logname):
# 
# Path: pyas2/as2lib.py
# def decompress_message(message, payload):
# def save_message(message, payload, raw_payload):
# def build_mdn(message, status, **kwargs):
# def build_message(message):
# def send_message(message, payload):
# def save_mdn(message, mdn_content):
# def run_post_send(message):
# def run_post_receive(message, full_filename):
# 
# Path: pyas2/as2utils.py
# def senderrorreport(message, errortext):
# def txtexc(mention_exception_type=True):
# def safe_unicode(value):
#     def __init__(self, msg, *args, **kwargs):
#     def __unicode__(self):
#     def __str__(self):
# def join(*paths):
# def dirshouldbethere(path):
# def opendata(filename, mode, charset=None, errors='strict'):
# def readdata(filename, charset=None, errors='strict'):
# def storefile(targetdir, filename, content, archive):
# def unescape_as2name(ename):
# def escape_as2name(uename):
# def extractpayload(message, **kwargs):
# def mimetostring(msg, headerlen):
# def extractpayload_fromstring1(msg, boundary):
# def extractpayload_fromstring2(msg, boundary):
# def canonicalize2(msg):
# def canonicalize(msg):
# def compress_payload(payload):
# def decompress_payload(payload):
# def encrypt_payload(payload, key, cipher):
# def decrypt_payload(payload, key, passphrase):
# def sign_payload(data, key, passphrase):
# def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert):
# def get_key_passphrase(self):
# def check_binary_sig(signature, boundary, content):
# class AS2Error(Exception):
# class As2Exception(AS2Error):
# class As2DuplicateDocument(AS2Error):
# class As2PartnerNotFound(AS2Error):
# class As2InsufficientSecurity(AS2Error):
# class As2DecompressionFailed(AS2Error):
# class As2DecryptionFailed(AS2Error):
# class As2InvalidSignature(AS2Error):
# class CompressedDataAttr(univ.Sequence):
# class Content(univ.OctetString):
# class CompressedDataPayload(univ.Sequence):
# class CompressedData(univ.Sequence):
# class CompressedDataMain(univ.Sequence):


# Path: pyas2/management/commands/retryfailedas2comms.py
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext as _
from pyas2 import models
from pyas2 import pyas2init
from pyas2 import as2lib
from pyas2 import as2utils


class Command(BaseCommand):
    help = _(u'Retrying all failed outbound communications')

    def handle(self, *args, **options):
        pyas2init.logger.info(_(u'Retrying all failed outbound messages'))

        # Get the list of all messages with status retry
        failed_msgs = models.Message.objects.filter(status='R', direction='OUT')

        for failed_msg in failed_msgs:
            # Increase the retry count
            if not failed_msg.retries:
                failed_msg.retries = 1
            else:
                failed_msg.retries += failed_msg.retries

            # if max retries has exceeded then mark message status as error
            if failed_msg.retries > pyas2init.gsettings['max_retries']:
                failed_msg.status = 'E'
                models.Log.objects.create(message=failed_msg,
                                          status='E',
                                          text=_(u'Message exceeded maximum retries, marked as error'))
                failed_msg.save()
                continue

            pyas2init.logger.info(_(u'Retrying send of message with ID %s' % failed_msg))
            try:
                # Build and resend the AS2 message
                payload = as2lib.build_message(failed_msg)

                as2lib.send_message(failed_msg, payload)