def handle(self, *args, **options):
     """ handle """
     site_codes = ContentRelease.objects.values_list('site_code',
                                                     flat=True).distinct()
     for site_code in site_codes:
         publisher_api = PublisherAPI(api_type='django')
         publisher_api.get_live_content_release(site_code)
class WagtailSnapshotPublisherDynamicContentTests(TestCase):
    """ WagtailSnapshotPublisherDynamicContentTests """
    @classmethod
    def setUpTestData(cls):
        """ setUpTestData """
        call_command('load_test_data_fixtures', '--no-output')

    def setUp(self):
        """ setUp """
        User = get_user_model()
        username = os.environ.get('CMS_SUPERUSER_USERNAME', 'superadmin')
        self.user = User.objects.get(username=username)
        self.page1 = TestPage.objects.get(id=3)
        self.page2 = TestPage.objects.get(id=4)
        self.page3 = TestPage.objects.get(id=5)
        self.content_release1 = WSSPContentRelease.objects.get(id=1)
        self.content_release2 = WSSPContentRelease.objects.get(id=2)
        self.content_release3 = WSSPContentRelease.objects.get(id=3)
        self.publisher_api = PublisherAPI(api_type='django')
        self.factory = RequestFactory()
        self.client = Client()
        self.client.force_login(self.user)
        self.page1.content_release = self.content_release1
        self.page1.save_revision(self.user)
        self.page2.content_release = self.content_release1
        self.page2.save_revision(self.user)
        self.page1.publish_to_release(self.page1.content_release,
                                      self.content_release1)
        self.publisher_api.set_live_content_release(
            self.content_release1.site_code, self.content_release1.uuid)
        self.publisher_api.get_live_content_release(
            self.content_release1.site_code)
        self.content_release1 = WSSPContentRelease.objects.get(id=1)
    def clean(self):
        """ clean """
        super().clean()

        # get live release
        if self.publish_to_live_release:
            self.publish_to_live_release = False
            publisher_api = PublisherAPI()
            response = publisher_api.get_live_content_release(self.site_code)
            if response['status'] == 'error':
                raise ValidationError({'site_code': response['error_msg']})

            self.content_release = WSSPContentRelease.objects.get(id=response['content'].id)
