Beispiel #1
0
def doc_reader(request, topic=None, slug=None, format=None, docs_root=settings.DOCS_ROOT):
    """ Read a document """
    # Define the document name
    if slug is not None:
        doc_name = slug
    else:
        doc_name = settings.DOCS_DEFAULT
    # Get the document topic path
    doc_path = settings.DOCS_TOPIC.get(topic, "tutorial")
    # The path to documentation file
    file_path = join(docs_root, doc_path, "%s.txt" % doc_name)
    # Test the file exists
    if not exists(file_path):
        return page_not_found(request, message=_("The required document page does not exist."))
    # Cache key
    cache_key = "tranpy:docs:%s:%s:%s" % (topic, doc_name, getmtime(file_path))
    # Try to read from cache
    parts = cache.get(cache_key)
    if parts is None:
        # Not found in cache
        parts = build_document(file_path)
        cache.set(cache_key, parts, 60 * 60)
    # Define the template
    if format == "xml":
        template_name = "docs/minimal.html"
    else:
        template_name = "docs/detail.html"
    # Return the response
    return render_to_response(
        template_name,
        {"doc": parts, "topic": topic, "slug": slug, "format": format},
        context_instance=RequestContext(request),
    )
Beispiel #2
0
def catalogs(request, language_code=None, project_code=None, format="csv", recursive=None):
    """ Return statistics for catalogs for the specified language and project """
    # Try to find the language
    try:
        language = Language.objects.get(code=language_code)
    except:
        # Language code inexistent, return 404
        return page_not_found(request, _("There is no language with %s code.") % language_code)
    # Try to find the project
    try:
        project = Project.objects.get(code=project_code)
    except:
        # Project code inexistent, return 404
        return page_not_found(request, _("There is no project with %s code.") % project_code)
    # Create the report data
    data = report_catalogs(language=language, project=project, user=request.user)
    # Create the generator and return the result
    generator = ReportGenerator(request, data)
    return generator.build(format, subject="%s %s" % (language.name, project.name))
Beispiel #3
0
def project(request, project_code=None, format="csv", recursive=None):
    """ Return language statistics for one project """
    # Try to find the project
    try:
        project = Project.objects.get(code=project_code)
    except:
        # Project code inexistent, return 404
        return page_not_found(request, _("There is no project with %s code.") % project_code)
    # Create the report data
    data = report_project(project=project, user=request.user, recursive=recursive)
    # Create the generator and return the result
    generator = ReportGenerator(request, data)
    return generator.build(format, subject="%s" % (project.name,))
Beispiel #4
0
def language(request, language_code=None, format="csv", recursive=None):
    """ Return project statistics for one language """
    # Try to find the language
    try:
        language = Language.objects.get(code=language_code)
    except:
        # Language code inexistent, return 404
        return page_not_found(request, _("There is no language with %s code.") % language_code)
    # Create the report data
    data = report_language(language=language, user=request.user, recursive=recursive)
    # Create the generator and return the result
    generator = ReportGenerator(request, data)
    return generator.build(format, subject="%s" % (language.name,))
Beispiel #5
0
def group_update(request, group_id = None, template_name = 'accounts/group/form.html'):
    """ Edit the group's details """

    if group_id:
        # Check permissions
        if not request.user.has_perm('accounts.change_group'):
            return page_forbidden(request, _('You are not allowed to change group details.'))
        # We know the group id, so this is an update
        try:
            group = Group.objects.select_related().get(id = group_id)
        except Group.DoesNotExist:
            return page_not_found(request, _('There is no such group.'))
    else:
        # Check permissions
        if not request.user.has_perm('accounts.add_group'):
            return page_forbidden(request, _('You are not allowed to add a group.'))
        # This is a new one
        group = None
    # The absolute URL of group list
    # TODO DNRY
    url = '/accounts/groups/'

    # Check the request
    if request.method == "POST":
        # Posting data
        if 'submit' in request.POST and 'group_form' in request.POST:
            # Fill the form with posted data
            form = GroupForm(request.POST, group = group)
            # Check the data validity
            if form.is_valid():
                # Save the form and, implicit, the model
                form.save()
                # Redirect to users page
                return HttpResponseRedirect(url)
        elif 'cancel' in request.POST:
            # No data, redirect to users page
            return HttpResponseRedirect(url)
    else:
        # No submitted data, just display the form
        form = GroupForm(group = group)

    # Return the response
    return render_to_response(
            template_name,
            {
                'form': form,
                'object': group,
            },
            context_instance = RequestContext(request)
        )
