示例#1
0
 def _update(self, request, project_slug, resource_slug):
     data = getattr(request, 'data', None)
     if not data:  # Check for {} as well
         return BAD_REQUEST("Empty request")
     try:
         self._check_fields(data.iterkeys(), self.written_fields)
     except AttributeError, e:
         return BAD_REQUEST("Field '%s' is not allowed." % e)
示例#2
0
 def update(self, request, project_slug, api_version=1):
     """
     API call to update project details via PUT.
     """
     if project_slug is None:
         return BAD_REQUEST("Project slug not specified.")
     data = request.data
     if data is None:
         return BAD_REQUEST("Empty request.")
     return self._update(request, project_slug, data)
示例#3
0
 def create(self, request, project_slug=None, api_version=1):
     """
     API call to create new projects via POST.
     """
     data = getattr(request, 'data', None)
     if project_slug is not None:
         return BAD_REQUEST("POSTing to this url is not allowed.")
     if data is None:
         return BAD_REQUEST("At least parameters 'slug', 'name' and "
                            "'source_language' are needed.")
     return self._create(request, data)
示例#4
0
 def delete(self, request, project_slug=None, api_version=1):
     """
     API call to delete projects via DELETE.
     """
     if project_slug is None:
         return BAD_REQUEST("Project slug not specified.")
     return self._delete(request, project_slug)
示例#5
0
 def create(self, request, project_slug, resource_slug=None, api_version=1):
     """
     Create new resource under project `project_slug` via POST
     """
     data = getattr(request, 'data', None)
     if resource_slug is not None:
         return BAD_REQUEST("POSTing to this url is not allowed.")
     if data is None:
         return BAD_REQUEST(
             "At least parameters 'slug', 'name', 'i18n_type' "
             "and 'source_language' must be specified,"
             " as well as the source strings.")
     try:
         res = self._create(request, project_slug, data)
     except BadRequestError, e:
         return BAD_REQUEST(unicode(e))
示例#6
0
    def _read(self, request, project_slug, resource_slug, lang_code,
              is_pseudo):
        try:
            r = Resource.objects.get(slug=resource_slug,
                                     project__slug=project_slug)
        except Resource.DoesNotExist:
            return rc.NOT_FOUND

        if lang_code == "source":
            language = r.source_language
        else:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                return rc.NOT_FOUND

        # Check whether the request asked for a pseudo file, if so check if
        # a ``pseudo_type`` GET var was passed with a valid pseudo type.
        if is_pseudo:
            ptype = request.GET.get('pseudo_type', None)
            if not ptype in settings.PSEUDO_TYPES.keys():
                return rc.NOT_FOUND
            # Instantiate Pseudo type object
            pseudo_type = get_pseudo_class(ptype)(r.i18n_type)
        else:
            pseudo_type = None

        # Get the mode the user requested, if any
        mode = request.GET.get('mode', None)
        if mode is not None:
            try:
                mode = getattr(Mode, mode.upper())
            except AttributeError, e:
                return BAD_REQUEST(unicode(e))
示例#7
0
class StatsHandler(BaseHandler):
    allowed_methods = ('GET', )

    def read(self,
             request,
             project_slug,
             resource_slug,
             lang_code=None,
             api_version=1):
        """
        This is an API handler to display translation statistics for individual
        resources.
        """
        if api_version != 2:
            return BAD_REQUEST('Wrong API version called.')
        return self._get_stats(request, project_slug, resource_slug, lang_code)

    def _get_stats(self, request, pslug, rslug, lang_code):
        try:
            resource = Resource.objects.get(project__slug=pslug, slug=rslug)
        except Resource.DoesNotExist, e:
            logger.debug("Resource %s.%s requested, but it does not exist" %
                         (pslug, rslug),
                         exc_info=True)
            return rc.NOT_FOUND
        language = None
        if lang_code is not None:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist, e:
                logger.debug(
                    "Language %s was requested, but it does not exist." %
                    lang_code,
                    exc_info=True)
                return BAD_REQUEST("Unknown language code %s" % lang_code)