def get_releases(request, site_code):
    """ get_releases """
    # time_now = timezone.now()
    # logger.info('Getting releases for site code %s after %s', site_code, time_now.strftime(DATETIME_FORMAT))
    # response = list_live_and_upcoming_content_releases(site_code, 1, time_now) # Status FROZEN = 1

    # if response['status'] == 'success':
    #     releases = list(response['content'].values('uuid', 'title', 'publish_datetime', 'is_live'))
    #     logger.info('Releases are %s', releases)
    # else:
    #     return response

    live_release = None
    stage_release = None
    publisher_api = PublisherAPI()

    response = publisher_api.get_live_content_release(site_code)
    if response['status'] == 'success':
        live_release = {
            'uuid': response['content'].uuid,
            'title': response['content'].title,
            'publish_datetime': response['content'].publish_datetime,
        }

    response = publisher_api.get_stage_content_release(site_code)
    if response['status'] == 'success':
        stage_release = {
            'uuid': response['content'].uuid,
            'title': response['content'].title,
            'publish_datetime': response['content'].publish_datetime,
        }

    return JsonResponse({
        'stage': stage_release,
        'live': live_release,
    }, safe=False)
    def test_set_live(self):
        """ unittest when content release go live """
        publisher_api = PublisherAPI(api_type='django')
        response = publisher_api.add_content_release('site1', 'title1', '0.1')
        content_release = response['content']
        document_json = json.dumps({'page_title': 'Test'})
        response = publisher_api.publish_document_to_content_release(
            'site1',
            content_release.uuid,
            document_json,
            'key1',
        )
        # set stage
        publisher_api.set_stage_content_release('site1', content_release.uuid)
        publisher_api.get_stage_content_release('site1')
        # set live
        publisher_api.set_live_content_release('site1', content_release.uuid)
        publisher_api.get_live_content_release('site1')

        # set live, not base release
        response = publisher_api.add_content_release('site1', 'title2', '0.2')
        content_release2 = response['content']
        document_json2 = json.dumps({'page_title': 'Test2'})
        response = publisher_api.publish_document_to_content_release(
            'site1',
            content_release2.uuid,
            document_json2,
            'key1',
        )
        document_json3 = json.dumps({'page_title': 'Test3'})
        response = publisher_api.publish_document_to_content_release(
            'site1',
            content_release2.uuid,
            document_json3,
            'key2',
        )
        publisher_api.set_stage_content_release('site1', content_release2.uuid)
        publisher_api.get_stage_content_release('site1')
        publisher_api.set_live_content_release('site1', content_release2.uuid)
        publisher_api.get_live_content_release('site1')
        content_release2 = ContentRelease.objects.get(
            uuid=content_release2.uuid)
        self.assertEqual(content_release2.release_documents.count(), 2)
        release_document1 = content_release2.release_documents.get(
            document_key='key1', )
        release_document2 = content_release2.release_documents.get(
            document_key='key2', )
        self.assertEqual(json.loads(release_document1.document_json),
                         {'page_title': 'Test2'})
        self.assertEqual(json.loads(release_document2.document_json),
                         {'page_title': 'Test3'})

        # copy base release documents
        response = publisher_api.add_content_release('site1', 'title3', '0.3',
                                                     None,
                                                     content_release2.uuid)
        content_release3 = response['content']
        document_json4 = json.dumps({'page_title': 'Test4'})
        response = publisher_api.publish_document_to_content_release(
            'site1',
            content_release3.uuid,
            document_json4,
            'key2',
        )
        publisher_api.set_stage_content_release('site1', content_release3.uuid)
        publisher_api.set_live_content_release('site1', content_release3.uuid)

        # publish to content release and get the last one and check in the copy works
        response = publisher_api.add_content_release('site1', 'title4', '0.4',
                                                     None, None, True)
        content_release4 = response['content']
        document_json5 = json.dumps({'page_title': 'Test5'})
        response = publisher_api.publish_document_to_content_release(
            'site1',
            content_release4.uuid,
            document_json5,
            'key1',
        )
        publisher_api.set_stage_content_release('site1', content_release4.uuid)
        publisher_api.get_stage_content_release('site1')
        publisher_api.set_live_content_release('site1', content_release4.uuid)
        publisher_api.get_live_content_release('site1')
        content_release3 = ContentRelease.objects.get(
            uuid=content_release3.uuid)
        self.assertEqual(content_release3.release_documents.count(), 2)
        release_document1 = content_release3.release_documents.get(
            document_key='key1', )
        release_document2 = content_release3.release_documents.get(
            document_key='key2', )
        self.assertEqual(json.loads(release_document1.document_json),
                         {'page_title': 'Test2'})
        self.assertEqual(json.loads(release_document2.document_json),
                         {'page_title': 'Test4'})

        content_release4 = ContentRelease.objects.get(
            uuid=content_release4.uuid)
        self.assertEqual(content_release4.release_documents.count(), 2)
        release_document1 = content_release4.release_documents.get(
            document_key='key1', )
        release_document2 = content_release4.release_documents.get(
            document_key='key2', )
        self.assertEqual(json.loads(release_document1.document_json),
                         {'page_title': 'Test5'})
        self.assertEqual(json.loads(release_document2.document_json),
                         {'page_title': 'Test4'})

        self.assertEqual(ContentRelease.objects.archived('site1').count(), 3)
def get_content_details(site_code, release_uuid, content_type, content_key):
    """ get_content_details """
    publisher_api = PublisherAPI()

    content_release = None

    try:
        if release_uuid:
            # get ContentRelease
            content_release = WSSPContentRelease.objects.get(
                site_code=site_code,
                uuid=release_uuid,
            )
        else:
            # get live ContentRelease
            response = publisher_api.get_live_content_release(site_code)
            if response['status'] == 'error':
                return response
            else:
                release = response['content']
                content_release = WSSPContentRelease.objects.get(id=release.id)
                release_uuid = content_release.uuid
    except WSSPContentRelease.DoesNotExist:
        pass

    # Fetch document from the content release.
    response = publisher_api.get_document_from_content_release(
        site_code,
        release_uuid,
        content_key,
        content_type,
    )

    base_content_release = None
    if response['status'] == 'error' and response['error_code'] == 'release_document_does_not_exist':
        # Release doc not found, try in the base release for preview releases.
        if content_release.status == 0:
            if content_release.use_current_live_as_base_release:
                response = publisher_api.get_live_content_release(site_code)
                if response['status'] == 'success':
                    release = response['content']
                    base_content_release = WSSPContentRelease.objects.get(id=release.id)
            else:
                base_content_release = content_release.base_release

    if base_content_release != None:
        # Fetch document from the base content release if available (should only happen for preview releases).
        response = publisher_api.get_document_from_content_release(
            site_code,
            base_content_release.uuid,
            content_key,
            content_type,
        )

    if response['status'] == 'success':
        data = json.loads(response['content'].document_json)

        response_extra = publisher_api.get_document_extra_from_content_release(
            site_code,
            release_uuid,
            content_key,
            content_type,
        )
        if response_extra['status'] == 'success':
            try:
                dynamic_element_keys = json.loads(response_extra['content'].get(key='dynamic_element_keys').content)
                data, updated = document_load_dynamic_elements(content_release, data, dynamic_element_keys)
            except:
                pass
    else:
        return response

    return data
