Exemplo n.º 1
0
    def test_approve_listing(self):
        apps_mall_steward = generic_model_access.get_profile('wsmith')
        username = apps_mall_steward.user.username
        air_mail = models.Listing.objects.for_user(username).get(title='Air Mail')

        model_access.approve_listing(apps_mall_steward, air_mail)

        air_mail = models.Listing.objects.for_user(username).get(title='Air Mail')
        self.assertEqual(air_mail.last_activity.action, models.ListingActivity.APPROVED)

        listing_activities = air_mail.listing_activities.filter(action=models.ListingActivity.APPROVED)
        approved_org_activity = listing_activities[0]
        self.assertEqual(approved_org_activity.author.user.username, username)
Exemplo n.º 2
0
    def update(self, instance, validated_data):
        logger.debug('inside ListingSerializer.update')
        user = generic_model_access.get_profile(
            self.context['request'].user.username)

        if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
            if user not in instance.owners.all():
                raise errors.PermissionDenied(
                    'User is not an owner of this listing')

        change_details = []

        simple_fields = ['title', 'description', 'description_short',
            'launch_url', 'version_name', 'requirements', 'unique_name',
            'what_is_new', 'security_marking']

        for i in simple_fields:
            if getattr(instance, i) != validated_data[i]:
                change_details.append({'old_value': getattr(instance, i),
                    'new_value': validated_data[i], 'field_name': i})
                setattr(instance, i, validated_data[i])

        if validated_data['is_enabled'] != instance.is_enabled:
            if validated_data['is_enabled']:
                model_access.enable_listing(user, instance)
                change_details.append({'field_name': 'is_enabled',
                    'old_value': 'false', 'new_value': 'true'})
            else:
                model_access.disable_listing(user, instance)
                change_details.append({'field_name': 'is_enabled',
                    'old_value': 'true', 'new_value': 'false'})

            instance.is_enabled = validated_data['is_enabled']

        if validated_data['is_private'] != instance.is_private:
            change_details.append({'old_value': model_access.bool_to_string(instance.is_private),
                    'new_value': model_access.bool_to_string(validated_data['is_private']), 'field_name': 'is_private'})
            instance.is_private = validated_data['is_private']

        if validated_data['is_featured'] != instance.is_featured:
            if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied('Only stewards can change is_featured setting of a listing')
            change_details.append({'old_value': model_access.bool_to_string(instance.is_featured),
                    'new_value': model_access.bool_to_string(validated_data['is_featured']), 'field_name': 'is_featured'})
            instance.is_featured = validated_data['is_featured']

        s = validated_data['approval_status']
        if s and s != instance.approval_status:
            if s == models.Listing.APPROVED and user.highest_role() != 'APPS_MALL_STEWARD':
                raise errors.PermissionDenied('Only an APPS_MALL_STEWARD can mark a listing as APPROVED')
            if s == models.Listing.APPROVED_ORG and user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied('Only stewards can mark a listing as APPROVED_ORG')

            if s == models.Listing.PENDING:
                model_access.submit_listing(user, instance)
            if s == models.Listing.APPROVED_ORG:
                model_access.approve_listing_by_org_steward(user, instance)
            if s == models.Listing.APPROVED:
                model_access.approve_listing(user, instance)
            if s == models.Listing.REJECTED:
                # TODO: need to get the rejection text from somewhere
                model_access.reject_listing(user, instance, 'TODO: rejection reason')

        if instance.listing_type != validated_data['listing_type']:
            if instance.listing_type:
                old_value = instance.listing_type.title
            else:
                old_value = None
            if validated_data['listing_type']:
                new_value = validated_data['listing_type'].title
            else:
                new_value = None
            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'listing_type'})
            instance.listing_type = validated_data['listing_type']

        image_keys = ['small_icon', 'large_icon', 'banner_icon', 'large_banner_icon']
        for image_key in image_keys:
            if validated_data[image_key]:
                old_value = model_access.image_to_string(getattr(instance, image_key), True, 'old_value(%s)'%image_key)
                new_value = model_access.image_to_string(validated_data[image_key], False, 'new_value(%s)'%image_key)

                if old_value != new_value:
                    new_value_image = None

                    old_image_id = None
                    if old_value is not None:
                        old_image_id = getattr(instance, image_key).id
                    if validated_data[image_key].get('id') == old_image_id:
                        new_value_image = getattr(instance, image_key)
                        new_value_image.security_marking = validated_data[image_key].get('security_marking')
                        new_value_image.save()
                    else:
                        new_value_image = image_model_access.get_image_by_id(validated_data[image_key].get('id'))

                        if new_value_image is None:
                            raise errors.InvalidInput('Error while saving, can not find image by id')

                    change_details.append({'old_value': old_value,
                            'new_value': new_value, 'field_name': image_key})

                    if image_key == 'small_icon':
                        instance.small_icon = new_value_image
                    elif image_key == 'large_icon':
                        instance.large_icon = new_value_image
                    elif image_key == 'banner_icon':
                        instance.banner_icon = new_value_image
                    elif image_key == 'large_banner_icon':
                        instance.large_banner_icon = new_value_image

        if 'contacts' in validated_data:
            old_contact_instances = instance.contacts.all()
            old_contacts = model_access.contacts_to_string(
                old_contact_instances, True)
            new_contacts = model_access.contacts_to_string(
                validated_data['contacts'])

            if old_contacts != new_contacts:
                change_details.append({'old_value': old_contacts,
                    'new_value': new_contacts, 'field_name': 'contacts'})
                instance.contacts.clear()
                for contact in validated_data['contacts']:
                    # TODO: Smarter Handling of Duplicates Contact Records
                    # A contact with the same name and email should be the same contact
                    # in the backend.
                    # Person1(name='N1',email='*****@*****.**') and
                    #    Person1' (name='N1',email='*****@*****.**',secure_phone = '414-444-444')
                    # The two people above should be one contact
                    # if approval_status: "IN_PROGRESS" then it should be using
                    # contact model ids' since it is temporary contacts
                    obj, created = models.Contact.objects.get_or_create(
                        name=contact['name'],
                        email=contact['email'],
                        secure_phone=contact['secure_phone'],
                        unsecure_phone=contact['unsecure_phone'],
                        organization=contact.get('organization', None),
                        contact_type=contact_type_model_access.get_contact_type_by_name(
                            contact['contact_type']['name'])
                    )
                    instance.contacts.add(obj)

        if 'categories' in validated_data:
            old_category_instances = instance.categories.all()
            old_categories = model_access.categories_to_string(
                old_category_instances, True)
            new_categories = model_access.categories_to_string(
                validated_data['categories'], True)
            if old_categories != new_categories:
                change_details.append({'old_value': old_categories,
                    'new_value': new_categories, 'field_name': 'categories'})
                instance.categories.clear()
                for category in validated_data['categories']:
                    instance.categories.add(category)

        if 'owners' in validated_data:
            old_owner_instances = instance.owners.all()
            old_owners = model_access.owners_to_string(
                old_owner_instances, True)
            new_owners = model_access.owners_to_string(
                validated_data['owners'], True)
            if old_owners != new_owners:
                change_details.append({'old_value': old_owners,
                    'new_value': new_owners, 'field_name': 'owners'})
                instance.owners.clear()
                for owner in validated_data['owners']:
                    instance.owners.add(owner)

        # tags will be automatically created if necessary
        if 'tags' in validated_data:
            old_tag_instances = instance.tags.all()
            old_tags = model_access.tags_to_string(old_tag_instances, True)
            new_tags = model_access.tags_to_string(validated_data['tags'])
            if old_tags != new_tags:
                change_details.append({'old_value': old_tags,
                    'new_value': new_tags, 'field_name': 'tags'})
                instance.tags.clear()
                for tag in validated_data['tags']:
                    obj, created = models.Tag.objects.get_or_create(
                        name=tag['name'])
                    instance.tags.add(obj)

        if 'intents' in validated_data:
            old_intent_instances = instance.intents.all()
            old_intents = model_access.intents_to_string(old_intent_instances,
                True)
            new_intents = model_access.intents_to_string(
                validated_data['intents'], True)
            if old_intents != new_intents:
                change_details.append({'old_value': old_intents,
                    'new_value': new_intents, 'field_name': 'intents'})
                instance.intents.clear()
                for intent in validated_data['intents']:
                    instance.intents.add(intent)

        # doc_urls will be automatically created
        if 'doc_urls' in validated_data:
            old_doc_url_instances = model_access.get_doc_urls_for_listing(instance)
            old_doc_urls = model_access.doc_urls_to_string(
                old_doc_url_instances, True)
            new_doc_urls = model_access.doc_urls_to_string(
                validated_data['doc_urls'])
            if old_doc_urls != new_doc_urls:
                change_details.append({
                    'old_value': old_doc_urls,
                    'new_value': new_doc_urls,
                    'field_name': 'doc_urls'})

                new_doc_url_instances = []
                for d in validated_data['doc_urls']:
                    obj, created = models.DocUrl.objects.get_or_create(
                        name=d['name'], url=d['url'], listing=instance)
                    new_doc_url_instances.append(obj)
                for i in old_doc_url_instances:
                    if i not in new_doc_url_instances:
                        logger.info('Deleting doc_url: %s' % i.id)
                        i.delete()

        # screenshots will be automatically created
        if 'screenshots' in validated_data:
            old_screenshot_instances = model_access.get_screenshots_for_listing(instance)
            old_screenshots = model_access.screenshots_to_string(old_screenshot_instances, True)
            new_screenshots = model_access.screenshots_to_string(validated_data['screenshots'])
            if old_screenshots != new_screenshots:
                change_details.append({'old_value': old_screenshots,
                    'new_value': new_screenshots, 'field_name': 'screenshots'})

            new_screenshot_instances = []

            for s in validated_data['screenshots']:

                new_small_image = image_model_access.get_image_by_id(s['small_image']['id'])
                new_small_image.security_marking = s['small_image']['security_marking']
                new_small_image.save()

                new_large_image = image_model_access.get_image_by_id(s['large_image']['id'])
                new_large_image.security_marking = s['large_image']['security_marking']
                new_large_image.save()

                obj, created = models.Screenshot.objects.get_or_create(
                    small_image=new_small_image,
                    large_image=new_large_image,
                    listing=instance)


                new_screenshot_instances.append(obj)

            for i in old_screenshot_instances:
                if i not in new_screenshot_instances:
                    logger.info('Deleting screenshot: %s' % i.id)
                    i.delete()

        if 'agency' in validated_data:
            if instance.agency != validated_data['agency']:
                change_details.append({'old_value': instance.agency.title,
                    'new_value': validated_data['agency'].title, 'field_name': 'agency'})
                instance.agency = validated_data['agency']

        instance.save()

        model_access.log_listing_modification(user, instance, change_details)
        instance.edited_date = datetime.datetime.now(pytz.utc)
        return instance
