bgneal@285: """
bgneal@285: This module contains a class for handling attachments on forum posts.
bgneal@285: """
bgneal@285: from oembed.models import Oembed
bgneal@285: from forums.models import Attachment
bgneal@285: 
bgneal@285: 
bgneal@285: class AttachmentProcessor(object):
bgneal@285:     """
bgneal@285:     This class is aggregated by various form classes to handle
bgneal@285:     attachments on forum posts. New posts can receive attachments and edited
bgneal@285:     posts can have their attachments replaced, augmented, or deleted.
bgneal@285: 
bgneal@285:     """
bgneal@285:     def __init__(self, ids):
bgneal@285:         """
bgneal@285:         This class is constructed with a list of Oembed ids. We retrieve the
bgneal@285:         actual Oembed objects associated with these keys for use in subsequent
bgneal@285:         operations.
bgneal@286: 
bgneal@285:         """
bgneal@285:         # ensure all ids are integers
bgneal@285:         self.pks = []
bgneal@285:         for pk in ids:
bgneal@285:             try:
bgneal@285:                 pk = int(pk)
bgneal@285:             except ValueError:
bgneal@285:                 continue
bgneal@285:             self.pks.append(pk)
bgneal@285: 
bgneal@285:         self.embeds = []
bgneal@285:         if self.pks:
bgneal@285:             self.embeds = Oembed.objects.in_bulk(self.pks)
bgneal@285: 
bgneal@285:     def save_attachments(self, post):
bgneal@285:         """
bgneal@285:         Create and save attachments to the supplied post object.
bgneal@285:         Any existing attachments on the post are removed first.
bgneal@285: 
bgneal@285:         """
bgneal@285:         post.attachments.clear()
bgneal@285: 
bgneal@285:         for n, pk in enumerate(self.pks):
bgneal@285:             attachment = Attachment(post=post, embed=self.embeds[pk], order=n)
bgneal@285:             attachment.save()
bgneal@286: 
bgneal@286:     def has_attachments(self):
bgneal@286:         """
bgneal@286:         Return true if we have valid pending attachments.
bgneal@286: 
bgneal@286:         """
bgneal@286:         return len(self.embeds) > 0
bgneal@286: 
bgneal@286:     def get_ids(self):
bgneal@286:         """
bgneal@286:         Return the list of Oembed ids.
bgneal@286: 
bgneal@286:         """
bgneal@286:         return self.pks