Exemplo n.º 1
0
class CaptureJobResource(DefaultResource):
    guid = fields.CharField(attribute='link_id')
    status = fields.CharField(attribute='status')
    attempt = fields.IntegerField(attribute='attempt')
    step_count = fields.FloatField(attribute='step_count')
    step_description = fields.CharField(attribute='step_description',
                                        blank=True,
                                        null=True)
    capture_start_time = fields.DateTimeField(attribute='capture_start_time',
                                              blank=True,
                                              null=True)
    capture_end_time = fields.DateTimeField(attribute='capture_end_time',
                                            blank=True,
                                            null=True)

    # calculated fields
    queue_position = fields.DateTimeField(attribute='queue_position')

    class Meta(DefaultResource.Meta):
        resource_name = 'capture_jobs'
        queryset = CaptureJob.objects.all()
        detail_uri_name = 'link_id'

    def prepend_urls(self):
        """ URLs should match on CaptureJob.link_id as well as CaptureJob.id. """
        return [
            url(r"^(?P<resource_name>%s)/(?P<link_id>[\w\d-]+)/?$" %
                self._meta.resource_name,
                self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail"),
        ]
Exemplo n.º 2
0
class ProjectResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user', full=True)
    template = fields.ForeignKey(TemplateResource, 'template', full=True)
    uuid = fields.CharField(readonly=True)
    created = fields.DateTimeField(readonly=True)
    modified = fields.DateTimeField(readonly=True)

    def get_object_list(self, request):
        """List only ``User`` owned templates"""
        if not hasattr(request, 'user'):
            return Project.objects.none()
        return (super(ProjectResource,
                      self).get_object_list(request).filter(user=request.user))

    def hydrate_user(self, bundle):
        bundle.data['user'] = bundle.request.user
        return bundle

    class Meta:
        queryset = Project.objects.filter(status=Project.LIVE)
        resource_name = 'project'
        fields = [
            'uuid', 'name', 'metadata', 'html', 'created', 'modified', 'user',
            'template'
        ]
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'patch']
        authentication = InternalApiKeyAuthentication()
        authorization = OwnerAuthorization()
        validation = CustomFormValidation(form_class=ProjectAPIForm)
Exemplo n.º 3
0
class PostResource(CodrspaceModelResource):
    # make sure these don't get set. The Django
    # model system will take care of it
    create_dt = fields.DateTimeField(attribute='create_dt', readonly=True)
    update_dt = fields.DateTimeField(attribute='update_dt', readonly=True)

    class Meta:
        resource_name = 'post'
        queryset = Post.objects.all()
        queryset = queryset.order_by('-publish_dt')
        allowed_methods = ['get', 'put', 'delete', 'post']
        authentication = ApiKeyAuthentication()
        authorization = CodrspaceAuthorization()
        serializer = Serializer(formats=['json'])
        validation = PostValidation(form_class=APIPostForm)
        always_return_data = True
        filtering = {"slug": ALL}

    def dehydrate(self, bundle):
        bundle.data['url'] = bundle.obj.url()
        return bundle

    def hydrate(self, bundle, request=None):
        # set the status if it is not specified
        if not bundle.obj.status:
            bundle.obj.status = "draft"

        # automatically set the author
        bundle.obj.author = User.objects.get(pk=bundle.request.user.id)

        return bundle
Exemplo n.º 4
0
class AnalysisResource(ModelResource):
    data_set = fields.ToOneField(DataSetResource, 'data_set', use_in='detail')
    uuid = fields.CharField(attribute='uuid', use_in='all')
    name = fields.CharField(attribute='name', use_in='all')
    creation_date = fields.CharField(attribute='creation_date', use_in='all')
    workflow_steps_num = fields.IntegerField(attribute='workflow_steps_num',
                                             blank=True, null=True, use_in='detail')
    workflow_copy = fields.CharField(attribute='workflow_copy',
                                     blank=True, null=True, use_in='detail')
    history_id = fields.CharField(attribute='history_id', blank=True, null=True,
                                  use_in='detail')
    workflow_galaxy_id = fields.CharField(attribute='workflow_galaxy_id',
                                          blank=True, null=True, use_in='detail')
    library_id = fields.CharField(attribute='library_id', blank=True, null=True,
                                  use_in='detail')
    time_start = fields.DateTimeField(attribute='time_start', blank=True, null=True,
                                      use_in='detail')
    time_end = fields.DateTimeField(attribute='time_end', blank=True, null=True,
                                    use_in='detail')
    status = fields.CharField(attribute='status', default=Analysis.INITIALIZED_STATUS,
                              blank=True, null=True, use_in='detail')

    class Meta:
        queryset = Analysis.objects.all()
        resource_name = Analysis._meta.module_name
        detail_uri_name = 'uuid'    # for using UUIDs instead of pk in URIs
        authentication = SessionAuthentication()
        authorization = GuardianAuthorization()
        allowed_methods = ["get"]
        fields = ['data_set', 'creation_date', 'history_id', 'library_id', 'name',
                'resource_uri', 'status', 'time_end', 'time_start', 'uuid',
                'workflow_copy', 'workflow_galaxy_id', 'workflow_steps_num']
        filtering = {'data_set': ALL_WITH_RELATIONS}
        ordering = ['name', 'creation_date']