示例#8
0
 def delete(self, request, project_slug, resource_slug=None, api_version=1):
     """
     API call to delete resources via DELETE.
     """
     if resource_slug is None:
         return BAD_REQUEST("No resource provided.")
     return self._delete(request, project_slug, resource_slug)
示例#9
0
 def update(self, request, project_slug, resource_slug=None, api_version=1):
     """
     API call to update resource details via PUT
     """
     if resource_slug is None:
         return BAD_REQUEST("No resource specified in url")
     return self._update(request, project_slug, resource_slug)
示例#10
0
 def read(self, request, project_slug, release_slug=None, api_version=1):
     """
     Get details of a release.
     """
     try:
         return Release.objects.get(slug=release_slug,
                                    project__slug=project_slug)
     except Release.DoesNotExist:
         return BAD_REQUEST("Release %s.%s does not exist." %
                            (project_slug, release_slug))
示例#11
0
    def _create(self, request, data):
        """
        Create a new project.
        """
        mandatory_fields = (
            'slug',
            'name',
            'source_language_code',
        )
        msg = "Field '%s' is required to create a project."
        for field in mandatory_fields:
            if field not in data:
                return BAD_REQUEST(msg % field)
        if 'owner' in data:
            return BAD_REQUEST("Owner cannot be set explicitly.")

        try:
            self._check_fields(data.iterkeys())
        except AttributeError, e:
            return BAD_REQUEST("Field '%s' is not available." % e.message)
示例#12
0
 def read(self,
          request,
          project_slug,
          resource_slug,
          lang_code=None,
          api_version=1):
     """
     This is an API handler to display translation statistics for individual
     resources.
     """
     if api_version != 2:
         return BAD_REQUEST('Wrong API version called.')
     return self._get_stats(request, project_slug, resource_slug, lang_code)
示例#13
0
    def _update(self, request, project_slug, resource_slug, lang_code=None):
        # Permissions handling
        try:
            resource = Resource.objects.select_related('project').get(
                slug=resource_slug, project__slug=project_slug)
        except Resource.DoesNotExist:
            return rc.NOT_FOUND
        source_push = False
        if lang_code == "source":
            language = resource.source_language
            source_push = True
        else:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                logger.error("Weird! Selected language code (%s) does "
                             "not match with any language in the database." %
                             lang_code)
                return BAD_REQUEST(
                    "Selected language code (%s) does not match with any"
                    "language in the database." % lang_code)

        team = Team.objects.get_or_none(resource.project, lang_code)
        check = ProjectPermission(request.user)
        if source_push and not check.maintain(resource.project):
            return rc.FORBIDDEN
        elif (not check.submit_translations(team or resource.project) or\
            not resource.accept_translations) and not\
                check.maintain(resource.project):
            return rc.FORBIDDEN

        try:
            t = Translation.get_object("create", request, resource, language)
            res = t.create()
        except BadRequestError, e:
            return BAD_REQUEST(unicode(e))
示例#14
0
 def _read(self, request, project_slug):
     """
     Return a list of projects or the details for a specific project.
     """
     if project_slug is None:
         # Use pagination
         p = Project.objects.for_user(request.user)
         res, msg = paginate(p, request.GET.get('start'),
                             request.GET.get('end'))
         if res is None:
             return BAD_REQUEST(msg)
         return res
     else:
         try:
             p = Project.objects.get(slug=project_slug)
             perm = ProjectPermission(request.user)
             if not perm.private(p):
                 return rc.FORBIDDEN
         except Project.DoesNotExist:
             return rc.NOT_FOUND
         return p
示例#15
0
        try:
            self._check_fields(data.iterkeys(), self.written_fields)
        except AttributeError, e:
            return BAD_REQUEST("Field '%s' is not allowed." % e)

        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist:
            return rc.NOT_FOUND
        i18n_type = data.pop('i18n_type', None)

        try:
            resource = Resource.objects.get(project=project,
                                            slug=resource_slug)
        except Resource.DoesNotExist:
            return BAD_REQUEST("Resource %s does not exist" % resource_slug)
        try:
            for key, value in data.iteritems():
                setattr(resource, key, value)
            # if i18n_type is not None:
            #     resource.i18n_method = i18n_typ
            resource.full_clean()
            resource.save()
        except:
            return rc.BAD_REQUEST
        return rc.ALL_OK

    def _delete(self, request, project_slug, resource_slug):
        try:
            resource = Resource.objects.get(slug=resource_slug,
                                            project__slug=project_slug)
