コード例 #1
0
ファイル: test_tasks.py プロジェクト: w0lramD/kuma
def test_publish_multiple(get_s3_bucket_mock, root_doc, redirect_doc,
                          redirect_to_home, trans_doc):
    """
    Test the publish task for multiple documents of various kinds, including
    standard documents and redirects.
    """
    trans_doc.delete()
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish(
        [trans_doc.pk, root_doc.pk, redirect_doc.pk, redirect_to_home.pk],
        log=log_mock,
        completion_message="Done!",
    )
    s3_bucket_mock.put_object.assert_has_calls([
        mock.call(
            ACL="public-read",
            Key=get_s3_key(root_doc),
            Body=json.dumps(document_api_data(root_doc)),
            ContentType="application/json",
            ContentLanguage=root_doc.locale,
        ),
        mock.call(
            ACL="public-read",
            Key=get_s3_key(redirect_doc),
            WebsiteRedirectLocation=get_s3_key(
                root_doc,
                prefix_with_forward_slash=True,
                suffix_file_extension=False,
            ),
            ContentType="application/json",
            ContentLanguage=redirect_doc.locale,
            Body=json.dumps(
                document_api_data(
                    redirect_url=get_content_based_redirect(redirect_doc)[0])),
        ),
        mock.call(
            ACL="public-read",
            Key=get_s3_key(redirect_to_home),
            Body=json.dumps(document_api_data(redirect_url="/en-US/")),
            ContentType="application/json",
            ContentLanguage=redirect_to_home.locale,
        ),
    ])
    log_mock.error.assert_called_once_with(
        "Document with pk={} does not exist".format(trans_doc.pk))
    log_mock.info.assert_has_calls([
        mock.call("Published S3 Object #1"),
        mock.call("Published S3 Object #2"),
        mock.call("Published S3 Object #3"),
        mock.call("Done!"),
    ])