Exemplo n.º 5
0
class ConfigureSensorTaskResource(resources.ModelResource):
    sensor_id = fields.IntegerField()
    sensor_name = fields.CharField()
    created = fields.DateTimeField('created', null=True, readonly=True)
    started = fields.DateTimeField('started', null=True, readonly=True)
    first_discovery = fields.DateTimeField('first_discovery', null=True, readonly=True)
    last_discovery = fields.DateTimeField('last_discovery', null=True, readonly=True)
    finished = fields.DateTimeField('finished', null=True, readonly=True)
    error = fields.CharField('error', null=True, readonly=True)

    class Meta(ResourceMetaCommon):
        queryset = ConfigureSensorTask.objects.select_related('sensor')
        authorization = ConfigureSensorTaskAuthorization()
        detail_allowed_methods = ['get']
        list_allowed_methods = ['post']
        fields = ['id']

    def obj_create(self, bundle, **kwargs):
        if 'sensor_name' in bundle.data:
            sensor_id = (set(range(1, 128)) - set([s.pk for s in Sensor.objects.all()])).pop()
            sensor = Sensor.objects.create(
                    id=sensor_id,
                    name=bundle.data['sensor_name'],
                    )
        else:
            sensor = Sensor.objects.get(pk=bundle.data['sensor_id'])

        return super().obj_create(bundle, sensor=sensor)

    def dehydrate(self, bundle):
        bundle.data['sensor_id'] = bundle.obj.sensor.id
        bundle.data['sensor_name'] = bundle.obj.sensor.name

        return bundle
Exemplo n.º 6
0
class UsersResource(ModelResource):
    since = fields.DateTimeField(attribute='since', default=datetime(1, 1, 1))
    birthday = fields.DateTimeField(attribute='since',
                                    default=datetime(1, 1, 1))

    class Meta:
        queryset = Users.objects.all()
        excludes = ['password', 'email']
        allowed_methods = ['get']
        authorization = Authorization()
        paginator_class = IDPaginator
        max_limit = 100
Exemplo n.º 7
0
class SentencesResource(ModelResource):
    created = fields.DateTimeField(attribute='created',
                                   default=datetime(1, 1, 1))
    modified = fields.DateTimeField(attribute='modified',
                                    default=datetime(1, 1, 1))
    text = UCharField(attribute='text')

    class Meta:
        queryset = Sentences.objects.all()
        allowed_methods = ['get']
        excludes = ['dico_id']
        authorization = Authorization()
        paginator_class = IDPaginator
        max_limit = 100
Exemplo n.º 8
0
class BugTrackerBugResource(CommonResource):
    """API Resource for 'BugTrackerBug' model. """

    bug = ReverseOneField('oilserver.api.resources.BugResource', 'bug')
    project = ForeignKey(ProjectResource, 'project', full_list=True)
    created_at = fields.DateTimeField('created_at', readonly=True)
    updated_at = fields.DateTimeField('updated_at', readonly=True)

    class Meta(CommonMeta):
        queryset = models.BugTrackerBug.objects.select_related('project').all()
        excludes = ['id']
        filtering = {
            'bug_number': ALL,
            'bug': ALL_WITH_RELATIONS, }
        detail_uri_name = 'bug_number'