示例#16
0
class ProjectHandler(BaseHandler):
    """
    API handler for model Project.
    """
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
    details_fields = (
        'slug',
        'name',
        'description',
        'long_description',
        'homepage',
        'feed',
        'created',
        'anyone_submit',
        'bug_tracker',
        'trans_instructions',
        'tags',
        'outsource',
        ('maintainers', ('username', )),
        ('owner', ('username', )),
        ('resources', (
            'slug',
            'name',
        )),
        'teams',
        'source_language_code',
    )
    default_fields = (
        'slug',
        'name',
        'description',
        'source_language_code',
    )
    fields = default_fields
    allowed_fields = (
        'name',
        'slug',
        'description',
        'long_description',
        'private',
        'homepage',
        'feed',
        'anyone_submit',
        'hidden',
        'bug_tracker',
        'trans_instructions',
        'tags',
        'maintainers',
        'outsource',
        'source_language_code',
    )
    exclude = ()

    @classmethod
    def source_language_code(cls, p):
        """Add the source language as a field."""
        return p.source_language.code

    @classmethod
    def teams(cls, p):
        """Show the language codes for which there are teams as list.

        Return an empty list in case there are no teams defined.
        """
        team_set = get_project_teams(p)
        return team_set.values_list('language__code', flat=True)

    def read(self, request, project_slug=None, api_version=1):
        """
        Get project details in json format
        """
        # Reset fields to default value
        ProjectHandler.fields = ProjectHandler.default_fields
        if "details" in request.GET.iterkeys():
            if project_slug is None:
                return rc.NOT_IMPLEMENTED
            ProjectHandler.fields = ProjectHandler.details_fields
        return self._read(request, project_slug)

    @require_mime('json')
    @method_decorator(one_perm_required_or_403(pr_project_add))
    def create(self, request, project_slug=None, api_version=1):
        """
        API call to create new projects via POST.
        """
        data = getattr(request, 'data', None)
        if project_slug is not None:
            return BAD_REQUEST("POSTing to this url is not allowed.")
        if data is None:
            return BAD_REQUEST("At least parameters 'slug', 'name' and "
                               "'source_language' are needed.")
        return self._create(request, data)

    @require_mime('json')
    @method_decorator(
        one_perm_required_or_403(pr_project_add_change,
                                 (Project, 'slug__exact', 'project_slug')))
    def update(self, request, project_slug, api_version=1):
        """
        API call to update project details via PUT.
        """
        if project_slug is None:
            return BAD_REQUEST("Project slug not specified.")
        data = request.data
        if data is None:
            return BAD_REQUEST("Empty request.")
        return self._update(request, project_slug, data)

    @method_decorator(
        one_perm_required_or_403(pr_project_delete,
                                 (Project, 'slug__exact', 'project_slug')))
    def delete(self, request, project_slug=None, api_version=1):
        """
        API call to delete projects via DELETE.
        """
        if project_slug is None:
            return BAD_REQUEST("Project slug not specified.")
        return self._delete(request, project_slug)

    def _read(self, request, project_slug):
        """
        Return a list of projects or the details for a specific project.
        """
        if project_slug is None:
            # Use pagination
            p = Project.objects.for_user(request.user)
            res, msg = paginate(p, request.GET.get('start'),
                                request.GET.get('end'))
            if res is None:
                return BAD_REQUEST(msg)
            return res
        else:
            try:
                p = Project.objects.get(slug=project_slug)
                perm = ProjectPermission(request.user)
                if not perm.private(p):
                    return rc.FORBIDDEN
            except Project.DoesNotExist:
                return rc.NOT_FOUND
            return p

    def _create(self, request, data):
        """
        Create a new project.
        """
        mandatory_fields = (
            'slug',
            'name',
            'source_language_code',
        )
        msg = "Field '%s' is required to create a project."
        for field in mandatory_fields:
            if field not in data:
                return BAD_REQUEST(msg % field)
        if 'owner' in data:
            return BAD_REQUEST("Owner cannot be set explicitly.")

        try:
            self._check_fields(data.iterkeys())
        except AttributeError, e:
            return BAD_REQUEST("Field '%s' is not available." % e.message)

        # outsource and maintainers are ForeignKey
        outsource = data.pop('outsource', {})
        maintainers = data.pop('maintainers', {})

        lang = data.pop('source_language_code')
        try:
            source_language = Language.objects.by_code_or_alias(lang)
        except Language.DoesNotExist:
            return BAD_REQUEST("Language %s does not exist." % lang)

        try:
            p = Project(**data)
            p.source_language = source_language
        except Exception:
            return BAD_REQUEST("Invalid arguments given.")
        try:
            p.full_clean()
        except ValidationError, e:
            return BAD_REQUEST("%s" % e)
