Exemplo n.º 1
0
def dump_app(id, **kw):
    from mkt.webapps.serializers import AppSerializer
    # Because @robhudson told me to.
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = RESTOFWORLD

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppSerializer(obj, context={'request': req}).data
    json.dump(res, open(target_file, 'w'), cls=JSONEncoder)
    return target_file
Exemplo n.º 2
0
 def serialize(self, app, profile=None, region=None, request=None):
     if request is None:
         request = self.request
     request.amo_user = self.profile
     request.REGION = region
     a = AppSerializer(instance=app, context={'request': request})
     return a.data
Exemplo n.º 3
0
 def get_apps(self, obj):
     """
     Return a list of serialized apps, adding each app's `group` to the
     serialization.
     """
     ret = []
     memberships = FeedCollectionMembership.objects.filter(obj_id=obj.id)
     field = TranslationSerializerField()
     field.initialize(self, 'group')
     field.context = self.context
     for member in memberships:
         data = AppSerializer(member.app, context=self.context).data
         data['group'] = field.field_to_native(member, 'group')
         ret.append(data)
     return ret
Exemplo n.º 4
0
 def get_apps(self, obj):
     """
     Return a list of serialized apps, adding each app's `group` to the
     serialization.
     """
     ret = []
     memberships = FeedShelfMembership.objects.filter(obj_id=obj.id)
     field = TranslationSerializerField()
     field.bind('group', self)
     field.context = self.context
     for member in memberships:
         data = AppSerializer(member.app, context=self.context).data
         data['group'] = field.to_representation(
             field.get_attribute(member))
         ret.append(data)
     return ret
Exemplo n.º 5
0
    def create(self, request, *args, **kwargs):
        uuid = request.data.get('upload', '')
        if uuid:
            is_packaged = True
        else:
            uuid = request.data.get('manifest', '')
            is_packaged = False
        if not uuid:
            raise exceptions.ParseError(
                'No upload or manifest specified.')

        try:
            upload = FileUpload.objects.get(uuid=uuid)
        except FileUpload.DoesNotExist:
            raise exceptions.ParseError('No upload found.')
        if not upload.valid:
            raise exceptions.ParseError('Upload not valid.')

        if not request.user.read_dev_agreement:
            log.info(u'Attempt to use API without dev agreement: %s'
                     % request.user.pk)
            raise exceptions.PermissionDenied('Terms of Service not accepted.')
        if not (upload.user and upload.user.pk == request.user.pk):
            raise exceptions.PermissionDenied('You do not own that app.')

        # Create app, user and fetch the icon.
        try:
            obj = Webapp.from_upload(upload, is_packaged=is_packaged)
        except (serializers.ValidationError,
                django_forms.ValidationError) as e:
            raise exceptions.ParseError(unicode(e))
        AddonUser(addon=obj, user=request.user).save()
        tasks.fetch_icon.delay(obj.pk, obj.latest_version.all_files[0].pk)
        record_action('app-submitted', request, {'app-id': obj.pk})
        log.info('App created: %s' % obj.pk)
        data = AppSerializer(
            context=self.get_serializer_context(), instance=obj).data

        return response.Response(
            data, status=201,
            headers={'Location': reverse('app-detail', kwargs={'pk': obj.pk})})
Exemplo n.º 6
0
def dump_app(id, **kw):
    from mkt.webapps.serializers import AppSerializer
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = RESTOFWORLD

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppSerializer(obj, context={'request': req}).data
    with private_storage.open(target_file, 'w') as fileobj:
        json.dump(res, fileobj, cls=JSONEncoder)
    return target_file
Exemplo n.º 7
0
class FeedAppSerializer(ValidateSlugMixin, URLSerializerMixin,
                        serializers.ModelSerializer):
    """
     A serializer for the FeedApp class, which highlights a single app and some
    additional metadata (e.g. a review or a screenshot).
    """
    app = SplitField(
        relations.PrimaryKeyRelatedField(required=True,
                                         queryset=Webapp.objects),
        AppSerializer())
    background_image = FeedImageField(allow_null=True)
    description = TranslationSerializerField(required=False)
    preview = SplitField(
        relations.PrimaryKeyRelatedField(required=False,
                                         queryset=Preview.objects),
        FeedPreviewESSerializer())
    pullquote_rating = serializers.IntegerField(required=False,
                                                max_value=5,
                                                min_value=1)
    pullquote_text = TranslationSerializerField(required=False)

    class Meta:
        fields = ('app', 'background_color', 'background_image', 'color',
                  'created', 'description', 'id', 'preview',
                  'pullquote_attribution', 'pullquote_rating',
                  'pullquote_text', 'slug', 'type', 'url')
        model = FeedApp
        url_basename = 'feedapps'

    def validate(self, attrs):
        """
        Require `pullquote_text` if `pullquote_rating` or
        `pullquote_attribution` are set.
        """
        if (not attrs.get('pullquote_text')
                and (attrs.get('pullquote_rating')
                     or attrs.get('pullquote_attribution'))):
            raise ValidationError('Pullquote text required if rating or '
                                  'attribution is defined.')
        return attrs
Exemplo n.º 8
0
class FeedAppSerializer(URLSerializerMixin, serializers.ModelSerializer):
    """
    A serializer for the FeedApp class, which highlights a single app and some
    additional metadata (e.g. a review or a screenshot).
    """
    app = SplitField(relations.PrimaryKeyRelatedField(required=True),
                     AppSerializer())
    description = TranslationSerializerField(required=False)
    background_image = CollectionImageField(
        source='*', view_name='api-v2:feed-app-image-detail', format='png')
    preview = SplitField(relations.PrimaryKeyRelatedField(required=False),
                         PreviewSerializer())
    pullquote_rating = serializers.IntegerField(required=False)
    pullquote_text = TranslationSerializerField(required=False)

    class Meta:
        fields = ('app', 'background_color', 'created', 'description',
                  'feedapp_type', 'id', 'background_image', 'preview',
                  'pullquote_attribution', 'pullquote_rating',
                  'pullquote_text', 'slug', 'url')
        model = FeedApp
        url_basename = 'feedapps'
Exemplo n.º 9
0
 def serialize(self, app, profile=None):
     self.request.amo_user = profile
     a = AppSerializer(instance=app, context={'request': self.request})
     return a.data
Exemplo n.º 10
0
 def app(self):
     return AppSerializer(self.webapp, context={'request': self.request})
Exemplo n.º 11
0
 def serialize(self, app, profile=None):
     self.request.user = profile if profile else AnonymousUser()
     a = AppSerializer(instance=app, context={'request': self.request})
     return a.data
Exemplo n.º 12
0
 def to_representation(self, qs, use_es=False):
     return AppSerializer(qs, context=self.context).data
Exemplo n.º 13
0
 def to_native(self, qs, use_es=False):
     return AppSerializer(qs, context=self.context).data