Exemplo n.º 9
0
class BugOccurrenceResource(CommonResource):
    """API Resource for 'BugTrackerBug' model. """

    knownbugregex = ForeignKey(
        KnownBugRegexResource, 'knownbugregex', full_list=True)
    testcaseinstance = ForeignKey(TestCaseInstanceResource, 'testcaseinstance')
    created_at = fields.DateTimeField('created_at', readonly=True)
    updated_at = fields.DateTimeField('updated_at', readonly=True)

    class Meta(CommonMeta):
        queryset = models.BugOccurrence.objects.select_related(
            'knownbugregex', 'testcaseinstance').all()
        excludes = []
        filtering = {'uuid': ALL,
                     'knownbugregex': ALL_WITH_RELATIONS,
                     'testcaseinstance': ALL_WITH_RELATIONS, }

    def occurrences_for_bug_filters(self, bundle):
        """Get the bug occurrences that match a bug's filter.

        When bugs are found by bug occurrence properties, this matches
        bug occurrences that match those properties. So if we filter for
        bugs with occurrences in pipelines that completed in 2015, only
        the bug occurrences that completed in 2015 will be included.

        Args:
            bundle: The tastypie bundle.
        """
        query_dict = bundle.request.GET
        replace_prefix = 'knownbugregexes__bugoccurrences__'
        bugoccurrence_filters = {}
        for key, value in query_dict.items():
            # remove prefixes from each OR portion of each key
            filter_name = '|'.join(
                [k.replace(replace_prefix, '')
                 for k in key.split('|') if k.startswith(replace_prefix)])

            if filter_name.endswith('__in'):
                # __in defines a list of possible entries, so get a list back.
                # Tastypie expects this to be a string joined by commas
                # our workaround for OR filters does not.
                value = bundle.request.GET.getlist(key)
                if '|' not in key:
                    value = ','.join(value)
            bugoccurrence_filters[filter_name] = value
        bugoccurrence_filters['knownbugregex__bug__uuid'] = bundle.obj.uuid
        built_filters = self.build_filters(filters=bugoccurrence_filters)
        return self.apply_filters(None, built_filters).distinct()
Exemplo n.º 10
0
class ReservationCount(Resource):
    count = fields.IntegerField(readonly=True)
    reservation_begins = fields.DateTimeField(readonly=True)

    class Meta:
        resource_name = 'reservation_count'
        allowed_methods = 'get'

    def dehydrate_count(self, bundle):
        return bundle.obj['reservation_begins__count']

    def dehydrate_reservation_begins(self, bundle):
        base_date = bundle.obj['reservation_begins']
        return timezone.localtime(base_date, timezone.get_default_timezone())

    def obj_get(self, request, **kwargs):
        #Information can only be obtained if asking for a list
        return {'reservation_begins': '', 'reservation_begins__count': ''}

    def obj_get_list(self, request, **kwargs):
        asset_id = request.GET.get('asset', None)
        ret = Reservation.objects.filter(asset__id=asset_id)

        try:
            date = datetime.strptime(request.GET.get('date', None), '%Y-%m-%d')
            ret = ret.filter(
                Q(reservation_begins__gte=date)
                & Q(reservation_begins__lt=(date + timedelta(1))))
        except:
            return []

        ret = ret.values('reservation_begins').order_by('reservation_begins')
        ret = ret.annotate(Count('reservation_begins'))
        return ret
Exemplo n.º 11
0
class ComboResource(MongoDBResource):
    id = fields.CharField(attribute="_id")
    frontend_id = fields.CharField(attribute="frontend_id")
    thug = fields.DictField(attribute="thug", null=True)
    timestamp = fields.DateTimeField(attribute="timestamp")
    connections = fields.ListField(attribute="connections")
    exploits = fields.ListField(attribute="exploits")
    behaviors = fields.ListField(attribute="behaviors")
    codes = fields.ListField(attribute="codes")
    maec11 = fields.ListField(attribute="maec11")
    certificates = fields.ListField(attribute="certificates")
    url_map = fields.ListField(attribute="url_map")
    locations = fields.ListField(attribute="locations")
    samples = fields.ListField(attribute="samples")
    virustotal = fields.ListField(attribute="virustotal")
    honeyagent = fields.ListField(attribute="honeyagent")
    androguard = fields.ListField(attribute="androguard")
    peepdf = fields.ListField(attribute="peepdf")
    url_map = fields.ListField(attribute="url_map")
    flat_tree = fields.ListField(attribute="flat_tree")
    pcaps = fields.ListField(attribute="pcaps")

    class Meta:
        resource_name = 'analysiscombo'
        authentication = ApiKeyAuthentication()
        object_class = Document
        collection = "analysiscombo"
        detail_uri_name = "_id"
        excludes = [
            "id",
        ]
        include_resource_uri = False