def compare_release(request, release_id, release_id_to_compare_to=None, set_live_button=False, set_stage_button=False):
    """ compare_release """
    publisher_api = PublisherAPI()
    release = WSSPContentRelease.objects.get(id=release_id)

    publish_release_form = PublishReleaseForm()
    frozen_releases_form = FrozenReleasesForm(release.site_code)

    if request.method == 'POST' and release_id_to_compare_to is None:
        frozen_releases_form = FrozenReleasesForm(release.site_code, request.POST)
        if frozen_releases_form.is_valid():
            # redirect to compare with this release
            release_id_to_compare_to = frozen_releases_form.cleaned_data['releases']
            return release_detail(request, release_id, set_live_button, set_stage_button, release_id_to_compare_to.id)

    if request.method == 'POST' and release_id_to_compare_to is None:
        publish_release_form = PublishReleaseForm(request.POST)
        if publish_release_form.is_valid():
            publish_datetime = publish_release_form.cleaned_data['publish_datetime']

            if publish_datetime:
                publish_datetime = publish_datetime.strftime('%Y-%m-%dT%H:%M:%S%z')

            return release_set_live(request, release_id, publish_datetime)


    if frozen_releases_form.fields['releases'].queryset is None or \
            not frozen_releases_form.fields['releases'].queryset.exists():
        frozen_releases_form = None

    # get current live release
    compare_with_live = True
    response = publisher_api.get_live_content_release(release.site_code)
    if response['status'] == 'error':
        return {
            'release': release,
            'error_msg': response['error_msg'],
            'publish_release_form': publish_release_form,
        }

    release_to_compare_to = response['content']
    if release_id_to_compare_to and release_to_compare_to.id != release_id_to_compare_to:
        compare_with_live = False
        release_to_compare_to = WSSPContentRelease.objects.get(id=release_id_to_compare_to)
    else:
        release_to_compare_to = WSSPContentRelease.objects.get(id=release_to_compare_to.id)

    response = publisher_api.compare_content_releases(release.site_code, release.uuid,
                                                      release_to_compare_to.uuid)
    comparison = response['content']

    added_pages = []
    removed_pages = []
    changed_pages = []
    extra_contents = []
    for item  in comparison:
        if item['content_type'] == 'page':
            try:
                if item['diff'] == 'Added':
                    try:
                        page_revision = PageRevision.objects.get(id=item['parameters']['revision_id'])
                    except:
                        logger.info('Page has been deleted from Wagtail: %s' % (item))
                        item['deleted_in_wagtail'] = True
                    item['page_revision'] = page_revision
                    item['title'] = json.loads(page_revision.content_json)['title']
                    added_pages.append(item)
                if item['diff'] == 'Removed':
                    try:
                        page_revision = PageRevision.objects.get(id=item['parameters']['revision_id'])
                    except:
                        logger.info('Page has been deleted from Wagtail: %s' % (item))
                        item['deleted_in_wagtail'] = True
                    item['title'] = json.loads(page_revision.content_json)['title']
                    item['page_revision'] = page_revision
                    removed_pages.append(item)
                if item['diff'] == 'Changed' and 'revision_id' in item['parameters']['release_from']:
                    try:
                        page_revision = PageRevision.objects.get(id=item['parameters']['release_from']['revision_id'])
                    except:
                        logger.info('Page has been deleted from Wagtail: %s' % (item))
                        item['deleted_in_wagtail'] = True
                    item['page_revision_from'] = page_revision
                    item['page_revision_compare_to'] = PageRevision.objects.get(
                        id=item['parameters']['release_compare_to']['revision_id'])
                    item['title'] = json.loads(page_revision.content_json)['title']
                    changed_pages.append(item)
            except Exception as e:
                logger.info('Error while comparing item: %s' % (item))
        else:
            extra_contents.append(item)

    return {
        'comparison': comparison,
        'added_pages': added_pages,
        'changed_pages': changed_pages,
        'removed_pages': removed_pages,
        'extra_contents': json.dumps(extra_contents, indent=4) if extra_contents and \
            request.user.has_perm('wagtailadmin.access_dev') else None,
        'release': release,
        'release_to_compare_to': release_to_compare_to,
        'publish_release_form': publish_release_form,
        'frozen_releases_form': frozen_releases_form,
        'compare_with_live': compare_with_live,
    }