Beispiel #6
0
def user_update(request, username = None, template_name = 'accounts/user/form.html'):
    """ Edit the user's details and profile """

    # Check permissions
    if not request.user.has_perm('accounts.change_user'):
        return page_forbidden(request, _('You are not allowed to change users details.'))

    # Try to get the user
    try:
        user = User.objects.select_related().get(username = username)
    except User.DoesNotExist:
        return page_not_found(request, _('There is no such user.'))
    # The absolute URL of users list
    # TODO DNRY
    url = '/accounts/users/'

    # Check the request
    if request.POST:
        # Posting data
        if 'submit' in request.POST:
            # Fill the form with posted data
            form = UserForm(user, request.POST)
            # Check the data validity
            if form.is_valid():
                # Save the form and, implicit, the model
                form.save()
                # Redirect to users page
                return HttpResponseRedirect(url)
        elif 'cancel' in request.POST:
            # No data, redirect to users page
            return HttpResponseRedirect(url)
    else:
        # No submitted data, just display the form
        form = UserForm(user)

    # Return the response
    return render_to_response(
            template_name,
            {
                'form': form,
                'object': user,
            },
            context_instance = RequestContext(request)
        )
Beispiel #7
0
def handle_xmlrpc(request):
    """ Handle XML-RPC requests

    request
        The HttpRequest object that carries the XML-RPC call. If this is a
        GET request, nothing will happen (we only accept POST requests)
    """
    if request.method == 'POST':
        # Limit the mumber of XML-RPC calls...
        key = request.META['REMOTE_ADDR']
        calls = cache.get('xmlrpc:calls:%s' % key, default = 0)
        if calls > 5:
            # Return '503'
            return service_unavailable(request)
        else:
            # Increment the limit counter
            cache.set('xmlrpc:calls:%s' % key, calls + 1, 600)

        # The XML-RPC response
        response = HttpResponse(mimetype = 'text/xml')

        # Try to process the request
        try:
            result = xmlrpc_interface.process(request.raw_post_data)
        except:
            # Decrement the limit counter
            calls = cache.get('xmlrpc:calls:%s' % key)
            cache.set('xmlrpc:calls:%s' % key, calls - 1, 600)
            # Return '500'
            return server_error(request)
        else:
            # Decrement the limit counter
            calls = cache.get('xmlrpc:calls:%s' % key)
            cache.set('xmlrpc:calls:%s' % key, calls - 1, 600)
            # Write the result to the XML-RPC response
            response.write(result)
            # Return the response
            return response
    else:
        # Return '404'
        return page_not_found(request)
Beispiel #8
0
def xmlrpc_remove(request, username = None):
    """ Remove the XML-RPC shared secret """
    # Set the next url
    next_url = request.META.get('HTTP_REFERER', '/')
    # Prepare the response
    response = HttpResponseRedirect(next_url)
    # Check permissions
    if not request.user.has_perm('accounts.remove_xmlrpc_key'):
        return page_forbidden(request, _('You are not allowed to remove a XML-RPC key.'))
    # Try to get the user
    try:
        user = User.objects.select_related().get(username = username)
    except User.DoesNotExist:
        return page_not_found(request, _('There is no such user.'))
    # Get the user profile
    user_profile = user.get_profile()
    # Remove the key
    user_profile.remove_xmlrpc_key()
    # Send a message to the creator
    request.user.alerts.create(type = 'delete', message = _('The XML-RPC key of %(user)s has been removed.') % {'user': user.get_full_name()})
    # Return the response
    return response
Beispiel #9
0
def exporter(request,
        language_code = None,
        project_code = None,
        catalog_code = None,
        filename = None,
        filter = None,
        untranslated = None,
        proofread = None,
        format = 'xliff',
        testpacktrans = False,
        **kwargs):
    """ Wrapper for the exporter """

    # Check the request
    if request.POST:
        try:
            format = request.POST['export-catalog-format']
        except:
            request.user.alerts.create(type = 'error', message = 'Unknown format.')
            format = None
        try:
            language_code = request.POST['export-catalog-language']
        except:
            request.user.alerts.create(type = 'error', message = 'Unknown language.')
            language_code = None
        try:
            project_code = request.POST['export-catalog-project']
        except:
            request.user.alerts.create(type = 'error', message = 'Unknown project.')
            project_code = None
        try:
            catalog_code = request.POST['export-catalog-catalog']
        except:
            request.user.alerts.create(type = 'error', message = 'Unknown catalog.')
            catalog_code = None
        try:
            modifier = request.POST['export-catalog-modifier']
        except:
            untranslated = None
            proofread = None
        else:
            if modifier == 'proofread':
                proofread = modifier
            elif modifier == 'untranslated':
                untranslated = modifier
        try:
            filename = request.POST['export-catalog-filename']
        except:
            filename = None
        try:
            filter = request.POST['export-catalog-filter']
        except:
            filter = None

        testpacktrans = request.POST.get('export-catalog-testpacktrans', 'yes') == 'yes'

    try:
        # The exporter object
        exporter = Exporter(
                language_code = language_code,
                project_code = project_code,
                catalog_code = catalog_code,
                user = request.user,
                filter = filter,
                untranslated = untranslated,
                proofread = proofread,
                testpacktrans = testpacktrans)
    except ExporterSourceIterationError:
        # Cannot find the iteration of the source catalog
        response = page_not_found(request, _('Cannot find the iteration of the reviewed catalog.'))
    else:
        try:
            # Get the content
            content = exporter.export(format, **kwargs)
        except ExporterUnsupportedFormat:
            # The format is not supported
            response = page_not_found(request, _('Unsupported format: %s' % format))
        except ExporterForbidden:
            # The user is not allowed to export
            response = page_forbidden(request, _('You are not allowed to export to the %s format.' % format))
        except ExporterSourceIterationError:
            # Cannot find the iteration of the source catalog
            response = page_not_found(request, _('The catalog needs to be transfered again. Please contact the system administrator.'))
        else:
            # Create the HttpResponse object with the appropriate header
            if filename is None:
                filename = exporter.create_file_name(CFT.get_extension(format))
            response = HttpResponse(content.getvalue(), mimetype = CFT.get_mime(format))
            response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    # Return the response
    return response