Exemplo n.º 12
0
class QuotesResource(Resource):
    """ Quotes resource """

    date = fields.DateTimeField(attribute='date', null=True)
    symbol = fields.CharField(attribute='symbol', null=True)
    price = fields.DecimalField(attribute='price', null=True)
    volume = fields.DecimalField(attribute='volume', null=True)
    type = fields.CharField(attribute='type', null=True)

    def base_urls(self):
        return []

    def override_urls(self):
        return [
            url(r"^symbols/(?P<symbol>[^/]+)/(?P<resource_name>%s)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('dispatch_list'),
                name="api_quotes_list"),
        ]

    def obj_get_list(self, request=None, **kwargs):
        symbol = 'symbol_{0}'.format(kwargs.get('symbol').upper())
        redis = RedisDB()
        json = '[{0}]'.format(','.join(redis.lrange(symbol, 0, 1000)))

        quote_type = request.GET.get('type', 'ask')
        objs = [Quote(quote_type, **x) for x in simplejson.loads(json)]
        return objs

    class Meta:
        resource_name = 'quotes'
        list_allowed_methods = [
            'get',
        ]
        filtering = {"type": ALL_WITH_RELATIONS}
Exemplo n.º 13
0
class FullStockTransactionResource(StockTransactionResource):
    """
    This is the one that's actually used in the stock transaction API,
    since it adds other fields from the stock report.
    """
    location_id = fields.CharField(attribute='location_id', readonly=True)
    received_on = fields.DateTimeField(attribute='received_on', readonly=True)
Exemplo n.º 14
0
class TimelineEntryBaseResource(TenantResource):
    module = base_fields.CharField(
        attribute='module', help_text=HELP_TEXT['timeline_entry']['module'])
    datetime = base_fields.DateTimeField(
        attribute='datetime',
        help_text=HELP_TEXT['timeline_entry']['datetime'])
    issuer_name = base_fields.CharField(
        attribute='issuer__get_full_name',
        help_text=HELP_TEXT['entity_saved']['contact'],
        null=True,
    )

    issuer = fields.ReferenceField(
        to='core.api.resources.VosaeUserResource',
        attribute='issuer',
        blank=True,
        null=True,
        help_text=HELP_TEXT['timeline_entry']['issuer'])

    class Meta(TenantResource.Meta):
        object_class = TimelineEntry
        excludes = ('tenant', 'access_permission', 'see_permission')
        list_allowed_methods = ('get', )
        detail_allowed_methods = ('get', )

    def get_object_list(self, request):
        object_list = super(TimelineEntryBaseResource,
                            self).get_object_list(request)
        if request and getattr(request, 'vosae_user', None):
            return object_list.filter(
                access_permission__in=request.vosae_user.permissions.
                access_perms,
                see_permission__in=request.vosae_user.permissions.see_perms)
        return object_list
Exemplo n.º 15
0
class AuthenticatedLinkResource(BaseLinkResource):
    notes = fields.CharField(attribute='notes', blank=True)
    created_by = fields.ForeignKey(LinkUserResource,
                                   'created_by',
                                   full=True,
                                   null=True,
                                   blank=True,
                                   readonly=True)

    is_private = fields.BooleanField(attribute='is_private')
    private_reason = fields.CharField(attribute='private_reason',
                                      blank=True,
                                      null=True)
    archive_timestamp = fields.DateTimeField(attribute='archive_timestamp',
                                             readonly=True)
    organization = fields.ForeignKey(OrganizationResource,
                                     'organization',
                                     full=True,
                                     blank=True,
                                     null=True,
                                     readonly=True)

    class Meta(BaseLinkResource.Meta):
        authorization = AuthenticatedLinkAuthorization()
        queryset = BaseLinkResource.Meta.queryset.select_related(
            'created_by', )
        allowed_update_fields = [
            'title', 'notes', 'is_private', 'private_reason', 'folder', 'file'
        ]

    def get_search_filters(self, search_query):
        return (super(AuthenticatedLinkResource,
                      self).get_search_filters(search_query)
                | Q(notes__icontains=search_query))