def run():
    """
    Creates basic sample data
    """
    # Create Groups
    models.Profile.create_groups()

    ############################################################################
    #                           Security Markings
    ############################################################################
    unclass = 'UNCLASSIFIED'
    secret = 'SECRET'
    secret_n = 'SECRET//NOVEMBER'
    ts = 'TOP SECRET'
    ts_s = 'TOP SECRET//SIERRA'
    ts_st = 'TOP SECRET//SIERRA//TANGO'
    ts_stgh = 'TOP SECRET//SIERRA//TANGO//GOLF//HOTEL'

    ts_n = 'TOP SECRET//NOVEMBER'
    ts_sn = 'TOP SECRET//SIERRA//NOVEMBER'
    ts_stn = 'TOP SECRET//SIERRA//TANGO//NOVEMBER'
    ts_stghn = 'TOP SECRET//SIERRA//TANGO//GOLF//HOTEL//NOVEMBER'

    ############################################################################
    #                           Categories
    ############################################################################
    books_ref = models.Category(title="Books and Reference",
        description="Things made of paper")
    books_ref.save()
    business = models.Category(title="Business",
        description="For making money")
    business.save()
    communication = models.Category(title="Communication",
        description="Moving info between people and things")
    communication.save()
    education = models.Category(title="Education",
        description="Educational in nature")
    education.save()
    entertainment = models.Category(title="Entertainment",
        description="For fun")
    entertainment.save()
    finance = models.Category(title="Finance",
        description="For managing money")
    finance.save()
    health_fitness = models.Category(title="Health and Fitness",
        description="Be healthy, be fit")
    health_fitness.save()
    media_video = models.Category(title="Media and Video",
        description="Videos and media stuff")
    media_video.save()
    music_audio = models.Category(title="Music and Audio",
        description="Using your ears")
    music_audio.save()
    news = models.Category(title="News",
        description="What's happening where")
    news.save()
    productivity = models.Category(title="Productivity",
        description="Do more in less time")
    productivity.save()
    shopping = models.Category(title="Shopping",
        description="For spending your money")
    shopping.save()
    sports = models.Category(title="Sports",
        description="Score more points than your opponent")
    sports.save()
    tools = models.Category(title="Tools",
        description="Tools and Utilities")
    tools.save()
    weather = models.Category(title="Weather",
        description="Get the temperature")
    weather.save()


    ############################################################################
    #                           Contact Types
    ############################################################################
    civillian = models.ContactType(name='Civillian')
    civillian.save()
    government = models.ContactType(name='Government')
    government.save()
    military = models.ContactType(name='Military')
    military.save()

    ############################################################################
    #                           Listing Types
    ############################################################################
    web_app = models.ListingType(title='web application',
        description='web applications')
    web_app.save()
    widget = models.ListingType(title='widget',
        description='widget things')
    widget.save()
    dev_resource = models.ListingType(title='developer resource',
        description='APIs and resources for developers')
    dev_resource.save()

    ############################################################################
    #                           Image Types
    ############################################################################
    # Note: these image sizes do not represent those that should be used in
    # production
    small_icon_type = models.ImageType(name='small_icon',
        max_size_bytes='4096')
    small_icon_type.save()
    large_icon_type = models.ImageType(name='large_icon',
        max_size_bytes='8192')
    large_icon_type.save()
    banner_icon_type = models.ImageType(name='banner_icon',
        max_size_bytes='2097152')
    banner_icon_type.save()
    large_banner_icon_type = models.ImageType(name='large_banner_icon',
        max_size_bytes='2097152')
    large_banner_icon_type.save()
    small_screenshot_type = models.ImageType(name='small_screenshot',
        max_size_bytes='1048576')
    small_screenshot_type.save()
    large_screenshot_type = models.ImageType(name='large_screenshot',
        max_size_bytes='1048576')
    large_screenshot_type.save()
    intent_icon_type = models.ImageType(name='intent_icon',
        max_size_bytes='2097152')
    intent_icon_type.save()
    agency_icon_type = models.ImageType(name='agency_icon',
        max_size_bytes='2097152')
    agency_icon_type.save()

    ############################################################################
    #                           Intents
    ############################################################################
    # TODO: more realistic data
    img = Image.open(TEST_IMG_PATH + 'android.png')
    icon = models.Image.create_image(img, file_extension='png',
        security_marking='UNCLASSIFIED', image_type=intent_icon_type.name)
    i = models.Intent(action='/application/json/view',
        media_type='vnd.ozp-intent-v1+json.json',
        label='view',
        icon=icon)
    i.save()

    i = models.Intent(action='/application/json/edit',
        media_type='vnd.ozp-intent-v1+json.json',
        label='edit',
        icon=icon)
    i.save()

    ############################################################################
    #                           Organizations
    ############################################################################
    img = Image.open(TEST_IMG_PATH + 'ministry_of_truth.jpg')
    icon = models.Image.create_image(img, file_extension='jpg',
        security_marking='UNCLASSIFIED', image_type='agency_icon')
    minitrue = models.Agency(title='Ministry of Truth', short_name='Minitrue',
        icon=icon)
    minitrue.save()

    img = Image.open(TEST_IMG_PATH + 'ministry_of_peace.png')
    icon = models.Image.create_image(img, file_extension='png',
        security_marking='UNCLASSIFIED', image_type='agency_icon')
    minipax = models.Agency(title='Ministry of Peace', short_name='Minipax',
        icon=icon)
    minipax.save()

    img = Image.open(TEST_IMG_PATH + 'ministry_of_love.jpeg')
    icon = models.Image.create_image(img, file_extension='jpeg',
        security_marking='UNCLASSIFIED', image_type='agency_icon')
    miniluv = models.Agency(title='Ministry of Love', short_name='Miniluv',
        icon=icon)
    miniluv.save()

    img = Image.open(TEST_IMG_PATH + 'ministry_of_plenty.png')
    icon = models.Image.create_image(img, file_extension='png',
        security_marking='UNCLASSIFIED', image_type='agency_icon')
    miniplenty = models.Agency(title='Ministry of Plenty',
        short_name='Miniplen', icon=icon)
    miniplenty.save()

    ############################################################################
    #                               Tags
    ############################################################################
    demo =  models.Tag(name='demo')
    demo.save()
    example = models.Tag(name='example')
    example.save()

    ############################################################################
    #                               Org Stewards
    ############################################################################
    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA', 'TANGO'],
        'visas': ['NOVEMBER']
    })
    winston = models.Profile.create_user('wsmith',
        email='*****@*****.**',
        display_name='Winston Smith',
        bio='I work at the Ministry of Truth',
        access_control=access_control,
        organizations=['Ministry of Truth'],
        stewarded_organizations=['Ministry of Truth'],
        groups=['ORG_STEWARD'],
        dn='Winston Smith wsmith'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA'],
        'visas': []
    })
    julia = models.Profile.create_user('julia',
        email='*****@*****.**',
        display_name='Julia Dixon',
        bio='An especially zealous propagandist',
        access_control=access_control,
        organizations=['Ministry of Truth'],
        stewarded_organizations=['Ministry of Truth', 'Ministry of Love'],
        groups=['ORG_STEWARD'],
        dn='Julia Dixon jdixon'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA', 'TANGO', 'GOLF', 'HOTEL'],
        'visas': ['NOVEMBER']
    })
    obrien = models.Profile.create_user('obrien',
        email='*****@*****.**',
        display_name='O\'brien',
        bio='I will find you, winston and julia',
        access_control=access_control,
        organizations=['Ministry of Peace'],
        stewarded_organizations=['Ministry of Peace', 'Ministry of Plenty'],
        groups=['ORG_STEWARD'],
        dn='O\'Brien obrien'
    )

    ############################################################################
    #                               Apps Mall Stewards
    ############################################################################

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA', 'TANGO', 'GOLF', 'HOTEL'],
        'visas': ['NOVEMBER']
    })
    big_brother = models.Profile.create_user('bigbrother',
        email='*****@*****.**',
        display_name='Big Brother',
        bio='I make everyones life better',
        access_control=access_control,
        organizations=['Ministry of Peace'],
        groups=['APPS_MALL_STEWARD'],
        dn='Big Brother bigbrother'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA', 'TANGO', 'GOLF', 'HOTEL'],
        'visas': ['NOVEMBER']
    })
    big_brother2 = models.Profile.create_user('bigbrother2',
        email='*****@*****.**',
        display_name='Big Brother2',
        bio='I also make everyones life better',
        access_control=access_control,
        organizations=['Ministry of Truth'],
        groups=['APPS_MALL_STEWARD'],
        dn='Big Brother2 bigbrother2'
    )

    ############################################################################
    #                               Regular user
    ############################################################################

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET'],
        'formal_accesses': [],
        'visas': ['NOVEMBER']
    })
    aaronson = models.Profile.create_user('aaronson',
        email='*****@*****.**',
        display_name='Aaronson',
        bio='Nothing special',
        access_control=access_control,
        organizations=['Ministry of Love'],
        groups=['USER'],
        dn='Aaronson aaronson'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET'],
        'formal_accesses': [],
        'visas': ['NOVEMBER']
    })
    jones = models.Profile.create_user('jones',
        email='*****@*****.**',
        display_name='Jones',
        bio='I am a normal person',
        access_control=access_control,
        organizations=['Ministry of Truth'],
        groups=['USER'],
        dn='Jones jones'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET'],
        'formal_accesses': [],
        'visas': []
    })
    rutherford = models.Profile.create_user('rutherford',
        email='*****@*****.**',
        display_name='Rutherford',
        bio='I am a normal person',
        access_control=access_control,
        organizations=['Ministry of Plenty'],
        groups=['USER'],
        dn='Rutherford rutherford'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA'],
        'visas': []
    })
    syme = models.Profile.create_user('syme',
        email='*****@*****.**',
        display_name='Syme',
        bio='I am too smart for my own good',
        access_control=access_control,
        organizations=['Ministry of Peace'],
        groups=['USER'],
        dn='Syme syme'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED'],
        'formal_accesses': [],
        'visas': []
    })
    tparsons = models.Profile.create_user('tparsons',
        email='*****@*****.**',
        display_name='Tom Parsons',
        bio='I am uneducated and loyal',
        access_control=access_control,
        organizations=['Ministry of Peace', 'Ministry of Love'],
        groups=['USER'],
        dn='Tparsons tparsons'
    )

    access_control = json.dumps({
        'clearances': ['UNCLASSIFIED', 'CONFIDENTIAL', 'SECRET', 'TOP SECRET'],
        'formal_accesses': ['SIERRA', 'TANGO', 'GOLF', 'HOTEL'],
        'visas': ['NOVEMBER']
    })
    charrington = models.Profile.create_user('charrington',
        email='*****@*****.**',
        display_name='Charrington',
        bio='A member of the Thought Police',
        access_control=access_control,
        organizations=['Ministry of Peace', 'Ministry of Love',
        'Ministry of Truth'],
        groups=['USER'],
        dn='Charrington charrington'
    )

    ############################################################################
    #                           System Notifications
    ############################################################################
    # create some notifications that expire next week
    next_week = datetime.datetime.now() + datetime.timedelta(days=7)
    eastern = pytz.timezone('US/Eastern')
    next_week = eastern.localize(next_week)
    n1 = models.Notification(message='System will be going down for \
        approximately 30 minutes on X/Y at 1100Z',
        expires_date=next_week, author=winston)
    n1.save()
    n2 = models.Notification(message='System will be functioning in a \
        degredaded state between 1800Z-0400Z on A/B',
        expires_date=next_week, author=julia)
    n2.save()

    # create some expired notifications
    last_week = datetime.datetime.now() - datetime.timedelta(days=7)
    last_week = eastern.localize(last_week)
    n1 = models.Notification(message='System will be going down for \
        approximately 30 minutes on C/D at 1700Z',
        expires_date=last_week, author=winston)
    n1.save()
    n2 = models.Notification(message='System will be functioning in a \
        degredaded state between 2100Z-0430Z on F/G',
        expires_date=last_week, author=julia)
    n2.save()

    ############################################################################
    #                           Contacts
    ############################################################################
    osha = models.Contact(name='Osha', organization='House Stark',
        contact_type=models.ContactType.objects.get(name='Civillian'),
        email='*****@*****.**', unsecure_phone='321-123-7894')
    osha.save()

    rob_baratheon = models.Contact(name='Robert Baratheon',
        organization='House Baratheon',
        contact_type=models.ContactType.objects.get(name='Government'),
        email='*****@*****.**', unsecure_phone='123-456-7890')
    rob_baratheon.save()

    brienne = models.Contact(name='Brienne Tarth', organization='House Stark',
        contact_type=models.ContactType.objects.get(name='Military'),
        email='*****@*****.**', unsecure_phone='222-324-3846')
    brienne.save()

    ############################################################################
    ############################################################################
    #                           Listings
    ############################################################################
    ############################################################################

    ############################################################################
    #                           Air Mail
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'AirMail16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'AirMail32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'AirMail.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'AirMailFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing = models.Listing(
        title='Air Mail',
        agency=minitrue,
        listing_type=web_app,
        description='Sends mail via air',
        launch_url='http://localhost/demo_apps/centerSampleListings/airMail/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.air_mail',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Sends airmail',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        security_marking=unclass
    )
    listing.save()
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Contacts
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing.contacts.add(osha)
    listing.contacts.add(brienne)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Owners
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing.owners.add(winston)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Categories
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing.categories.add(communication)
    listing.categories.add(productivity)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing.tags.add(demo)
    listing.tags.add(example)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Screenshots
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'screenshot_small.png')
    small_img = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_screenshot_type.name)
    img = Image.open(TEST_IMG_PATH + 'screenshot_large.png')
    large_img = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_screenshot_type.name)
    screenshot = models.Screenshot(small_image=small_img,
        large_image=large_img,
        listing=listing)
    screenshot.save()
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Notifications
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    notification1 = models.Notification(message='Air Mail update next week',
        expires_date=next_week, listing=listing, author=winston)
    notification1.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Reviews
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing_model_access.create_listing_review(charrington.user.username,
        listing, 5,
        text="This app is great - well designed and easy to use")

    listing_model_access.create_listing_review(tparsons.user.username,
        listing, 3,
        text="Air mail is ok - does what it says and no more")

    listing_model_access.create_listing_review(syme.user.username,
        listing, 1,
        text="Air mail crashes all the time - it doesn't even support IE 6!")

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Document URLs
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    wiki = models.DocUrl(name='wiki', url='http://www.google.com/wiki',
        listing=listing)
    wiki.save()
    guide = models.DocUrl(name='guide', url='http://www.google.com/guide',
        listing=listing)
    guide.save()

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           Bread Basket
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'BreadBasket16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'BreadBasket32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'BreadBasket.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'BreadBasketFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing = models.Listing(
        title='Bread Basket',
        agency=minitrue,
        listing_type=web_app,
        description='Carries delicious bread',
        launch_url='http://localhost/demo_apps/centerSampleListings/breadBasket/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.bread_basket',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Carries bread',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=True,
        security_marking=unclass
    )
    listing.save()

    listing.contacts.add(osha)
    listing.owners.add(julia)
    listing.categories.add(health_fitness)
    listing.categories.add(shopping)

    listing.tags.add(demo)
    listing.tags.add(example)

    listing_model_access.create_listing_review(jones.user.username,
        listing, 2,
        text="This bread is stale!")

    listing_model_access.create_listing_review(julia.user.username,
        listing, 5,
        text="Yum!")

    listing_model_access.create_listing(julia, listing)
    listing_model_access.submit_listing(julia, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           Chart Course
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'ChartCourse16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChartCourse32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChartCourse.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChartCourseFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='Chart Course',
        agency=minitrue,
        listing_type=web_app,
        description='Chart your course',
        launch_url='http://localhost/demo_apps/centerSampleListings/chartCourse/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.chartcourse',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Chart your course',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(winston)
    listing.categories.add(tools)
    listing.categories.add(education)
    listing.tags.add(demo)

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)


    ############################################################################
    #                           Chatter Box
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'ChatterBox16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChatterBox32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChatterBox.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ChatterBoxFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='Chatter Box',
        agency=miniluv,
        listing_type=web_app,
        description='Chat with people',
        launch_url='http://localhost/demo_apps/centerSampleListings/chatterBox/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.chatterbox',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Chat in a box',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(julia)
    listing.categories.add(communication)
    listing.tags.add(demo)

    listing_model_access.create_listing(julia, listing)
    listing_model_access.submit_listing(julia, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           Clipboard
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'Clipboard16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'Clipboard32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'Clipboard.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'ClipboardFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='Clipboard',
        agency=minitrue,
        listing_type=web_app,
        description='Clip stuff on a board',
        launch_url='http://localhost/demo_apps/centerSampleListings/clipboard/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.clipboard',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Its a clipboard',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(winston)
    listing.categories.add(tools)
    listing.categories.add(education)
    listing.tags.add(demo)

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           FrameIt
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'FrameIt16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'FrameIt32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'FrameIt.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'FrameItFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='FrameIt',
        agency=minitrue,
        listing_type=web_app,
        description='Show things in an iframe',
        launch_url='http://localhost/demo_apps/frameit/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.frameit',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Its an iframe',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(winston)
    listing.categories.add(tools)
    listing.categories.add(education)
    listing.tags.add(demo)

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           Hatch Latch
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'HatchLatch16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'HatchLatch32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'HatchLatch.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'HatchLatchFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='Hatch Latch',
        agency=minitrue,
        listing_type=web_app,
        description='Hatch latches',
        launch_url='http://localhost/demo_apps/centerSampleListings/hatchLatch/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.hatchlatch',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Its a hatch latch',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(winston)
    listing.categories.add(tools)
    listing.categories.add(education)
    listing.categories.add(health_fitness)
    listing.tags.add(demo)

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    ############################################################################
    #                           Jot Spot
    ############################################################################
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    img = Image.open(TEST_IMG_PATH + 'JotSpot16.png')
    small_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=small_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'JotSpot32.png')
    large_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'JotSpot.png')
    banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=banner_icon_type.name)
    img = Image.open(TEST_IMG_PATH + 'JotSpotFeatured.png')
    large_banner_icon = models.Image.create_image(img, file_extension='png',
        security_marking=unclass, image_type=large_banner_icon_type.name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    listing = models.Listing(
        title='JotSpot',
        agency=minitrue,
        listing_type=web_app,
        description='Jot things down',
        launch_url='http://localhost/demo_apps/centerSampleListings/jotSpot/index.html',
        version_name='1.0.0',
        unique_name='ozp.test.jotspot',
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new='Nothing really new here',
        description_short='Jot stuff down',
        requirements='None',
        is_enabled=True,
        is_featured=True,
        iframe_compatible=False,
        is_private=False,
        security_marking=unclass
    )
    listing.save()
    listing.contacts.add(rob_baratheon)
    listing.owners.add(winston)
    listing.categories.add(tools)
    listing.categories.add(education)
    listing.tags.add(demo)

    listing_model_access.create_listing(winston, listing)
    listing_model_access.submit_listing(winston, listing)
    listing_model_access.approve_listing_by_org_steward(winston, listing)
    listing_model_access.approve_listing(winston, listing)

    listing_model_access.create_listing_review(charrington.user.username,
        listing, 4,
        text="I really like it")

    ############################################################################
    #                           Library
    ############################################################################
    # bookmark listings
    library_entry = models.ApplicationLibraryEntry(
        owner=winston,
        listing=models.Listing.objects.get(unique_name='ozp.test.bread_basket'))
    library_entry.save()

    library_entry = models.ApplicationLibraryEntry(
        owner=winston,
        listing=models.Listing.objects.get(unique_name='ozp.test.air_mail'))
    library_entry.save()
Exemplo n.º 4
0
    def update(self, instance, validated_data):
        user = generic_model_access.get_profile(
            self.context['request'].user.username)

        if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
            if user not in instance.owners.all():
                raise errors.PermissionDenied(
                    'User is not an owner of this listing')

        change_details = []

        simple_fields = ['title', 'description', 'description_short',
            'launch_url', 'version_name', 'requirements', 'unique_name',
            'what_is_new', 'security_marking']

        for i in simple_fields:
            if getattr(instance, i) != validated_data[i]:
                change_details.append({'old_value': getattr(instance, i),
                    'new_value': validated_data[i], 'field_name': i})
                setattr(instance, i, validated_data[i])

        if validated_data['is_enabled'] != instance.is_enabled:
            if validated_data['is_enabled']:
                model_access.enable_listing(user, instance)
                change_details.append({'field_name': 'is_enabled',
                    'old_value': 'false', 'new_value': 'true'})
            else:
                model_access.disable_listing(user, instance)
                change_details.append({'field_name': 'is_enabled',
                    'old_value': 'true', 'new_value': 'false'})

            instance.is_enabled = validated_data['is_enabled']

        if validated_data['is_private'] != instance.is_private:
            change_details.append({'old_value': model_access.bool_to_string(instance.is_private),
                    'new_value': model_access.bool_to_string(validated_data['is_private']), 'field_name': 'is_private'})
            instance.is_private = validated_data['is_private']

        if validated_data['is_featured'] != instance.is_featured:
            if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied('Only stewards can change is_featured setting of a listing')
            change_details.append({'old_value': model_access.bool_to_string(instance.is_featured),
                    'new_value': model_access.bool_to_string(validated_data['is_featured']), 'field_name': 'is_featured'})
            instance.is_featured = validated_data['is_featured']

        s = validated_data['approval_status']
        if s and s != instance.approval_status:
            if s == models.Listing.APPROVED and user.highest_role() != 'APPS_MALL_STEWARD':
                raise errors.PermissionDenied('Only an APPS_MALL_STEWARD can mark a listing as APPROVED')
            if s == models.Listing.APPROVED_ORG and user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied('Only stewards can mark a listing as APPROVED_ORG')

            if s == models.Listing.PENDING:
                model_access.submit_listing(user, instance)
            if s == models.Listing.APPROVED_ORG:
                model_access.approve_listing_by_org_steward(user, instance)
            if s == models.Listing.APPROVED:
                model_access.approve_listing(user, instance)
            if s == models.Listing.REJECTED:
                # TODO: need to get the rejection text from somewhere
                model_access.reject_listing(user, instance, 'TODO: rejection reason')

        if instance.listing_type != validated_data['listing_type']:
            if instance.listing_type:
                old_value = instance.listing_type.title
            else:
                old_value = None
            if validated_data['listing_type']:
                new_value = validated_data['listing_type'].title
            else:
                new_value = None
            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'listing_type'})
            instance.listing_type = validated_data['listing_type']

        if instance.small_icon != validated_data['small_icon']:
            if instance.small_icon:
                old_value = instance.small_icon.id
            else:
                old_value = None
            if validated_data['small_icon']:
                new_value = validated_data['small_icon'].id
            else:
                new_value = None

            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'small_icon'})
            instance.small_icon = validated_data['small_icon']

        if instance.large_icon != validated_data['large_icon']:
            if instance.large_icon:
                old_value = instance.large_icon.id
            else:
                old_value = None
            if validated_data['large_icon']:
                new_value = validated_data['large_icon'].id
            else:
                new_value = None
            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'large_icon'})
            instance.large_icon = validated_data['large_icon']

        if instance.banner_icon != validated_data['banner_icon']:
            if instance.banner_icon:
                old_value = instance.banner_icon.id
            else:
                old_value = None
            if validated_data['banner_icon']:
                new_value = validated_data['banner_icon'].id
            else:
                new_value = None
            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'banner_icon'})
            instance.banner_icon = validated_data['banner_icon']

        if instance.large_banner_icon != validated_data['large_banner_icon']:
            if instance.large_banner_icon:
                old_value = instance.large_banner_icon.id
            else:
                old_value = None
            if validated_data['large_banner_icon']:
                new_value = validated_data['large_banner_icon'].id
            else:
                new_value = None
            change_details.append({'old_value': old_value,
                    'new_value': new_value, 'field_name': 'large_banner_icon'})
            instance.large_banner_icon = validated_data['large_banner_icon']

        if 'contacts' in validated_data:
            old_contact_instances = instance.contacts.all()
            old_contacts = model_access.contacts_to_string(
                old_contact_instances, True)
            new_contacts = model_access.contacts_to_string(
                validated_data['contacts'])
            if old_contacts != new_contacts:
                change_details.append({'old_value': old_contacts,
                    'new_value': new_contacts, 'field_name': 'contacts'})
                instance.contacts.clear()
                for contact in validated_data['contacts']:
                    obj, created = models.Contact.objects.get_or_create(
                        name=contact['name'],
                        email=contact['email'],
                        secure_phone=contact['secure_phone'],
                        unsecure_phone=contact['unsecure_phone'],
                        organization=contact.get('organization', None),
                        contact_type=contact_type_model_access.get_contact_type_by_name(
                            contact['contact_type']['name'])
                    )
                    instance.contacts.add(obj)

        if 'categories' in validated_data:
            old_category_instances = instance.categories.all()
            old_categories = model_access.categories_to_string(
                old_category_instances, True)
            new_categories = model_access.categories_to_string(
                validated_data['categories'], True)
            if old_categories != new_categories:
                change_details.append({'old_value': old_categories,
                    'new_value': new_categories, 'field_name': 'categories'})
                instance.categories.clear()
                for category in validated_data['categories']:
                    instance.categories.add(category)

        if 'owners' in validated_data:
            old_owner_instances = instance.owners.all()
            old_owners = model_access.owners_to_string(
                old_owner_instances, True)
            new_owners = model_access.owners_to_string(
                validated_data['owners'], True)
            if old_owners != new_owners:
                change_details.append({'old_value': old_owners,
                    'new_value': new_owners, 'field_name': 'owners'})
                instance.owners.clear()
                for owner in validated_data['owners']:
                    instance.owners.add(owner)

        # tags will be automatically created if necessary
        if 'tags' in validated_data:
            old_tag_instances = instance.tags.all()
            old_tags = model_access.tags_to_string(old_tag_instances, True)
            new_tags = model_access.tags_to_string(validated_data['tags'])
            if old_tags != new_tags:
                change_details.append({'old_value': old_tags,
                    'new_value': new_tags, 'field_name': 'tags'})
                instance.tags.clear()
                for tag in validated_data['tags']:
                    obj, created = models.Tag.objects.get_or_create(
                        name=tag['name'])
                    instance.tags.add(obj)

        if 'intents' in validated_data:
            old_intent_instances = instance.intents.all()
            old_intents = model_access.intents_to_string(old_intent_instances,
                True)
            new_intents = model_access.intents_to_string(
                validated_data['intents'], True)
            if old_intents != new_intents:
                change_details.append({'old_value': old_intents,
                    'new_value': new_intents, 'field_name': 'intents'})
                instance.intents.clear()
                for intent in validated_data['intents']:
                    instance.intents.add(intent)

        # doc_urls will be automatically created
        if 'doc_urls' in validated_data:
            old_doc_url_instances = model_access.get_doc_urls_for_listing(instance)
            old_doc_urls = model_access.doc_urls_to_string(
                old_doc_url_instances, True)
            new_doc_urls = model_access.doc_urls_to_string(
                validated_data['doc_urls'])
            if old_doc_urls != new_doc_urls:
                change_details.append({
                    'old_value': old_doc_urls,
                    'new_value': new_doc_urls,
                    'field_name': 'doc_urls'})

                new_doc_url_instances = []
                for d in validated_data['doc_urls']:
                    obj, created = models.DocUrl.objects.get_or_create(
                        name=d['name'], url=d['url'], listing=instance)
                    new_doc_url_instances.append(obj)
                for i in old_doc_url_instances:
                    if i not in new_doc_url_instances:
                        logger.info('Deleting doc_url: %s' % i.id)
                        i.delete()

        # screenshots will be automatically created
        if 'screenshots' in validated_data:
            old_screenshot_instances = model_access.get_screenshots_for_listing(instance)
            old_screenshots = model_access.screenshots_to_string(old_screenshot_instances, True)
            new_screenshots = model_access.screenshots_to_string(
                validated_data['screenshots'])
            if old_screenshots != new_screenshots:
                change_details.append({'old_value': old_screenshots,
                    'new_value': new_screenshots, 'field_name': 'screenshots'})

            new_screenshot_instances = []
            for s in validated_data['screenshots']:
                obj, created = models.Screenshot.objects.get_or_create(
                    small_image=image_model_access.get_image_by_id(
                        s['small_image']['id']),
                    large_image=image_model_access.get_image_by_id(
                        s['large_image']['id']),
                    listing=instance)
                new_screenshot_instances.append(obj)
            for i in old_screenshot_instances:
                if i not in new_screenshot_instances:
                    logger.info('Deleting screenshot: %s' % i.id)
                    i.delete()

        if 'agency' in validated_data:
            if instance.agency != validated_data['agency']:
                change_details.append({'old_value': instance.agency.title,
                    'new_value': validated_data['agency'].title, 'field_name': 'agency'})
                instance.agency = validated_data['agency']

        instance.save()

        model_access.log_listing_modification(user, instance, change_details)
        instance.edited_date = datetime.datetime.now(pytz.utc)
        return instance