示例#17
0
 def _update(self, request, project_slug, data):
     try:
         self._check_fields(data.iterkeys(), extra_exclude=['slug'])
     except AttributeError, e:
         return BAD_REQUEST("Field '%s' is not available." % e)
示例#18
0
class TranslationHandler(BaseHandler):
    allowed_methods = (
        'GET',
        'PUT',
        'DELETE',
    )

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(
        one_perm_required_or_403(pr_project_private_perm,
                                 (Project, 'slug__exact', 'project_slug')))
    def read(self,
             request,
             project_slug,
             resource_slug,
             lang_code=None,
             is_pseudo=None,
             api_version=2):
        return self._read(request, project_slug, resource_slug, lang_code,
                          is_pseudo)

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    def update(self,
               request,
               project_slug,
               resource_slug,
               lang_code,
               api_version=2):
        return self._update(request, project_slug, resource_slug, lang_code)

    @method_decorator(
        one_perm_required_or_403(pr_resource_translations_delete,
                                 (Project, "slug__exact", "project_slug")))
    def delete(self,
               request,
               project_slug,
               resource_slug,
               lang_code=None,
               api_version=2):
        return self._delete(request, project_slug, resource_slug, lang_code)

    def _read(self, request, project_slug, resource_slug, lang_code,
              is_pseudo):
        try:
            r = Resource.objects.get(slug=resource_slug,
                                     project__slug=project_slug)
        except Resource.DoesNotExist:
            return rc.NOT_FOUND

        if lang_code == "source":
            language = r.source_language
        else:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                return rc.NOT_FOUND

        # Check whether the request asked for a pseudo file, if so check if
        # a ``pseudo_type`` GET var was passed with a valid pseudo type.
        if is_pseudo:
            ptype = request.GET.get('pseudo_type', None)
            if not ptype in settings.PSEUDO_TYPES.keys():
                return rc.NOT_FOUND
            # Instantiate Pseudo type object
            pseudo_type = get_pseudo_class(ptype)(r.i18n_type)
        else:
            pseudo_type = None

        # Get the mode the user requested, if any
        mode = request.GET.get('mode', None)
        if mode is not None:
            try:
                mode = getattr(Mode, mode.upper())
            except AttributeError, e:
                return BAD_REQUEST(unicode(e))

        translation = Translation.get_object("get", request, r, language)
        try:
            res = translation.get(pseudo_type=pseudo_type, mode=mode)
        except BadRequestError, e:
            return BAD_REQUEST(unicode(e))
示例#19
0
        try:
            p.full_clean()
        except ValidationError, e:
            return BAD_REQUEST("%s" % e)
        try:
            p.save()
        except IntegrityError:
            return rc.DUPLICATE_ENTRY

        p.owner = request.user
        if outsource:
            try:
                outsource_project = Project.objects.get(slug=outsource)
            except Project.DoesNotExist:
                p.delete()
                return BAD_REQUEST("Project for outsource does not exist.")
            p.outsource = outsource_project

        if maintainers:
            for user in maintainers.split(','):
                try:
                    u = User.objects.get(username=user)
                except User.DoesNotExist:
                    p.delete()
                    return BAD_REQUEST("User %s does not exist." % user)
                p.maintainers.add(u)
        else:
            p.maintainers.add(p.owner)
        p.save()
        return rc.CREATED