Exemplo n.º 16
0
class ProductResource(HqBaseResource):

    type = "product"
    id = fields.CharField(attribute='_id', readonly=True, unique=True)
    code = fields.CharField(attribute='code', readonly=True, unique=True)
    name = fields.CharField(attribute='name', readonly=True)
    unit = fields.CharField(attribute='unit', readonly=True, null=True)
    description = fields.CharField(attribute='description',
                                   readonly=True,
                                   null=True)
    category = fields.CharField(attribute='category', readonly=True, null=True)
    last_modified = fields.DateTimeField(attribute='last_modified',
                                         readonly=True,
                                         null=True)

    # TODO:
    # price?

    def obj_get(self, request, **kwargs):
        return get_object_or_not_exist(Product, kwargs['pk'], kwargs['domain'])

    def obj_get_list(self, request, **kwargs):
        return Product.by_domain(kwargs['domain'])

    class Meta(CustomResourceMeta):
        authentication = DomainAdminAuthentication()
        resource_name = 'product'
        limit = 0
Exemplo n.º 17
0
class EventResource(MyResource):
    user = fields.ForeignKey(UserResource, 'user')
    time = fields.DateTimeField('time')
    collection = fields.ForeignKey(CollectionResource, 'collection')

    class Meta():
        queryset = Event.objects.all()
Exemplo n.º 18
0
class NotificationBaseResource(TenantResource):
    sent_at = base_fields.DateTimeField(
        attribute='sent_at',
        readonly=True,
        help_text=HELP_TEXT['notification_base']['sent_at']
    )
    read = base_fields.BooleanField(
        attribute='read',
        readonly=True,
        help_text=HELP_TEXT['notification_base']['read']
    )

    issuer = fields.ReferenceField(
        to='core.api.resources.VosaeUserResource',
        attribute='issuer',
        readonly=True,
        null=True,
        help_text=HELP_TEXT['notification_base']['issuer']
    )

    class Meta(TenantResource.Meta):
        object_class = Notification
        excludes = ('tenant', 'recipient')
        list_allowed_methods = ('get',)
        detail_allowed_methods = ('get',)

    def get_object_list(self, request):
        """Filters the notifications list on the recipient (extracted from request)"""
        return super(NotificationBaseResource, self).get_object_list(request).filter(recipient=request.vosae_user)
Exemplo n.º 19
0
class InvoiceNoteResource(VosaeResource):
    datetime = base_fields.DateTimeField(
        attribute='datetime',
        readonly=True,
        help_text=HELP_TEXT['invoice_note']['datetime']
    )
    note = base_fields.CharField(
        attribute='note',
        help_text=HELP_TEXT['invoice_note']['note']
    )

    issuer = fields.ReferenceField(
        to='core.api.resources.VosaeUserResource',
        attribute='issuer',
        readonly=True,
        help_text=HELP_TEXT['invoice_note']['issuer']
    )

    class Meta(VosaeResource.Meta):
        object_class = InvoiceNote

    def full_hydrate(self, bundle):
        """Set issuer on POST, extracted from request"""
        bundle = super(InvoiceNoteResource, self).full_hydrate(bundle)
        if bundle.request.method.lower() == 'post':
            bundle.obj.issuer = bundle.request.vosae_user
        return bundle
Exemplo n.º 20
0
class SBIResource(SimpleResource):
    text = fields.CharField(readonly=True, attribute='text')
    valid = fields.DateTimeField(readonly=True, attribute='valid', null=True)
    expires = fields.DateField(readonly=True, attribute='expires', null=True)
    accepted = fields.DateField(readonly=True, attribute='accepted', null=True)

    class Meta(SimpleResource.Meta):
        resource_name = 'sbi'
        allowed_methods = ['get']
        list_allowed_methods = ['post']

    def obj_create(self, bundle, request, **kwargs):
        form = SBIForm(bundle.data)
        if not form.is_valid():
            raise self.form_errors(form)

        try:
            res = self.client('AcceptSBIAgreement',
                              form.bango_data,
                              raise_on=(SBI_ALREADY_ACCEPTED))
        except BangoFormError, exc:
            if exc.id != SBI_ALREADY_ACCEPTED:
                raise

        res = self.client('GetAcceptedSBIAgreement', form.bango_data)
        seller_bango = form.cleaned_data['seller_bango']
        seller_bango.sbi_expires = res.sbiAgreementExpires
        seller_bango.save()

        bundle.obj = SBIAgreement('', None, res.acceptedSBIAgreement,
                                  res.sbiAgreementExpires)
        return bundle