Exemplo n.º 5
0
def create_listing(listing_builder_dict, object_cache):
    """
    Create Listing Helper Function

    10-01-2017 - Total Database Calls: 11842
    10-02-2017 - Total Database Calls: 7737
    """
    listing_data = listing_builder_dict['listing']

    listing = models.Listing(
        title=listing_data['title'],
        agency=object_cache['Agency.{}'.format(listing_data['agency'])],
        listing_type=object_cache['ListingType.{}'.format(
            listing_data['listing_type'])],
        description=listing_data['description'],
        launch_url=listing_data['launch_url'].format_map(
            {'DEMO_APP_ROOT': DEMO_APP_ROOT}),
        version_name=listing_data['version_name'],
        unique_name=listing_data['unique_name'],
        small_icon=object_cache['Listing[{}].small_icon'.format(
            listing_data['title'])],
        large_icon=object_cache['Listing[{}].large_icon'.format(
            listing_data['title'])],
        banner_icon=object_cache['Listing[{}].banner_icon'.format(
            listing_data['title'])],
        large_banner_icon=object_cache['Listing[{}].large_banner_icon'.format(
            listing_data['title'])],
        what_is_new=listing_data['what_is_new'],
        description_short=listing_data['description_short'],
        usage_requirements=listing_data['usage_requirements'],
        system_requirements=listing_data['system_requirements'],
        is_enabled=listing_data['is_enabled'],
        is_private=listing_data['is_private'],
        is_featured=listing_data['is_featured'],
        iframe_compatible=listing_data['iframe_compatible'],
        security_marking=listing_data['security_marking'])
    listing.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Contacts
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_contact in listing_data['contacts']:
        listing.contacts.add(
            object_cache['Contact.{}'.format(current_contact)])

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Owners
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_owner in listing_data['owners']:
        listing.owners.add(object_cache['Profile.{}'.format(current_owner)])

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Categories
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_category in listing_data['categories']:
        listing.categories.add(
            models.Category.objects.get(title=current_category))
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_tag in listing_data['tags']:
        if object_cache.get('Tag.{}'.format(current_tag)):
            current_tag_obj = object_cache['Tag.{}'.format(current_tag)]
        else:
            current_tag_obj, created = models.Tag.objects.get_or_create(
                name=current_tag)
        listing.tags.add(current_tag_obj)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Screenshots
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_screenshot_entry in listing_data['screenshots']:
        small_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH +
                       current_screenshot_entry['small_image']['filename']),
            file_extension=current_screenshot_entry['small_image']
            ['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['small_image']
            ['security_marking'],
            image_type=object_cache['ImageType.small_screenshot'].name)

        large_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH +
                       current_screenshot_entry['large_image']['filename']),
            file_extension=current_screenshot_entry['large_image']
            ['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['large_image']
            ['security_marking'],
            image_type=object_cache['ImageType.large_screenshot'].name)

        screenshot = models.Screenshot(
            small_image=small_image,
            large_image=large_image,
            listing=listing,
            description=current_screenshot_entry['description'],
            order=current_screenshot_entry['order'])
        screenshot.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Document URLs
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_doc_url_entry in listing_data['doc_urls']:
        current_doc_url_obj = models.DocUrl(name=current_doc_url_entry['name'],
                                            url=current_doc_url_entry['url'],
                                            listing=listing)
        current_doc_url_obj.save()

    # listing_activity
    for listing_activity_entry in listing_builder_dict['listing_activity']:
        listing_activity_action = listing_activity_entry['action']
        listing_activity_author = object_cache['Profile.{}'.format(
            listing_activity_entry['author'])]

        if listing_activity_action == 'CREATED':
            listing_model_access.create_listing(listing_activity_author,
                                                listing)
        elif listing_activity_action == 'SUBMITTED':
            listing_model_access.submit_listing(listing_activity_author,
                                                listing)
        elif listing_activity_action == 'APPROVED_ORG':
            listing_model_access.approve_listing_by_org_steward(
                listing_activity_author, listing)
        elif listing_activity_action == 'APPROVED':
            listing_model_access.approve_listing(listing_activity_author,
                                                 listing)

    return listing