コード例 #2
0
ファイル: test_views.py プロジェクト: mozilla/kuma
def test_doc_api_for_redirect_to_non_doc(client, api_settings, redirect_to_home,
                                         redirect_to_macros, case):
    """
    Test the document API when we're requesting data for a document that
    redirects to a non-document page (either the home page or another).
    """
    if case == 'redirect-to-home':
        doc = redirect_to_home
        expected_redirect_url = '/en-US/'
    else:
        doc = redirect_to_macros
        expected_redirect_url = absolutify('/en-US/dashboards/macros',
                                           for_wiki_site=True)
    url = reverse('api.v1.doc', args=[doc.locale, doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData'] is None
    assert data['redirectURL'] == expected_redirect_url

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(redirect_url=expected_redirect_url)
コード例 #3
0
def test_doc_api_for_redirect_to_non_doc(client, redirect_to_home,
                                         redirect_to_macros, case):
    """
    Test the document API when we're requesting data for a document that
    redirects to a non-document page (either the home page or another).
    """
    if case == 'redirect-to-home':
        doc = redirect_to_home
        expected_redirect_url = '/en-US/'
    else:
        doc = redirect_to_macros
        expected_redirect_url = absolutify('/en-US/dashboards/macros',
                                           for_wiki_site=True)
    url = reverse('api.v1.doc', args=[doc.locale, doc.slug])
    response = client.get(url)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData'] is None
    assert data['redirectURL'] == expected_redirect_url

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(redirect_url=expected_redirect_url)
コード例 #4
0
def test_publish_multiple(get_s3_bucket_mock, root_doc, redirect_doc,
                          redirect_to_home, trans_doc):
    """
    Test the publish task for multiple documents of various kinds, including
    standard documents and redirects.
    """
    trans_doc.delete()
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([trans_doc.pk, root_doc.pk, redirect_doc.pk, redirect_to_home.pk],
            log=log_mock, completion_message='Done!')
    s3_bucket_mock.put_object.assert_has_calls([
        mock.call(
            ACL='public-read',
            Key=get_s3_key(root_doc),
            Body=json.dumps(
                document_api_data(root_doc, ensure_contributors=True)),
            ContentType='application/json',
            ContentLanguage=root_doc.locale
        ),
        mock.call(
            ACL='public-read',
            Key=get_s3_key(redirect_doc),
            WebsiteRedirectLocation=get_s3_key(root_doc, for_redirect=True),
            ContentType='application/json',
            ContentLanguage=redirect_doc.locale
        ),
        mock.call(
            ACL='public-read',
            Key=get_s3_key(redirect_to_home),
            Body=json.dumps(document_api_data(redirect_url='/en-US/')),
            ContentType='application/json',
            ContentLanguage=redirect_to_home.locale
        ),
    ])
    log_mock.error.assert_called_once_with(
        'Document with pk={} does not exist'.format(trans_doc.pk))
    log_mock.info.assert_has_calls([
        mock.call('Published S3 Object #1'),
        mock.call('Published S3 Object #2'),
        mock.call('Published S3 Object #3'),
        mock.call('Done!'),
    ])
コード例 #5
0
ファイル: test_views.py プロジェクト: itai421/kuma
def test_doc_api_for_redirect_to_doc(client, api_settings, root_doc,
                                     redirect_doc, cleared_cacheback_cache,
                                     ensure_contributors):
    """
    Test the document API when we're requesting data for a document that
    redirects to another document.
    """
    if ensure_contributors:
        # Pre-populate the cache for the call to document_api_data()
        # made within the view that serves the "api.v1.doc" endpoint.
        DocumentContributorsJob().refresh(root_doc.pk)

    url = reverse('api.v1.doc', args=[redirect_doc.locale, redirect_doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST, follow=True)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData']
    assert data['redirectURL'] is None
    doc_data = data['documentData']
    assert doc_data['locale'] == root_doc.locale
    assert doc_data['slug'] == root_doc.slug
    assert doc_data['id'] == root_doc.id
    assert doc_data['title'] == root_doc.title
    assert doc_data['language'] == root_doc.language
    assert doc_data['hrefLang'] == 'en'
    assert doc_data['absoluteURL'] == root_doc.get_absolute_url()
    assert doc_data['editURL'] == absolutify(root_doc.get_edit_url(),
                                             for_wiki_site=True)
    assert doc_data['translateURL'] == absolutify(reverse(
        'wiki.select_locale',
        args=(root_doc.slug, ),
        locale=root_doc.locale,
    ),
                                                  for_wiki_site=True)
    assert doc_data['bodyHTML'] == root_doc.get_body_html()
    assert doc_data['quickLinksHTML'] == root_doc.get_quick_links_html()
    assert doc_data['tocHTML'] == root_doc.get_toc_html()
    assert doc_data['translations'] == []
    assert doc_data['contributors'] == (['wiki_user']
                                        if ensure_contributors else [])
    assert doc_data['lastModified'] == '2017-04-14T12:15:00'
    assert doc_data['lastModifiedBy'] == 'wiki_user'

    # Clear the cache for a clean slate when calling document_api_data().
    DocumentContributorsJob().delete(root_doc.pk)

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(root_doc,
                                     ensure_contributors=ensure_contributors)
コード例 #6
0
ファイル: test_views.py プロジェクト: itai421/kuma
def test_doc_api(client, api_settings, trans_doc, cleared_cacheback_cache,
                 ensure_contributors):
    """On success we get document details in a JSON response."""
    if ensure_contributors:
        # Pre-populate the cache for the call to document_api_data()
        # made within the view that serves the "api.v1.doc" endpoint.
        DocumentContributorsJob().refresh(trans_doc.pk)

    url = reverse('api.v1.doc', args=[trans_doc.locale, trans_doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData']
    assert data['redirectURL'] is None
    doc_data = data['documentData']
    assert doc_data['locale'] == trans_doc.locale
    assert doc_data['slug'] == trans_doc.slug
    assert doc_data['id'] == trans_doc.id
    assert doc_data['title'] == trans_doc.title
    assert doc_data['language'] == trans_doc.language
    assert doc_data['hrefLang'] == 'fr'
    assert doc_data['absoluteURL'] == trans_doc.get_absolute_url()
    assert doc_data['editURL'] == absolutify(trans_doc.get_edit_url(),
                                             for_wiki_site=True)
    assert doc_data['translateURL'] is None
    assert doc_data['bodyHTML'] == trans_doc.get_body_html()
    assert doc_data['quickLinksHTML'] == trans_doc.get_quick_links_html()
    assert doc_data['tocHTML'] == trans_doc.get_toc_html()
    assert doc_data['translations'] == [{
        'locale': 'en-US',
        'language': 'English (US)',
        'hrefLang': 'en',
        'localizedLanguage': u'Anglais am\u00e9ricain',
        'title': 'Root Document',
        'url': '/en-US/docs/Root'
    }]
    assert doc_data['contributors'] == (['wiki_user']
                                        if ensure_contributors else [])
    assert doc_data['lastModified'] == '2017-04-14T12:20:00'
    assert doc_data['lastModifiedBy'] == 'wiki_user'

    # Clear the cache for a clean slate when calling document_api_data().
    DocumentContributorsJob().delete(trans_doc.pk)

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(trans_doc,
                                     ensure_contributors=ensure_contributors)
コード例 #7
0
def test_publish_standard(get_s3_bucket_mock, root_doc):
    """Test the publish task for a standard (non-redirect) document."""
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish.get_logger = mock.Mock(return_value=log_mock)
    publish([root_doc.pk])
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(root_doc),
        Body=json.dumps(document_api_data(root_doc, ensure_contributors=True)),
        ContentType='application/json',
        ContentLanguage=root_doc.locale
    )
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #8
0
def test_publish_redirect_to_home(get_s3_bucket_mock, redirect_to_home):
    """
    Test the publish task for a document that redirects to a URL outside the
    S3 bucket, in this case the home page.
    """
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([redirect_to_home.pk], log=log_mock)
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(redirect_to_home),
        Body=json.dumps(document_api_data(redirect_url='/en-US/')),
        ContentType='application/json',
        ContentLanguage=redirect_to_home.locale)
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #9
0
ファイル: test_tasks.py プロジェクト: mozilla/kuma
def test_publish_redirect_to_home(get_s3_bucket_mock, redirect_to_home):
    """
    Test the publish task for a document that redirects to a URL outside the
    S3 bucket, in this case the home page.
    """
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([redirect_to_home.pk], log=log_mock)
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(redirect_to_home),
        Body=json.dumps(document_api_data(redirect_url='/en-US/')),
        ContentType='application/json',
        ContentLanguage=redirect_to_home.locale
    )
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #10
0
ファイル: test_views.py プロジェクト: mozilla/kuma
def test_doc_api(client, api_settings, trans_doc, cleared_cacheback_cache,
                 ensure_contributors):
    """On success we get document details in a JSON response."""
    if ensure_contributors:
        # Pre-populate the cache for the call to document_api_data()
        # made within the view that serves the "api.v1.doc" endpoint.
        DocumentContributorsJob().refresh(trans_doc.pk)

    url = reverse('api.v1.doc', args=[trans_doc.locale, trans_doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData']
    assert data['redirectURL'] is None
    doc_data = data['documentData']
    assert doc_data['locale'] == trans_doc.locale
    assert doc_data['slug'] == trans_doc.slug
    assert doc_data['id'] == trans_doc.id
    assert doc_data['title'] == trans_doc.title
    assert doc_data['language'] == trans_doc.language
    assert doc_data['absoluteURL'] == trans_doc.get_absolute_url()
    assert doc_data['editURL'] == absolutify(trans_doc.get_edit_url(),
                                             for_wiki_site=True)
    assert doc_data['bodyHTML'] == trans_doc.get_body_html()
    assert doc_data['quickLinksHTML'] == trans_doc.get_quick_links_html()
    assert doc_data['tocHTML'] == trans_doc.get_toc_html()
    assert doc_data['translations'] == [{
        'locale': 'en-US',
        'language': 'English (US)',
        'localizedLanguage': u'Anglais am\u00e9ricain',
        'title': 'Root Document',
        'url': '/en-US/docs/Root'
    }]
    assert doc_data['contributors'] == (
        ['wiki_user'] if ensure_contributors else [])
    assert doc_data['lastModified'] == '2017-04-14T12:20:00'
    assert doc_data['lastModifiedBy'] == 'wiki_user'

    # Clear the cache for a clean slate when calling document_api_data().
    DocumentContributorsJob().delete(trans_doc.pk)

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(
        trans_doc, ensure_contributors=ensure_contributors)
コード例 #11
0
def test_publish_redirect_to_other(get_s3_bucket_mock, redirect_to_macros):
    """
    Test the publish task for a document that redirects to a URL outside the
    S3 bucket, in this case someting other than the home page.
    """
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([redirect_to_macros.pk], log=log_mock)
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(redirect_to_macros),
        Body=json.dumps(
            document_api_data(redirect_url=absolutify(
                '/en-US/dashboards/macros', for_wiki_site=True))),
        ContentType='application/json',
        ContentLanguage=redirect_to_macros.locale)
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #12
0
ファイル: test_views.py プロジェクト: mozilla/kuma
def test_doc_api_for_redirect_to_doc(client, api_settings, root_doc,
                                     redirect_doc, cleared_cacheback_cache,
                                     ensure_contributors):
    """
    Test the document API when we're requesting data for a document that
    redirects to another document.
    """
    if ensure_contributors:
        # Pre-populate the cache for the call to document_api_data()
        # made within the view that serves the "api.v1.doc" endpoint.
        DocumentContributorsJob().refresh(root_doc.pk)

    url = reverse('api.v1.doc', args=[redirect_doc.locale, redirect_doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST, follow=True)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['documentData']
    assert data['redirectURL'] is None
    doc_data = data['documentData']
    assert doc_data['locale'] == root_doc.locale
    assert doc_data['slug'] == root_doc.slug
    assert doc_data['id'] == root_doc.id
    assert doc_data['title'] == root_doc.title
    assert doc_data['language'] == root_doc.language
    assert doc_data['absoluteURL'] == root_doc.get_absolute_url()
    assert doc_data['editURL'] == absolutify(root_doc.get_edit_url(),
                                             for_wiki_site=True)
    assert doc_data['bodyHTML'] == root_doc.get_body_html()
    assert doc_data['quickLinksHTML'] == root_doc.get_quick_links_html()
    assert doc_data['tocHTML'] == root_doc.get_toc_html()
    assert doc_data['translations'] == []
    assert doc_data['contributors'] == (
        ['wiki_user'] if ensure_contributors else [])
    assert doc_data['lastModified'] == '2017-04-14T12:15:00'
    assert doc_data['lastModifiedBy'] == 'wiki_user'

    # Clear the cache for a clean slate when calling document_api_data().
    DocumentContributorsJob().delete(root_doc.pk)

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(
        root_doc, ensure_contributors=ensure_contributors)
コード例 #13
0
ファイル: test_tasks.py プロジェクト: mozilla/kuma
def test_publish_redirect_to_other(get_s3_bucket_mock, redirect_to_macros):
    """
    Test the publish task for a document that redirects to a URL outside the
    S3 bucket, in this case someting other than the home page.
    """
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([redirect_to_macros.pk], log=log_mock)
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(redirect_to_macros),
        Body=json.dumps(document_api_data(
            redirect_url=absolutify('/en-US/dashboards/macros',
                                    for_wiki_site=True))),
        ContentType='application/json',
        ContentLanguage=redirect_to_macros.locale
    )
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #14
0
def test_publish_standard(get_s3_bucket_mock, root_doc, invalidate_cdn_cache):
    """Test the publish task for a standard (non-redirect) document."""
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish.get_logger = mock.Mock(return_value=log_mock)
    with mock.patch('kuma.api.tasks.request_cdn_cache_invalidation') as mocked:
        publish([root_doc.pk], invalidate_cdn_cache=invalidate_cdn_cache)
        if invalidate_cdn_cache:
            mocked.delay.assert_called_once_with([(root_doc.locale,
                                                   root_doc.slug)])
        else:
            mocked.delay.assert_not_called()
    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(root_doc),
        Body=json.dumps(document_api_data(root_doc)),
        ContentType='application/json',
        ContentLanguage=root_doc.locale)
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #15
0
ファイル: test_tasks.py プロジェクト: pha-nui/kuma
def test_publish_redirect(get_s3_bucket_mock, root_doc, redirect_doc):
    """
    Test the publish task for a document that redirects to another document
    within the S3 bucket.
    """
    log_mock = mock.Mock()
    get_s3_bucket_mock.return_value = s3_bucket_mock = get_mocked_s3_bucket()
    publish([redirect_doc.pk], log=log_mock)

    s3_bucket_mock.put_object.assert_called_once_with(
        ACL='public-read',
        Key=get_s3_key(redirect_doc),
        WebsiteRedirectLocation=get_s3_key(
            root_doc, prefix_with_forward_slash=True, suffix_file_extension=False),
        ContentType='application/json',
        ContentLanguage=redirect_doc.locale,
        Body=json.dumps(document_api_data(None, redirect_url=get_content_based_redirect(redirect_doc)[0]))
    )
    log_mock.info.assert_called_once_with('Published S3 Object #1')
コード例 #16
0
def test_doc_api(client, api_settings, trans_doc, cleared_cacheback_cache):
    """On success we get document details in a JSON response."""

    # The fetch_on_miss mock and the cleared_cacheback_cache fixture
    # are here to ensure that we don't get an old cached value for
    # the contributors property, and also that we don't use []
    # while a celery job is running.
    url = reverse('api.v1.doc', args=[trans_doc.locale, trans_doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['locale'] == trans_doc.locale
    assert data['slug'] == trans_doc.slug
    assert data['id'] == trans_doc.id
    assert data['title'] == trans_doc.title
    assert data['language'] == trans_doc.language
    assert data['absoluteURL'] == trans_doc.get_absolute_url()
    assert data['redirectURL'] == trans_doc.get_redirect_url()
    assert data['editURL'] == absolutify(trans_doc.get_edit_url(),
                                         for_wiki_site=True)
    assert data['bodyHTML'] == trans_doc.get_body_html()
    assert data['quickLinksHTML'] == trans_doc.get_quick_links_html()
    assert data['tocHTML'] == trans_doc.get_toc_html()
    assert data['translations'] == [{
        'locale': 'en-US',
        'language': 'English (US)',
        'localizedLanguage': u'Anglais am\u00e9ricain',
        'title': 'Root Document',
        'url': '/en-US/docs/Root'
    }]
    assert data['contributors'] == ['wiki_user']
    assert data['lastModified'] == '2017-04-14T12:20:00'
    assert data['lastModifiedBy'] == 'wiki_user'

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    data2 = document_api_data(trans_doc)
    assert data == data2
コード例 #17
0
ファイル: test_views.py プロジェクト: parsamparpary/kuma
def test_doc_api_for_redirect_to_non_doc(client, api_settings,
                                         redirect_to_home, redirect_to_macros,
                                         case):
    """
    Test the document API when we're requesting data for a document that
    redirects to a non-document page (either the home page or another).
    """
    if case == 'redirect-to-home':
        doc = redirect_to_home
        expected_redirect_url = '/en-US/'
    else:
        doc = redirect_to_macros
        expected_redirect_url = absolutify('/en-US/dashboards/macros',
                                           for_wiki_site=True)
    url = reverse('api.v1.doc', args=[doc.locale, doc.slug])
    response = client.get(url, HTTP_HOST=api_settings.BETA_HOST)
    assert response.status_code == 200
    assert_no_cache_header(response)

    data = response.json()
    assert data['locale'] is None
    assert data['slug'] is None
    assert data['id'] is None
    assert data['title'] is None
    assert data['language'] is None
    assert data['absoluteURL'] is None
    assert data['redirectURL'] == expected_redirect_url
    assert data['editURL'] is None
    assert data['bodyHTML'] is None
    assert data['quickLinksHTML'] is None
    assert data['tocHTML'] is None
    assert data['translations'] is None
    assert data['contributors'] is None
    assert data['lastModified'] is None
    assert data['lastModifiedBy'] is None

    # Also ensure that we get exactly the same data by calling
    # the document_api_data() function directly
    assert data == document_api_data(redirect_url=expected_redirect_url)
コード例 #18
0
ファイル: document.py プロジェクト: mozilla/kuma
def react_document(request, document_slug, document_locale):
    """
    View a wiki document.
    """
    fallback_reason = None
    slug_dict = split_slug(document_slug)

    # Is there a document at this slug, in this locale?
    doc, fallback_reason = _get_doc_and_fallback_reason(document_locale,
                                                        document_slug)

    if doc is None:
        # We can throw a 404 immediately if the request type is HEAD.
        # TODO: take a shortcut if the document was found?
        if request.method == 'HEAD':
            raise Http404

        # Check if we should fall back to default locale.
        fallback_doc, fallback_reason, redirect_url = _default_locale_fallback(
            request, document_slug, document_locale)
        if fallback_doc is not None:
            doc = fallback_doc
            if redirect_url is not None:
                return redirect(redirect_url)
        else:
            raise Http404

    # We found a Document. Now we need to figure out how we're going
    # to display it.

    # If we're a redirect, and redirecting hasn't been disabled, redirect.

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (None if request.GET.get('redirect') == 'no'
                    else doc.get_redirect_url())

    if redirect_url and redirect_url != doc.get_absolute_url():
        url = urlparams(redirect_url, query_dict=request.GET)
        # TODO: Re-enable the link in this message after Django >1.5 upgrade
        # Redirected from <a href="%(url)s?redirect=no">%(url)s</a>
        messages.add_message(
            request, messages.WARNING,
            mark_safe(ugettext(u'Redirected from %(url)s') % {
                "url": request.build_absolute_uri(doc.get_absolute_url())
            }), extra_tags='wiki_redirect')
        return HttpResponsePermanentRedirect(url)

    # Get the SEO summary
    seo_summary = doc.get_summary_text()

    # Get the additional title information, if necessary.
    seo_parent_title = _get_seo_parent_title(
        doc, slug_dict, document_locale)

    # Record the English slug in Google Analytics,
    # to associate translations
    if doc.locale == 'en-US':
        en_slug = doc.slug
    elif doc.parent_id and doc.parent.locale == 'en-US':
        en_slug = doc.parent.slug
    else:
        en_slug = ''

    share_text = ugettext(
        'I learned about %(title)s on MDN.') % {"title": doc.title}

    contributors = doc.contributors
    contributors_count = len(contributors)
    has_contributors = contributors_count > 0
    other_translations = doc.get_other_translations(
        fields=['title', 'locale', 'slug', 'parent']
    )
    all_locales = (set([doc.locale]) |
                   set(trans.locale for trans in other_translations))

    # Get the JSON data for this document
    doc_api_data = document_api_data(doc, ensure_contributors=True)
    document_data = doc_api_data['documentData']

    # Create another object of request-related data to pass to jinja
    request_data = {
        # Despite its name, the document_locale argument is the locale
        # of the request, and is not always (in the case of missing
        # translations) the same as the locale of the document.
        'locale': document_locale
    }

    # Bundle it all up and, finally, return.
    context = {
        'document_data': document_data,
        'request_data': request_data,

        # TODO: anything we're actually using in the template ought
        # to be bundled up into the json object above instead.
        'document': doc,
        'contributors': contributors,
        'contributors_count': contributors_count,
        'contributors_limit': 6,
        'has_contributors': has_contributors,
        'fallback_reason': fallback_reason,
        'seo_summary': seo_summary,
        'seo_parent_title': seo_parent_title,
        'share_text': share_text,
        'search_url': get_search_url_from_referer(request) or '',
        'analytics_page_revision': doc.current_revision_id,
        'analytics_en_slug': en_slug,
        'other_translations': other_translations,
        'all_locales': all_locales,
    }
    response = render(request, 'wiki/react_document.html', context)

    return _add_kuma_revision_header(doc, response)
コード例 #19
0
ファイル: document.py プロジェクト: surajpoddar16/kuma
def react_document(request, document_slug, document_locale):
    """
    View a wiki document.
    """
    fallback_reason = None
    slug_dict = split_slug(document_slug)

    # Is there a document at this slug, in this locale?
    doc, fallback_reason = _get_doc_and_fallback_reason(
        document_locale, document_slug)

    if doc is None:
        # We can throw a 404 immediately if the request type is HEAD.
        # TODO: take a shortcut if the document was found?
        if request.method == 'HEAD':
            raise Http404

        # Check if we should fall back to default locale.
        fallback_doc, fallback_reason, redirect_url = _default_locale_fallback(
            request, document_slug, document_locale)
        if fallback_doc is not None:
            doc = fallback_doc
            if redirect_url is not None:
                return redirect(redirect_url)
        else:
            raise Http404

    # We found a Document. Now we need to figure out how we're going
    # to display it.

    # If we're a redirect, and redirecting hasn't been disabled, redirect.

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (None if request.GET.get('redirect') == 'no' else
                    doc.get_redirect_url())

    if redirect_url and redirect_url != doc.get_absolute_url():
        url = urlparams(redirect_url, query_dict=request.GET)
        # TODO: Re-enable the link in this message after Django >1.5 upgrade
        # Redirected from <a href="%(url)s?redirect=no">%(url)s</a>
        messages.add_message(
            request,
            messages.WARNING,
            mark_safe(
                ugettext(u'Redirected from %(url)s') %
                {"url": request.build_absolute_uri(doc.get_absolute_url())}),
            extra_tags='wiki_redirect')
        return HttpResponsePermanentRedirect(url)

    # Get the SEO summary
    seo_summary = doc.get_summary_text()

    # Get the additional title information, if necessary.
    seo_parent_title = _get_seo_parent_title(doc, slug_dict, document_locale)

    # Record the English slug in Google Analytics,
    # to associate translations
    if doc.locale == 'en-US':
        en_slug = doc.slug
    elif doc.parent_id and doc.parent.locale == 'en-US':
        en_slug = doc.parent.slug
    else:
        en_slug = ''

    share_text = ugettext('I learned about %(title)s on MDN.') % {
        "title": doc.title
    }

    contributors = doc.contributors
    contributors_count = len(contributors)
    has_contributors = contributors_count > 0
    other_translations = doc.get_other_translations(
        fields=['title', 'locale', 'slug', 'parent'])
    all_locales = (set([doc.locale]) | set(trans.locale
                                           for trans in other_translations))

    # Bundle it all up and, finally, return.
    context = {
        'document_api_data':
        base64.b64encode(json.dumps(document_api_data(doc))),
        # TODO: anything we're actually using in the template ought
        # to be bundled up into the json object above instead.
        'document': doc,
        'contributors': contributors,
        'contributors_count': contributors_count,
        'contributors_limit': 6,
        'has_contributors': has_contributors,
        'fallback_reason': fallback_reason,
        'seo_summary': seo_summary,
        'seo_parent_title': seo_parent_title,
        'share_text': share_text,
        'search_url': get_search_url_from_referer(request) or '',
        'analytics_page_revision': doc.current_revision_id,
        'analytics_en_slug': en_slug,
        'other_translations': other_translations,
        'all_locales': all_locales,
    }
    response = render(request, 'wiki/react_document.html', context)

    return _add_kuma_revision_header(doc, response)
コード例 #20
0
ファイル: document.py プロジェクト: sato-hirokazu/kuma
def react_document(request, document_slug, document_locale):
    """
    View a wiki document.
    """
    # If any query parameter is used that is only supported by the wiki view,
    # redirect to the wiki domain.
    if frozenset(request.GET) & WIKI_ONLY_DOCUMENT_QUERY_PARAMS:
        return redirect_to_wiki(request)

    slug_dict = split_slug(document_slug)

    # Is there a document at this slug, in this locale?
    doc, _ = _get_doc_and_fallback_reason(document_locale, document_slug)

    if doc is None:
        # We can throw a 404 immediately if the request type is HEAD.
        # TODO: take a shortcut if the document was found?
        if request.method == 'HEAD':
            raise Http404

        # Check if we should fall back to default locale.
        fallback_doc, _, redirect_url = _default_locale_fallback(
            request, document_slug, document_locale)
        if fallback_doc is not None:
            doc = fallback_doc
            if redirect_url is not None:
                return redirect(redirect_url)
        else:
            raise Http404

    # We found a Document. Now we need to figure out how we're going
    # to display it.

    # If we're a redirect, and redirecting hasn't been disabled, redirect.

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (None if request.GET.get('redirect') == 'no' else
                    doc.get_redirect_url())

    if redirect_url and redirect_url != doc.get_absolute_url():
        url = urlparams(redirect_url, query_dict=request.GET)
        # TODO: Re-enable the link in this message after Django >1.5 upgrade
        # Redirected from <a href="%(url)s?redirect=no">%(url)s</a>
        messages.add_message(
            request,
            messages.WARNING,
            mark_safe(
                ugettext(u'Redirected from %(url)s') %
                {"url": request.build_absolute_uri(doc.get_absolute_url())}),
            extra_tags='wiki_redirect')
        return HttpResponsePermanentRedirect(url)

    # Get the SEO summary
    seo_summary = doc.get_summary_text()

    # Get the additional title information, if necessary.
    seo_parent_title = _get_seo_parent_title(doc, slug_dict, document_locale)

    # Get the JSON data for this document
    doc_api_data = document_api_data(doc)
    document_data = doc_api_data['documentData']

    # Bundle it all up and, finally, return.
    context = {
        'document_data': document_data,

        # TODO: anything we're actually using in the template ought
        # to be bundled up into the json object above instead.
        'seo_summary': seo_summary,
        'seo_parent_title': seo_parent_title,
    }
    response = render(request, 'wiki/react_document.html', context)

    return _add_kuma_revision_header(doc, response)
コード例 #21
0
ファイル: document.py プロジェクト: w0lramD/kuma
def react_document(request, document_slug, document_locale):
    """
    View a wiki document.
    """
    # If any query parameter is used that is only supported by the wiki view,
    # redirect to the wiki domain.
    if frozenset(request.GET) & WIKI_ONLY_DOCUMENT_QUERY_PARAMS:
        return redirect_to_wiki(request)

    slug_dict = split_slug(document_slug)

    # Is there a document at this slug, in this locale?
    doc, fallback_reason = _get_doc_and_fallback_reason(document_locale, document_slug)

    if doc is None:
        # We can throw a 404 immediately if the request type is HEAD.
        # TODO: take a shortcut if the document was found?
        if request.method == "HEAD":
            raise Http404

        # Check if we should fall back to default locale.
        fallback_doc, fallback_reason, redirect_url = _default_locale_fallback(
            request, document_slug, document_locale
        )
        if fallback_doc is not None:
            doc = fallback_doc
            if redirect_url is not None:
                return redirect(redirect_url)
        else:
            # It could be that the document you're trying to view was deleted and
            # the reason we're not finding a fallback is because the slug
            # doesn't match.
            # E.g. you're trying to view `/sv-SE/docs/Foö/Bår` but that document
            # was soft-deleted and its parent was `/en-US/docs/Foo/Bar`
            if document_locale != settings.LANGUAGE_CODE:  # Not in English!
                redirect_url = _get_deleted_parent_redirect_url(
                    document_locale, document_slug
                )
                if redirect_url:
                    return redirect(redirect_url)

            raise Http404

    # We found a Document. Now we need to figure out how we're going
    # to display it.

    # If we're a redirect, and redirecting hasn't been disabled, redirect.

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (
        None if request.GET.get("redirect") == "no" else doc.get_redirect_url()
    )

    if redirect_url and redirect_url != doc.get_absolute_url():
        url = urlparams(redirect_url, query_dict=request.GET)
        # TODO: Re-enable the link in this message after Django >1.5 upgrade
        # Redirected from <a href="%(url)s?redirect=no">%(url)s</a>
        messages.add_message(
            request,
            messages.WARNING,
            mark_safe(
                gettext("Redirected from %(url)s")
                % {"url": request.build_absolute_uri(doc.get_absolute_url())}
            ),
            extra_tags="wiki_redirect",
        )
        return HttpResponsePermanentRedirect(url)

    # Get the SEO summary
    seo_summary = doc.get_summary_text()

    # Get the additional title information, if necessary.
    seo_parent_title = _get_seo_parent_title(doc, slug_dict, document_locale)

    # Get the JSON data for this document
    doc_api_data = document_api_data(doc)
    document_data = doc_api_data["documentData"]

    def robots_index():
        if fallback_reason:
            return False

        if not doc.html:
            return False

        if doc.is_experiment:
            return False

        if doc.has_legacy_namespace:
            return False

        if doc.has_noindex_slug:
            return False

        if request.get_host() not in settings.ALLOW_ROBOTS_WEB_DOMAINS:
            return False

        return True

    robots_meta_content = "index, follow" if robots_index() else "noindex, nofollow"

    # Bundle it all up and, finally, return.
    context = {
        "document_data": document_data,
        # TODO: anything we're actually using in the template ought
        # to be bundled up into the json object above instead.
        "seo_summary": seo_summary,
        "seo_parent_title": seo_parent_title,
        "robots_meta_content": robots_meta_content,
    }
    response = render(request, "wiki/react_document.html", context)

    return _add_kuma_revision_header(doc, response)