Exemplo n.º 21
0
class CommentResource(ActivityGenericResource):
    task = fields.ForeignKey(TaskResource, 'task', null=True)
    post = fields.ForeignKey(PostResource, 'post', null=True)
    username = fields.CharField(readonly=True)
    avatar = fields.CharField(readonly=True)
    created = fields.DateTimeField(attribute='created', readonly=True)

    # Relations
    project_part = fields.ForeignKey(ProjectPartResource,
                                     'project_part',
                                     null=True)

    class Meta(GenericMeta):
        queryset = Comment.objects.all()
        resource_name = 'comment'
        filtering = {'project_part': ALL, 'task': ALL, 'post': ALL}
        serializer = DatetimeSerializer()
        authorization = CommentAuthorization()
        validation = CommentValidation()

    def obj_create(self, bundle, **kwargs):
        created = now()
        return super(CommentResource,
                     self).obj_create(bundle,
                                      created=created,
                                      created_user=bundle.request.user)

    def dehydrate_username(self, bundle):
        return " ".join([
            bundle.obj.created_user.first_name,
            bundle.obj.created_user.last_name
        ])

    def dehydrate_avatar(self, bundle):
        return bundle.obj.created_user.profile.get_image_profile()
Exemplo n.º 22
0
class LtgResource(ModelResource):
    '''
    abstract class with commone attribute common to all my rest models
    '''
    creation_date = fields.DateTimeField(attribute='creation_date',
                                         readonly=True)
    modified_data = fields.DateTimeField(attribute='modified_data',
                                         readonly=True)

    #set read only fields
    class Meta:
        allowed_methods = ['get']
        always_return_data = True
        ordering = ['creation_date', 'modified_date']
        serializer = MyDateSerializer()

    @staticmethod
    def get_pk_from_uri(uri):
        '''
        gets a uri and return the pk from the url
        @param uri: the url
        @return: string the pk 
        '''

        prefix = get_script_prefix()
        chomped_uri = uri

        if prefix and chomped_uri.startswith(prefix):
            chomped_uri = chomped_uri[len(prefix) - 1:]

        try:
            view, args, kwargs = resolve(chomped_uri)
        except:
            return 0

        return kwargs['pk']

    def obj_create(self, bundle, **kwargs):
        '''
        if the subclass has an attr of 'user', create the resource with the request.user as the user for the resource
        '''
        if hasattr(self, 'user'):
            return super(LtgResource,
                         self).obj_create(bundle, user=bundle.request.user)
        else:
            return super(LtgResource, self).obj_create(bundle)
        return bundle
Exemplo n.º 23
0
class LayerResource(ModelResource):
    """
    A resource representing a Layer.
    """
    bbox = fields.CharField(readonly=True)
    created_dttm = fields.DateTimeField(readonly=True)
    is_public = fields.BooleanField(readonly=True)
    keywords = fields.ToManyField(TagResource, 'keywords', full=True)
    owner_username = fields.CharField(readonly=True)
    topic_category = fields.CharField(readonly=True)

    def dehydrate_created_dttm(self, bundle):
        # TODO maybe implement created_dttm in GeoNode? For now let's set it to Date, but it is not the same thing
        return bundle.obj.date

    def dehydrate_bbox(self, bundle):
        return bundle.obj.bbox

    def dehydrate_topic_category(self, bundle):
        if bundle.obj.category:
            return bundle.obj.category.gn_description
        else:
            return None

    def dehydrate_owner_username(self, bundle):
        return bundle.obj.owner.username

    def dehydrate_is_public(self, bundle):
        # TODO implement this with new permission system
        # return bundle.request.user.has_perm('maps.view_layer', obj=bundle.obj)
        return True

    class Meta:
        queryset = Layer.objects.all()
        allowed_methods = [
            'get',
        ]
        ordering = [
            'date',
        ]
        fields = [
            'abstract',
            'bbox',
            'created_dttm',
            'date',
            'date_type',
            'is_public',
            'keywords',
            'name',
            'owner_username',
            'srs',
            'temporal_extent_end',
            'temporal_extent_start',
            'title',
            'topic_category',
            'typename',
            'uuid',
        ]