Exemplo n.º 6
0
    def create_listing(self, listing: ListingData) -> models.Listing:
        agency = self.agencies_by_title.get(listing.agency_title, None)
        assert agency is not None, "Agency with title '{}' not found".format(
            listing.agency_title)

        listing_type = self.listing_types_by_title.get(
            listing.listing_type_title, None)
        assert listing_type is not None, "ListingType with title '{}' not found".format(
            listing.listing_type_title)

        small_icon = self.create_image(listing.small_icon)
        large_icon = self.create_image(listing.large_icon)
        banner_icon = self.create_image(listing.banner_icon)
        large_banner_icon = self.create_image(listing.large_banner_icon)

        instance = models.Listing(
            title=listing.title,
            description=listing.description,
            description_short=listing.description_short,
            launch_url=listing.launch_url,
            version_name=listing.version_name,
            unique_name=listing.unique_name,
            what_is_new=listing.what_is_new,
            usage_requirements=listing.usage_requirements,
            system_requirements=listing.system_requirements,
            security_marking=listing.security_marking,
            is_enabled=listing.is_enabled,
            is_private=listing.is_private,
            is_featured=listing.is_featured,
            is_exportable=listing.is_exportable,
            small_icon=small_icon,
            large_icon=large_icon,
            banner_icon=banner_icon,
            large_banner_icon=large_banner_icon,
            agency=agency,
            listing_type=listing_type)
        instance.save()

        for category_title in listing.category_titles:
            category = self.categories_by_title.get(category_title, None)
            assert category is not None, "Category with title '{}' not found".format(
                category_title)
            instance.categories.add(category)

        for contact_email in listing.contact_emails:
            contact = self.contacts_by_email.get(contact_email, None)
            assert contact is not None, "Contact with email '{}' not found".format(
                contact_email)
            instance.contacts.add(contact)

        for custom_field_value in listing.custom_field_values:
            self.create_custom_field_value(instance, custom_field_value)

        for intent_action in listing.intent_actions:
            intent = self.intents_by_action.get(intent_action, None)
            assert intent is not None, "Intent with action '{}' not found".format(
                intent_action)
            instance.intents.add(intent)

        for owner_username in listing.owner_usernames:
            owner = self.profiles_by_username.get(owner_username, None)
            assert owner is not None, "Profile with username '{}' not found".format(
                owner_username)
            instance.owners.add(owner)

        for tag_name in listing.tag_names:
            tag = self.tags_by_name.get(tag_name, None)
            assert tag is not None, "Tag with name '{}' not found".format(
                tag_name)
            instance.tags.add(tag)

        for screenshot in listing.screenshots:
            self.create_screenshot(instance, screenshot)

        for doc_url in listing.doc_urls:
            self.create_doc_url(instance, doc_url)

        for activity in listing.activities:
            author = self.profiles_by_username.get(activity.author_username,
                                                   None)
            assert author is not None, "Profile with username '{}' not found".format(
                activity.author_username)

            if activity.action == 'CREATED':
                listing_model_access.create_listing(author, instance)
            elif activity.action == 'SUBMITTED':
                listing_model_access.submit_listing(author, instance)
            elif activity.action == 'APPROVED_ORG':
                listing_model_access.approve_listing_by_org_steward(
                    author, instance)
            elif activity.action == 'APPROVED':
                listing_model_access.approve_listing(author, instance)

        return instance