Beispiel #10
0
def campaigns(request, language_code=None, project_code=None, campid=None):
    """ Campaigns for the specified language and project """

    if language_code is not None:
        # Try to find the language
        try:
            language = Language.objects.get(code=language_code)
        except:
            # Language code inexistent, return 404
            return page_not_found(request, _("There is no language with %s code.") % language_code)
    else:
        language = None
    if project_code is not None:
        # Try to find the project
        try:
            project = Project.objects.get(code=project_code)
        except:
            # Project code inexistent, return 404
            return page_not_found(request, _("There is no project with %s code.") % project_code)
    else:
        project = None

    # Find the redirect URL
    url = request.META.get("HTTP_REFERER", "/")
    # Check permissions
    if not request.user.has_perm("statistics.campaigns"):
        return HttpResponseRedirect(url)

    # Check the method
    if request.META.get("REQUEST_METHOD", "GET") == "POST" and language is not None and project is not None:
        # Get the action
        action = request.POST.get("campaign", None)
        if action == "open":
            # Open a new campaign
            campaign = Campaign.objects.open(language=language, project=project, user=request.user)
        elif action == "close":
            # Close the campaigns
            Campaign.objects.close(language=language, project=project)
        elif action == "refresh":
            # Refresh the work status
            for camp in Campaign.objects.active(language=language, project=project):
                camp.refresh()
        elif action == "export":
            # Export the report
            report_type = request.POST.get("type", None)
            if report_type == "csv":
                subject = "Campaigns-%s-%s" % (language.name, project.name)
                header = [
                    "Campaign",
                    "Language",
                    "Project",
                    "Started",
                    "Ended",
                    "Total word count",
                    "Cost (%.3f euro/word)" % (0.001 * language.price),
                ]
                users = []
                campaigns = []
                # Create the HttpResponse object with the appropriate CSV header
                response = HttpResponse(mimetype="text/csv")
                response["Content-Disposition"] = "attachment; filename=%s.csv" % (subject.replace(" ", "_"),)
                # Create the CSV writer
                writer = csv.writer(response, dialect="excel", quoting=csv.QUOTE_ALL)
                # Get the campaigns and users list
                for campaign in Campaign.objects.filter(language=language, project=project):
                    campaigns.append(campaign)
                    for user in campaign.get_users(all=True):
                        if not user in users:
                            users.append(user)
                # Write the header
                header.extend([u.get_full_name() for u in users])
                writer.writerow(header)
                # Write the data
                for campaign in campaigns:
                    data = [
                        campaign.id,
                        str(campaign.language),
                        str(campaign.project),
                        format(campaign.started, "d-m-Y"),
                        format(campaign.ended, "d-m-Y"),
                        campaign.work,
                        "%.3f" % campaign.cost(),
                    ]
                    for user in users:
                        wordcount = campaign.get_wordcount(user)
                        data.append("%s (%.3f euro)" % (wordcount, 0.001 * wordcount * campaign.language.price))
                    writer.writerow(data)
                # Return the response
                return response
    else:
        if campid is None:
            # Get all the campaigns
            campaigns = Campaign.objects.all()
            if language is not None:
                campaigns = campaigns.filter(language=language)
            if project is not None:
                campaigns = campaigns.filter(project=project)
        else:
            # Get the specified campaign
            try:
                campaign = Campaign.objects.get(id=campid)
            except:
                # Campaign inexistent, return 404
                return page_not_found(request, _("There is no such campaign."))
            else:
                campaigns = [campaign]
                language = campaign.language
                project = campaign.project
        # Initialize the context
        context = RequestContext(request)
        if language is not None:
            # Get the language
            context["language"] = language
        if project is not None:
            # Get the project
            context["project"] = project
        # Get the campaign
        context["campaigns"] = campaigns
        # The price per word
        if language is not None:
            context["price"] = 0.001 * language.price
        else:
            context["price"] = 0.0
        # Render the response
        return render_to_response("statistics/campaign.html", context)
    # Redirect
    return HttpResponseRedirect(url)