Exemplo n.º 24
0
class PositionUpdateResource(LoggedMixin, resources.ModelResource):
    spectator = fields.ToOneField(SpectatorResource, 'spectator')
    spectator_guid = fields.CharField(attribute='spectator__guid',
                                      readonly=True)
    spectator_name = fields.CharField(attribute='spectator__name',
                                      readonly=True)
    server_created_date = fields.DateTimeField(attribute='server_created_date',
                                               readonly=True)
    server_updated_date = fields.DateTimeField(attribute='server_updated_date',
                                               readonly=True)

    def hydrate(self, bundle):
        if ("spectator"
                not in bundle.data) and (not hasattr(bundle.obj, "spectator")):
            if "spectator_id" in bundle.data:
                bundle.obj.spectator_id = bundle.data["spectator_id"]
            elif "spectator_guid" in bundle.data:
                bundle.obj.spectator = Spectator.objects.get(
                    guid=bundle.data["spectator_guid"])
            else:
                bundle.obj.spectator, created = Spectator.objects.get_or_create(
                    user=bundle.request.user,
                    defaults={
                        "name": "Participant %d" % bundle.request.user.id
                    })
        return bundle

    class Meta:
        queryset = PositionUpdate.objects.select_related('spectator').order_by(
            "-time")
        resource_name = 'positionupdate'
        fields = ['id', 'guid', 'time', 'latitude', 'longitude', 'accuracy']
        allowed_methods = ['get', 'put', 'post', 'delete']
        authentication = LoggedMultiAuthentication()
        authorization = PositionUpdateAuthorization()
        filtering = {
            "id": ("exact", ),
            "latitude": ALL,
            "longitude": ALL,
            "accuracy": ALL,
            "time": ALL,
            "guid": ("exact", ),
            "spectator": ALL_WITH_RELATIONS,
        }
        ordering = ["time"]
Exemplo n.º 25
0
class InstanceResource(Resource):
    uuid = fields.CharField(attribute='uuid')
    name = fields.CharField(attribute='name')
    lifetime = fields.DateTimeField(attribute='lifetime')

    class Meta:
        max_limit = 10
        resource_name = 'instance'
        allowed_methods = ['get']
        object_class = Instance
        authentication = Authentication()
        authorization = Authorization()
        serializer = DefaultSerializer()

    def detail_uri_kwargs(self, bundle_or_obj):
        kwargs = {}

        if isinstance(bundle_or_obj, Bundle):
            kwargs['pk'] = bundle_or_obj.obj.name
        else:
            kwargs['pk'] = bundle_or_obj.name

        return kwargs

    def get_object_list(self, request):
        return instances

    def obj_get_list(self, bundle, **kwargs):
        return self.get_object_list(bundle.request)

    def obj_get(self, bundle, **kwargs):
        pk = str(kwargs['pk'])
        try:
            return next((item for item in instances if item.name == pk))
        except StopIteration:
            raise NotFound("DEFT instance '%s' is not registered" % pk)

    def obj_create(self, bundle, **kwargs):
        raise BadRequest()

    def obj_update(self, bundle, **kwargs):
        raise BadRequest()

    def obj_delete_list(self, bundle, **kwargs):
        raise BadRequest()

    def obj_delete(self, bundle, **kwargs):
        raise BadRequest()

    def rollback(self, bundles):
        pass

    def apply_filters(self, request, applicable_filters):
        pass

    def obj_delete_list_for_update(self, bundle, **kwargs):
        pass
Exemplo n.º 26
0
class SensorResyncResource(resources.ModelResource):
    sensor = fields.ToOneField(THSensorResource, 'sensor')
    ts = fields.DateTimeField('ts', readonly=True)

    class Meta(ResourceMetaCommon):
        queryset = SensorResync.objects.all()
        authorization = RWAuthorization()
        detail_allowed_methods = ['get']
        list_allowed_methods = ['get', 'post']