Exemplo n.º 7
0
def update_listing(serializer_instance, instance, validated_data):
    # TODO Put in listing model_access.py
    user = generic_model_access.get_profile(serializer_instance.context['request'].user.username)

    if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
        if user not in instance.owners.all():
            raise errors.PermissionDenied(
                'User ({0!s}) is not an owner of this listing'.format(user.username))

    if instance.is_deleted:
        raise errors.PermissionDenied('Cannot update a previously deleted listing')

    change_details = []

    simple_fields = ['title', 'description', 'description_short',
        'launch_url', 'version_name', 'usage_requirements', 'system_requirements', 'unique_name',
        'what_is_new', 'security_marking']

    for i in simple_fields:
        if getattr(instance, i) != validated_data[i]:
            if validated_data[i] is not None:
                change_details.append({'old_value': getattr(instance, i),
                    'new_value': validated_data[i], 'field_name': i})
                setattr(instance, i, validated_data[i])

    if validated_data['is_enabled'] is not None and validated_data['is_enabled'] != instance.is_enabled:
        if validated_data['is_enabled']:
            model_access.enable_listing(user, instance)
        else:
            model_access.disable_listing(user, instance)

        instance.is_enabled = validated_data['is_enabled']

        if validated_data['approval_status'] == models.Listing.APPROVED:
            dispatcher.publish('listing_enabled_status_changed',
                               listing=instance,
                               profile=user,
                               is_enabled=validated_data['is_enabled'])

    if validated_data['is_508_compliant'] is not None and validated_data['is_508_compliant'] != instance.is_508_compliant:
        changeset = {'old_value': model_access.bool_to_string(instance.is_508_compliant),
                'new_value': model_access.bool_to_string(validated_data['is_508_compliant']), 'field_name': 'is_508_compliant'}
        change_details.append(changeset)
        instance.is_508_compliant = validated_data['is_508_compliant']

    if validated_data['is_private'] is not None and validated_data['is_private'] != instance.is_private:
        changeset = {'old_value': model_access.bool_to_string(instance.is_private),
                'new_value': model_access.bool_to_string(validated_data['is_private']), 'field_name': 'is_private'}
        change_details.append(changeset)
        instance.is_private = validated_data['is_private']

        if validated_data['approval_status'] == models.Listing.APPROVED:
            dispatcher.publish('listing_private_status_changed',
                               listing=instance,
                               profile=user,
                               is_private=validated_data['is_private'])

    if validated_data['is_featured'] is not None and validated_data['is_featured'] != instance.is_featured:
        if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
            raise errors.PermissionDenied('Only stewards can change is_featured setting of a listing')

        change_details.append({'old_value': model_access.bool_to_string(instance.is_featured),
                'new_value': model_access.bool_to_string(validated_data['is_featured']), 'field_name': 'is_featured'})
        instance.is_featured = validated_data['is_featured']
        instance.featured_date = datetime.datetime.now(pytz.utc) if validated_data['is_featured'] else None

    s = validated_data['approval_status']
    if s and s != instance.approval_status:  # Check to see if approval_status has changed
        old_approval_status = instance.approval_status
        if s == models.Listing.APPROVED and user.highest_role() != 'APPS_MALL_STEWARD':
            raise errors.PermissionDenied('Only an APPS_MALL_STEWARD can mark a listing as APPROVED')
        if s == models.Listing.APPROVED_ORG and user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
            raise errors.PermissionDenied('Only stewards can mark a listing as APPROVED_ORG')
        if s == models.Listing.PENDING:
            model_access.submit_listing(user, instance)
        if s == models.Listing.PENDING_DELETION:
            # pending deletion should be handled through ListingPendingDeletionViewSet
            # keeping this here for now for backwards compatibility
            model_access.pending_delete_listing(user, instance, 'Unknown reason')
        if s == models.Listing.APPROVED_ORG:
            model_access.approve_listing_by_org_steward(user, instance)
        if s == models.Listing.APPROVED:
            model_access.approve_listing(user, instance)
        if s == models.Listing.REJECTED:
            # TODO: need to get the rejection text from somewhere
            model_access.reject_listing(user, instance, 'TODO: rejection reason')

        dispatcher.publish('listing_approval_status_changed',
                           listing=instance,
                           profile=user,
                           old_approval_status=old_approval_status,
                           new_approval_status=instance.approval_status)

    if instance.listing_type != validated_data['listing_type']:
        if instance.listing_type:
            old_value = instance.listing_type.title
        else:
            old_value = None
        if validated_data['listing_type']:
            new_value = validated_data['listing_type'].title
        else:
            new_value = None
        change_details.append({'old_value': old_value,
                'new_value': new_value, 'field_name': 'listing_type'})
        instance.listing_type = validated_data['listing_type']

    image_keys = ['small_icon', 'large_icon', 'banner_icon', 'large_banner_icon']
    for image_key in image_keys:
        if validated_data[image_key]:
            old_value = model_access.image_to_string(getattr(instance, image_key), True, 'old_value({0!s})'.format(image_key))
            new_value = model_access.image_to_string(validated_data[image_key], False, 'new_value({0!s})'.format(image_key))

            if old_value != new_value:
                new_value_image = None

                old_image_id = None
                if old_value is not None:
                    old_image_id = getattr(instance, image_key).id
                if validated_data[image_key].get('id') == old_image_id:
                    new_value_image = getattr(instance, image_key)
                    new_value_image.security_marking = validated_data[image_key].get('security_marking')
                    new_value_image.save()
                else:
                    new_value_image = image_model_access.get_image_by_id(validated_data[image_key].get('id'))

                    if new_value_image is None:
                        raise errors.InvalidInput('Error while saving, can not find image by id')

                change_details.append({'old_value': old_value,
                        'new_value': new_value, 'field_name': image_key})

                if image_key == 'small_icon':
                    instance.small_icon = new_value_image
                elif image_key == 'large_icon':
                    instance.large_icon = new_value_image
                elif image_key == 'banner_icon':
                    instance.banner_icon = new_value_image
                elif image_key == 'large_banner_icon':
                    instance.large_banner_icon = new_value_image

    if 'contacts' in validated_data:
        old_contact_instances = instance.contacts.all()
        old_contacts = model_access.contacts_to_string(old_contact_instances, True)
        new_contacts = model_access.contacts_to_string(validated_data['contacts'])

        if old_contacts != new_contacts:
            change_details.append({'old_value': old_contacts,
                'new_value': new_contacts, 'field_name': 'contacts'})
            instance.contacts.clear()
            for contact in validated_data['contacts']:
                # TODO: Smarter Handling of Duplicates Contact Records
                # A contact with the same name and email should be the same contact
                # in the backend.
                # Person1(name='N1',email='*****@*****.**') and
                #    Person1' (name='N1',email='*****@*****.**',secure_phone = '414-444-444')
                # The two people above should be one contact
                # if approval_status: "IN_PROGRESS" then it should be using
                # contact model ids' since it is temporary contacts
                obj, created = models.Contact.objects.get_or_create(
                    name=contact['name'],
                    email=contact['email'],
                    secure_phone=contact['secure_phone'],
                    unsecure_phone=contact['unsecure_phone'],
                    organization=contact.get('organization', None),
                    contact_type=contact_type_model_access.get_contact_type_by_name(
                        contact['contact_type']['name'])
                )
                instance.contacts.add(obj)

    if 'categories' in validated_data:
        old_category_instances = instance.categories.all()
        old_categories = model_access.categories_to_string(old_category_instances, True)
        new_categories = model_access.categories_to_string(validated_data['categories'], True)

        if old_categories != new_categories:
            changeset = {'old_value': old_categories,
                'new_value': new_categories, 'field_name': 'categories'}
            change_details.append(changeset)
            instance.categories.clear()
            for category in validated_data['categories']:
                instance.categories.add(category)

            dispatcher.publish('listing_categories_changed',
                               listing=instance,
                               profile=user,
                               old_categories=old_category_instances,
                               new_categories=validated_data['categories'])

    if 'owners' in validated_data:
        old_owner_instances = instance.owners.all()
        old_owners = model_access.owners_to_string(old_owner_instances, True)
        new_owners = model_access.owners_to_string(validated_data['owners'], True)
        if old_owners != new_owners:
            change_details.append({'old_value': old_owners,
                'new_value': new_owners, 'field_name': 'owners'})
            instance.owners.clear()
            for owner in validated_data['owners']:
                instance.owners.add(owner)

    # tags will be automatically created if necessary
    if 'tags' in validated_data:
        old_tag_instances = instance.tags.all()
        old_tags = model_access.tags_to_string(old_tag_instances, True)
        new_tags = model_access.tags_to_string(validated_data['tags'])

        if old_tags != new_tags:
            changeset = {'old_value': old_tags,
                         'new_value': new_tags, 'field_name': 'tags'}
            change_details.append(changeset)
            instance.tags.clear()
            new_tags_instances = []
            for tag in validated_data['tags']:
                obj, created = models.Tag.objects.get_or_create(
                    name=tag['name'])
                instance.tags.add(obj)
                new_tags_instances.append(obj)

            dispatcher.publish('listing_tags_changed',
                               listing=instance,
                               profile=user,
                               old_tags=old_tag_instances,
                               new_tags=new_tags_instances)

    if 'intents' in validated_data:
        old_intent_instances = instance.intents.all()
        old_intents = model_access.intents_to_string(old_intent_instances, True)
        new_intents = model_access.intents_to_string(validated_data['intents'], True)
        if old_intents != new_intents:
            change_details.append({'old_value': old_intents,
                'new_value': new_intents, 'field_name': 'intents'})
            instance.intents.clear()
            for intent in validated_data['intents']:
                instance.intents.add(intent)

    # doc_urls will be automatically created
    if 'doc_urls' in validated_data:
        old_doc_url_instances = model_access.get_doc_urls_for_listing(instance)
        old_doc_urls = model_access.doc_urls_to_string(old_doc_url_instances, True)
        new_doc_urls = model_access.doc_urls_to_string(validated_data['doc_urls'])
        if old_doc_urls != new_doc_urls:
            change_details.append({
                'old_value': old_doc_urls,
                'new_value': new_doc_urls,
                'field_name': 'doc_urls'})

            new_doc_url_instances = []
            for d in validated_data['doc_urls']:
                obj, created = models.DocUrl.objects.get_or_create(
                    name=d['name'], url=d['url'], listing=instance)
                new_doc_url_instances.append(obj)
            for i in old_doc_url_instances:
                if i not in new_doc_url_instances:
                    logger.info('Deleting doc_url: {0!s}'.format(i.id), extra={'request': serializer_instance.context.get('request')})
                    i.delete()

    # screenshots will be automatically created
    if 'screenshots' in validated_data:
        old_screenshot_instances = model_access.get_screenshots_for_listing(instance)
        old_screenshots = model_access.screenshots_to_string(old_screenshot_instances, True)
        new_screenshots = model_access.screenshots_to_string(validated_data['screenshots'])
        if old_screenshots != new_screenshots:
            change_details.append({'old_value': old_screenshots,
                'new_value': new_screenshots, 'field_name': 'screenshots'})

        new_screenshot_instances = []

        for s in validated_data['screenshots']:
            new_small_image = image_model_access.get_image_by_id(s['small_image']['id'])
            new_small_image.security_marking = s['small_image']['security_marking']
            new_small_image.save()

            new_large_image = image_model_access.get_image_by_id(s['large_image']['id'])
            new_large_image.security_marking = s['large_image']['security_marking']
            new_large_image.save()

            obj, created = models.Screenshot.objects.get_or_create(
                order=s.get('order'),
                small_image=new_small_image,
                large_image=new_large_image,
                description=s.get('description'),
                listing=instance)

            new_screenshot_instances.append(obj)

        for i in old_screenshot_instances:
            if i not in new_screenshot_instances:
                logger.info('Deleting screenshot: {0!s}'.format(i.id), extra={'request': serializer_instance.context.get('request')})
                i.delete()

    if 'agency' in validated_data:
        if instance.agency != validated_data['agency']:
            change_details.append({'old_value': instance.agency.title,
                'new_value': validated_data['agency'].title, 'field_name': 'agency'})
            instance.agency = validated_data['agency']

    instance.save()

    # If the listing was modified add an entry showing changes
    if change_details:
        model_access.log_listing_modification(user, instance, change_details)

        new_change_details = []
        field_to_exclude = ['is_private', 'categories', 'tags']
        for change_detail in change_details:
            if change_detail['field_name'] not in field_to_exclude:
                new_change_details.append(change_detail)

        if new_change_details:
            dispatcher.publish('listing_changed',
                               listing=instance,
                               profile=user,
                               change_details=new_change_details)

    instance.edited_date = datetime.datetime.now(pytz.utc)
    return instance