Exemplo n.º 27
0
class BugResource(CommonResource):
    """API Resource for 'Bug' model. """

    bugtrackerbug = ToOneField(
        'oilserver.api.resources.BugTrackerBugResource', 'bugtrackerbug',
        full=True)
    knownbugregexes = ReverseManyField(
        'oilserver.api.resources.KnownBugRegexResource', 'knownbugregexes')
    historical_bugoccurrences = fields.ListField('historical_bugoccurrences',
                                                 readonly=True, null=True)
    occurrence_count = fields.IntegerField('occurrence_count', readonly=True,
                                           null=True)
    last_seen = fields.DateTimeField('last_seen', readonly=True, null=True)

    class Meta(CommonMeta):
        queryset = models.Bug.objects.select_related('bugtrackerbug').all()
        filtering = {'summary': ('contains', 'exact'),
                     'uuid': ('exact'),
                     'description': ('exact'),
                     'knownbugregexes': ALL_WITH_RELATIONS,
                     'bugtrackerbug': ALL_WITH_RELATIONS, }

    def dehydrate(self, bundle):
        bundle = super(BugResource, self).dehydrate(bundle)
        bugoccurrence = BugOccurrenceResource().occurrences_for_bug_filters(
            bundle)
        bundle.data['occurrence_count'] = bugoccurrence.count()

        interval = bundle.request.GET.get('historical_bugoccurrences_grouping')
        try:
            bugno = bundle.data['bugtrackerbug'].data['bug_number']
        except (KeyError, AttributeError):
            bugno = None
        if interval in ['day', 'month', 'year'] and bugno:
            bugoccurrences_history = models.BugOccurrence.objects.filter(
                knownbugregex__bug__bugtrackerbug__bug_number=bugno)
            stmnt = "date_trunc('%s', oilserver_bugoccurrence.created_at)" % \
                interval
            timeframe = bugoccurrences_history.extra({"date": stmnt})
            bugocc_data = []
            if timeframe:
                period = timeframe.values("date").order_by("date")
                bugocc_data = list(period.annotate(count=AggCount("id")))
            bundle.data["historical_bugoccurrences"] = bugocc_data
        else:
            del bundle.data['historical_bugoccurrences']

        if bugoccurrence.exists():
            try:
                last_seen = bugoccurrence.latest(
                    'testcaseinstance__build__pipeline__completed_at')
                bundle.data['last_seen'] = \
                    last_seen.testcaseinstance.build.pipeline.completed_at
            except AttributeError:
                bundle.data['last_seen'] = None
        return bundle
Exemplo n.º 28
0
class ActivityScoresResource(Resource):
    type = fields.CharField(attribute='type')
    score = fields.FloatField(attribute='score')
    time = fields.DateTimeField(attribute='activity_date')

    def get_list(self, request, **kwargs):
        self.parent_object = kwargs.get('parent_object')
        if self.parent_object is None:
            raise BadRequest(
                'Missing parent object. Trying to get this as a non-nested resource?'
            )

        self.parent_uri = kwargs.get('parent_uri')
        if self.parent_uri is None:
            raise BadRequest('Missing parent uri.')

        return super(ActivityScoresResource, self).get_list(request, **kwargs)

    def obj_get_list(self, bundle, **kwargs):
        resolution = bundle.request.GET.get('resolution', '').lower()
        if resolution == '':
            resolution = None

        since = parse_date_from_opts(bundle.request.GET, 'since')
        until = parse_date_from_opts(bundle.request.GET, 'until')

        keyword = bundle.request.GET.get('keyword', '')
        if keyword:
            try:
                kw_obj = Keyword.objects.get(name__iexact=keyword)
            except Keyword.DoesNotExist:
                raise BadRequest("Invalid keyword '%s'" % keyword)
            kwargs['keyword'] = kw_obj

        obj = self.parent_object
        score_list = obj.get_activity_score_set(since=since,
                                                until=until,
                                                resolution=resolution,
                                                **kwargs)
        bundle = []
        for score in score_list:
            score_obj = DictModel(score)
            bundle.append(score_obj)

        return bundle

    def get_resource_uri(self,
                         bundle_or_obj=None,
                         url_name='api_dispatch_list'):
        return self.parent_uri

    class Meta:
        include_resource_uri = False
        resource_name = 'activity_scores'
Exemplo n.º 29
0
class PostResource(ModelResource):
    author = fields.ForeignKey(AuthorResource, attribute='author', null=True)
    files = fields.ManyToManyField('tests.tastypie_api.api.MediaResource',
                                   attribute='files')
    date = fields.DateTimeField('date')
    rating = fields.DecimalField('rating', null=True)
    content = fields.CharField('content')

    class Meta:
        queryset = Post.objects.all()
        resource_name = u'post'
Exemplo n.º 30
0
class StockStatusResource(JsonResource):

    type = "stock_status"
    id = fields.CharField(attribute='_id', readonly=True, unique=True)
    current_stock = fields.IntegerField(attribute='current_stock',
                                        readonly=True,
                                        null=True)
    stocked_out_since = fields.DateTimeField(attribute='stocked_out_since',
                                             readonly=True,
                                             null=True)
    product_id = fields.CharField(attribute='product', readonly=True)
    location_id = fields.CharField(attribute='location_id', readonly=True)
    modified_on = fields.DateTimeField(attribute='server_modified_on',
                                       readonly=True,
                                       null=True)

    def obj_get(self, request, **kwargs):
        case = get_object_or_not_exist(CommCareCase, kwargs["pk"],
                                       kwargs["domain"])
        return StockStatus.from_case(case)