Exemplo n.º 8
0
def create_listing(listing_builder_dict):
    """
    Create Listing Helper Function
    """
    listing_data = listing_builder_dict['listing']
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Icons
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    small_icon = models.Image.create_image(
        Image.open(TEST_IMG_PATH + listing_data['small_icon']['filename']),
        file_extension=listing_data['small_icon']['filename'].split('.')[-1],
        security_marking=listing_data['small_icon']['security_marking'],
        image_type=models.ImageType.objects.get(name='small_icon').name)

    large_icon = models.Image.create_image(
        Image.open(TEST_IMG_PATH + listing_data['large_icon']['filename']),
        file_extension=listing_data['large_icon']['filename'].split('.')[-1],
        security_marking=listing_data['large_icon']['security_marking'],
        image_type=models.ImageType.objects.get(name='large_icon').name)

    banner_icon = models.Image.create_image(
        Image.open(TEST_IMG_PATH + listing_data['banner_icon']['filename']),
        file_extension=listing_data['banner_icon']['filename'].split('.')[-1],
        security_marking=listing_data['banner_icon']['security_marking'],
        image_type=models.ImageType.objects.get(name='banner_icon').name)

    large_banner_icon = models.Image.create_image(
        Image.open(TEST_IMG_PATH +
                   listing_data['large_banner_icon']['filename']),
        file_extension=listing_data['large_banner_icon']['filename'].split(
            '.')[-1],
        security_marking=listing_data['large_banner_icon']['security_marking'],
        image_type=models.ImageType.objects.get(name='large_banner_icon').name)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Listing
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    listing = models.Listing(
        title=listing_data['title'],
        agency=models.Agency.objects.get(short_name=listing_data['agency']),
        listing_type=models.ListingType.objects.get(
            title=listing_data['listing_type']),
        description=listing_data['description'],
        launch_url=listing_data['launch_url'].format_map(
            {'DEMO_APP_ROOT': DEMO_APP_ROOT}),
        version_name=listing_data['version_name'],
        unique_name=listing_data['unique_name'],
        small_icon=small_icon,
        large_icon=large_icon,
        banner_icon=banner_icon,
        large_banner_icon=large_banner_icon,
        what_is_new=listing_data['what_is_new'],
        description_short=listing_data['description_short'],
        requirements=listing_data['requirements'],
        is_enabled=listing_data['is_enabled'],
        is_private=listing_data['is_private'],
        is_featured=listing_data['is_featured'],
        iframe_compatible=listing_data['iframe_compatible'],
        security_marking=listing_data['security_marking'])
    listing.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Contacts
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_contact in listing_data['contacts']:
        listing.contacts.add(models.Contact.objects.get(email=current_contact))

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Owners
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_owner in listing_data['owners']:
        listing.owners.add(
            models.Profile.objects.get(user__username=current_owner))

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Categories
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_category in listing_data['categories']:
        listing.categories.add(
            models.Category.objects.get(title=current_category))
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_tag in listing_data['tags']:
        current_tag_obj, created = models.Tag.objects.get_or_create(
            name=current_tag)
        listing.tags.add(current_tag_obj)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Screenshots
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_screenshot_entry in listing_data['screenshots']:
        small_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH +
                       current_screenshot_entry['small_image']['filename']),
            file_extension=current_screenshot_entry['small_image']
            ['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['small_image']
            ['security_marking'],
            image_type=models.ImageType.objects.get(
                name='small_screenshot').name)

        large_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH +
                       current_screenshot_entry['large_image']['filename']),
            file_extension=current_screenshot_entry['large_image']
            ['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['large_image']
            ['security_marking'],
            image_type=models.ImageType.objects.get(
                name='large_screenshot').name)

        screenshot = models.Screenshot(
            small_image=small_image,
            large_image=large_image,
            listing=listing,
            description=current_screenshot_entry['description'],
            order=current_screenshot_entry['order'])
        screenshot.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Document URLs
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_doc_url_entry in listing_data['doc_urls']:
        current_doc_url_obj = models.DocUrl(name=current_doc_url_entry['name'],
                                            url=current_doc_url_entry['url'],
                                            listing=listing)
        current_doc_url_obj.save()

    # listing_activity
    for listing_activity_entry in listing_builder_dict['listing_activity']:
        listing_activity_action = listing_activity_entry['action']
        listing_activity_author = models.Profile.objects.get(
            user__username=listing_activity_entry['author'])

        if listing_activity_action == 'CREATED':
            listing_model_access.create_listing(listing_activity_author,
                                                listing)
        elif listing_activity_action == 'SUBMITTED':
            listing_model_access.submit_listing(listing_activity_author,
                                                listing)
        elif listing_activity_action == 'APPROVED_ORG':
            listing_model_access.approve_listing_by_org_steward(
                listing_activity_author, listing)
        elif listing_activity_action == 'APPROVED':
            listing_model_access.approve_listing(listing_activity_author,
                                                 listing)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Reviews
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    # listing_review_batch
    create_listing_review_batch(listing,
                                listing_builder_dict['listing_review_batch'])
    return listing
Exemplo n.º 9
0
    def update(self, instance, validated_data):
        # logger.debug('inside ListingSerializer.update', extra={'request':self.context.get('request')})
        user = generic_model_access.get_profile(
            self.context['request'].user.username)

        if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
            if user not in instance.owners.all():
                raise errors.PermissionDenied(
                    'User ({0!s}) is not an owner of this listing'.format(
                        user.username))

        if instance.is_deleted:
            raise errors.PermissionDenied(
                'Cannot update a previously deleted listing')

        change_details = []

        simple_fields = [
            'title', 'description', 'description_short', 'launch_url',
            'version_name', 'requirements', 'unique_name', 'what_is_new',
            'security_marking'
        ]

        for i in simple_fields:
            if getattr(instance, i) != validated_data[i]:
                change_details.append({
                    'old_value': getattr(instance, i),
                    'new_value': validated_data[i],
                    'field_name': i
                })
                setattr(instance, i, validated_data[i])

        if validated_data['is_enabled'] != instance.is_enabled:
            if validated_data['is_enabled']:
                model_access.enable_listing(user, instance)
            else:
                model_access.disable_listing(user, instance)

            instance.is_enabled = validated_data['is_enabled']

        if validated_data['is_private'] != instance.is_private:
            change_details.append({
                'old_value':
                model_access.bool_to_string(instance.is_private),
                'new_value':
                model_access.bool_to_string(validated_data['is_private']),
                'field_name':
                'is_private'
            })
            instance.is_private = validated_data['is_private']

        if validated_data['is_featured'] != instance.is_featured:
            if user.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied(
                    'Only stewards can change is_featured setting of a listing'
                )
            change_details.append({
                'old_value':
                model_access.bool_to_string(instance.is_featured),
                'new_value':
                model_access.bool_to_string(validated_data['is_featured']),
                'field_name':
                'is_featured'
            })
            instance.is_featured = validated_data['is_featured']

        s = validated_data['approval_status']
        if s and s != instance.approval_status:
            if s == models.Listing.APPROVED and user.highest_role(
            ) != 'APPS_MALL_STEWARD':
                raise errors.PermissionDenied(
                    'Only an APPS_MALL_STEWARD can mark a listing as APPROVED')
            if s == models.Listing.APPROVED_ORG and user.highest_role(
            ) not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']:
                raise errors.PermissionDenied(
                    'Only stewards can mark a listing as APPROVED_ORG')
            if s == models.Listing.PENDING:
                model_access.submit_listing(user, instance)
            if s == models.Listing.APPROVED_ORG:
                model_access.approve_listing_by_org_steward(user, instance)
            if s == models.Listing.APPROVED:
                model_access.approve_listing(user, instance)
            if s == models.Listing.REJECTED:
                # TODO: need to get the rejection text from somewhere
                model_access.reject_listing(user, instance,
                                            'TODO: rejection reason')

        if instance.listing_type != validated_data['listing_type']:
            if instance.listing_type:
                old_value = instance.listing_type.title
            else:
                old_value = None
            if validated_data['listing_type']:
                new_value = validated_data['listing_type'].title
            else:
                new_value = None
            change_details.append({
                'old_value': old_value,
                'new_value': new_value,
                'field_name': 'listing_type'
            })
            instance.listing_type = validated_data['listing_type']

        image_keys = [
            'small_icon', 'large_icon', 'banner_icon', 'large_banner_icon'
        ]
        for image_key in image_keys:
            if validated_data[image_key]:
                old_value = model_access.image_to_string(
                    getattr(instance, image_key), True,
                    'old_value({0!s})'.format(image_key))
                new_value = model_access.image_to_string(
                    validated_data[image_key], False,
                    'new_value({0!s})'.format(image_key))

                if old_value != new_value:
                    new_value_image = None

                    old_image_id = None
                    if old_value is not None:
                        old_image_id = getattr(instance, image_key).id
                    if validated_data[image_key].get('id') == old_image_id:
                        new_value_image = getattr(instance, image_key)
                        new_value_image.security_marking = validated_data[
                            image_key].get('security_marking')
                        new_value_image.save()
                    else:
                        new_value_image = image_model_access.get_image_by_id(
                            validated_data[image_key].get('id'))

                        if new_value_image is None:
                            raise errors.InvalidInput(
                                'Error while saving, can not find image by id')

                    change_details.append({
                        'old_value': old_value,
                        'new_value': new_value,
                        'field_name': image_key
                    })

                    if image_key == 'small_icon':
                        instance.small_icon = new_value_image
                    elif image_key == 'large_icon':
                        instance.large_icon = new_value_image
                    elif image_key == 'banner_icon':
                        instance.banner_icon = new_value_image
                    elif image_key == 'large_banner_icon':
                        instance.large_banner_icon = new_value_image

        if 'contacts' in validated_data:
            old_contact_instances = instance.contacts.all()
            old_contacts = model_access.contacts_to_string(
                old_contact_instances, True)
            new_contacts = model_access.contacts_to_string(
                validated_data['contacts'])

            if old_contacts != new_contacts:
                change_details.append({
                    'old_value': old_contacts,
                    'new_value': new_contacts,
                    'field_name': 'contacts'
                })
                instance.contacts.clear()
                for contact in validated_data['contacts']:
                    # TODO: Smarter Handling of Duplicates Contact Records
                    # A contact with the same name and email should be the same contact
                    # in the backend.
                    # Person1(name='N1',email='*****@*****.**') and
                    #    Person1' (name='N1',email='*****@*****.**',secure_phone = '414-444-444')
                    # The two people above should be one contact
                    # if approval_status: "IN_PROGRESS" then it should be using
                    # contact model ids' since it is temporary contacts
                    obj, created = models.Contact.objects.get_or_create(
                        name=contact['name'],
                        email=contact['email'],
                        secure_phone=contact['secure_phone'],
                        unsecure_phone=contact['unsecure_phone'],
                        organization=contact.get('organization', None),
                        contact_type=contact_type_model_access.
                        get_contact_type_by_name(
                            contact['contact_type']['name']))
                    instance.contacts.add(obj)

        if 'categories' in validated_data:
            old_category_instances = instance.categories.all()
            old_categories = model_access.categories_to_string(
                old_category_instances, True)
            new_categories = model_access.categories_to_string(
                validated_data['categories'], True)
            if old_categories != new_categories:
                change_details.append({
                    'old_value': old_categories,
                    'new_value': new_categories,
                    'field_name': 'categories'
                })
                instance.categories.clear()
                for category in validated_data['categories']:
                    instance.categories.add(category)

        if 'owners' in validated_data:
            old_owner_instances = instance.owners.all()
            old_owners = model_access.owners_to_string(old_owner_instances,
                                                       True)
            new_owners = model_access.owners_to_string(
                validated_data['owners'], True)
            if old_owners != new_owners:
                change_details.append({
                    'old_value': old_owners,
                    'new_value': new_owners,
                    'field_name': 'owners'
                })
                instance.owners.clear()
                for owner in validated_data['owners']:
                    instance.owners.add(owner)

        # tags will be automatically created if necessary
        if 'tags' in validated_data:
            old_tag_instances = instance.tags.all()
            old_tags = model_access.tags_to_string(old_tag_instances, True)
            new_tags = model_access.tags_to_string(validated_data['tags'])
            if old_tags != new_tags:
                change_details.append({
                    'old_value': old_tags,
                    'new_value': new_tags,
                    'field_name': 'tags'
                })
                instance.tags.clear()
                for tag in validated_data['tags']:
                    obj, created = models.Tag.objects.get_or_create(
                        name=tag['name'])
                    instance.tags.add(obj)

        if 'intents' in validated_data:
            old_intent_instances = instance.intents.all()
            old_intents = model_access.intents_to_string(
                old_intent_instances, True)
            new_intents = model_access.intents_to_string(
                validated_data['intents'], True)
            if old_intents != new_intents:
                change_details.append({
                    'old_value': old_intents,
                    'new_value': new_intents,
                    'field_name': 'intents'
                })
                instance.intents.clear()
                for intent in validated_data['intents']:
                    instance.intents.add(intent)

        # doc_urls will be automatically created
        if 'doc_urls' in validated_data:
            old_doc_url_instances = model_access.get_doc_urls_for_listing(
                instance)
            old_doc_urls = model_access.doc_urls_to_string(
                old_doc_url_instances, True)
            new_doc_urls = model_access.doc_urls_to_string(
                validated_data['doc_urls'])
            if old_doc_urls != new_doc_urls:
                change_details.append({
                    'old_value': old_doc_urls,
                    'new_value': new_doc_urls,
                    'field_name': 'doc_urls'
                })

                new_doc_url_instances = []
                for d in validated_data['doc_urls']:
                    obj, created = models.DocUrl.objects.get_or_create(
                        name=d['name'], url=d['url'], listing=instance)
                    new_doc_url_instances.append(obj)
                for i in old_doc_url_instances:
                    if i not in new_doc_url_instances:
                        logger.info(
                            'Deleting doc_url: {0!s}'.format(i.id),
                            extra={'request': self.context.get('request')})
                        i.delete()

        # screenshots will be automatically created
        if 'screenshots' in validated_data:
            old_screenshot_instances = model_access.get_screenshots_for_listing(
                instance)
            old_screenshots = model_access.screenshots_to_string(
                old_screenshot_instances, True)
            new_screenshots = model_access.screenshots_to_string(
                validated_data['screenshots'])
            if old_screenshots != new_screenshots:
                change_details.append({
                    'old_value': old_screenshots,
                    'new_value': new_screenshots,
                    'field_name': 'screenshots'
                })

            new_screenshot_instances = []

            for s in validated_data['screenshots']:

                new_small_image = image_model_access.get_image_by_id(
                    s['small_image']['id'])
                new_small_image.security_marking = s['small_image'][
                    'security_marking']
                new_small_image.save()

                new_large_image = image_model_access.get_image_by_id(
                    s['large_image']['id'])
                new_large_image.security_marking = s['large_image'][
                    'security_marking']
                new_large_image.save()

                obj, created = models.Screenshot.objects.get_or_create(
                    small_image=new_small_image,
                    large_image=new_large_image,
                    listing=instance)

                new_screenshot_instances.append(obj)

            for i in old_screenshot_instances:
                if i not in new_screenshot_instances:
                    logger.info('Deleting screenshot: {0!s}'.format(i.id),
                                extra={'request': self.context.get('request')})
                    i.delete()

        if 'agency' in validated_data:
            if instance.agency != validated_data['agency']:
                change_details.append({
                    'old_value': instance.agency.title,
                    'new_value': validated_data['agency'].title,
                    'field_name': 'agency'
                })
                instance.agency = validated_data['agency']

        instance.save()

        # If the listing was modified add an entry showing changes
        if change_details:
            model_access.log_listing_modification(user, instance,
                                                  change_details)

        instance.edited_date = datetime.datetime.now(pytz.utc)
        return instance
def create_listing(listing_builder_dict, object_cache):
    """
    Create Listing Helper Function

    10-01-2017 - Total Database Calls: 11842
    10-02-2017 - Total Database Calls: 7737
    """
    listing_data = listing_builder_dict['listing']

    listing = models.Listing(
        title=listing_data['title'],
        agency=object_cache['Agency.{}'.format(listing_data['agency'])],
        listing_type=object_cache['ListingType.{}'.format(listing_data['listing_type'])],
        description=listing_data['description'],
        launch_url=listing_data['launch_url'].format_map({'DEMO_APP_ROOT': DEMO_APP_ROOT}),
        version_name=listing_data['version_name'],
        unique_name=listing_data['unique_name'],
        small_icon=object_cache['Listing[{}].small_icon'.format(listing_data['title'])],
        large_icon=object_cache['Listing[{}].large_icon'.format(listing_data['title'])],
        banner_icon=object_cache['Listing[{}].banner_icon'.format(listing_data['title'])],
        large_banner_icon=object_cache['Listing[{}].large_banner_icon'.format(listing_data['title'])],
        what_is_new=listing_data['what_is_new'],
        description_short=listing_data['description_short'],
        usage_requirements=listing_data['usage_requirements'],
        system_requirements=listing_data['system_requirements'],
        is_enabled=listing_data['is_enabled'],
        is_private=listing_data['is_private'],
        is_508_compliant=listing_data.get('is_508_compliant', False),
        is_featured=listing_data['is_featured'],
        iframe_compatible=listing_data['iframe_compatible'],
        security_marking=listing_data['security_marking']
    )
    listing.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Contacts
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_contact in listing_data['contacts']:
        listing.contacts.add(object_cache['Contact.{}'.format(current_contact)])

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Owners
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_owner in listing_data['owners']:
        listing.owners.add(object_cache['Profile.{}'.format(current_owner)])

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Categories
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_category in listing_data['categories']:
        listing.categories.add(models.Category.objects.get(title=current_category))
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_tag in listing_data['tags']:
        if object_cache.get('Tag.{}'.format(current_tag)):
            current_tag_obj = object_cache['Tag.{}'.format(current_tag)]
        else:
            current_tag_obj, created = models.Tag.objects.get_or_create(name=current_tag)
        listing.tags.add(current_tag_obj)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Screenshots
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_screenshot_entry in listing_data['screenshots']:
        small_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH + current_screenshot_entry['small_image']['filename']),
            file_extension=current_screenshot_entry['small_image']['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['small_image']['security_marking'],
            image_type=object_cache['ImageType.small_screenshot'].name)

        large_image = models.Image.create_image(
            Image.open(TEST_IMG_PATH + current_screenshot_entry['large_image']['filename']),
            file_extension=current_screenshot_entry['large_image']['filename'].split('.')[-1],
            security_marking=current_screenshot_entry['large_image']['security_marking'],
            image_type=object_cache['ImageType.large_screenshot'].name)

        screenshot = models.Screenshot(small_image=small_image,
                                       large_image=large_image,
                                       listing=listing,
                                       description=current_screenshot_entry['description'],
                                       order=current_screenshot_entry['order'])
        screenshot.save()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #                           Document URLs
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    for current_doc_url_entry in listing_data['doc_urls']:
        current_doc_url_obj = models.DocUrl(name=current_doc_url_entry['name'], url=current_doc_url_entry['url'], listing=listing)
        current_doc_url_obj.save()

    # listing_activity
    for listing_activity_entry in listing_builder_dict['listing_activity']:
        listing_activity_action = listing_activity_entry['action']
        listing_activity_author = object_cache['Profile.{}'.format(listing_activity_entry['author'])]

        if listing_activity_action == 'CREATED':
            listing_model_access.create_listing(listing_activity_author, listing)
        elif listing_activity_action == 'SUBMITTED':
            listing_model_access.submit_listing(listing_activity_author, listing)
        elif listing_activity_action == 'APPROVED_ORG':
            listing_model_access.approve_listing_by_org_steward(listing_activity_author, listing)
        elif listing_activity_action == 'APPROVED':
            listing_model_access.approve_listing(listing_activity_author, listing)

    return listing