Beispiel #1
0
def checkin_succeeded(request, user, area=None, env=None, virtual=False):
    from client.api import AreaResource, EnvironmentResource, UserResource

    ## default is to just return an 200 OK http response
    response = {"success": True, "code": 200, "data": {}}

    ## add the value of the virtual checkin flag
    response['data'].update({'virtual': virtual})

    ## add the user URI as data payload - will be used for all notifications
    user_uri = UserResource().get_resource_uri(user)
    response['data'].update({'user_uri': user_uri})

    if area:
        ## return data about the area resource
        ar = AreaResource()
        ar_bundle = ar.build_bundle()
        ar_item = ar.obj_get(ar_bundle, pk=area.id)
        ar_bundle.obj = ar_item
        ar_bundle.request = request

        try:
            area_data = ar.full_dehydrate(ar_bundle).data
            response['data'].update(area_data)
        except ImmediateHttpResponse, error:
            return error.response
Beispiel #2
0
    def hydrate(self, bundle):
        ## get all data from bundle.data
        user = bundle.request.user.get_profile()

        category = ProgramAnnotation.CATEGORY
        data = bundle.data['data']
        environment = None
        area = None

        try:
            environment = EnvironmentResource().get_via_uri(
                bundle.data['environment'], request=bundle.request)
        except:
            environment = None

        try:
            area = AreaResource().get_via_uri(bundle.data['area'],
                                              request=bundle.request)
        except:
            area = None

        try:
            bundle.obj = ProgramAnnotation(user=user,
                                           environment=environment,
                                           area=area,
                                           category=category,
                                           data=data)
        except DuplicateAnnotationException, e:
            raise ImmediateHttpResponse(response=http.HttpForbidden(
                content=e.get_message()))
Beispiel #3
0
    def is_valid(self, bundle, request=None):
        from client.api import EnvironmentResource, AreaResource

        ## check that we have a user
        if not bundle.request.user or bundle.request.user.is_anonymous():
            return {'__all__': 'No user found in request.'}

        if not bundle.data:
            return {'__all__': 'No data submitted.'}

        errors = {}

        if bundle.request.method.upper() == "POST":
            env_obj = None
            area_obj = None

            if 'environment' in bundle.data:
                try:
                    env_obj = EnvironmentResource().get_via_uri(
                        bundle.data['environment'])
                except:
                    env_obj = None

            if 'area' in bundle.data:
                try:
                    area_obj = AreaResource().get_via_uri(bundle.data['area'])
                except:
                    area_obj = None

            if env_obj is None and area_obj is None:
                errors['environment'] = ['No or wrong environment uri']
                errors['area'] = ['No or wrong area uri']

            if not env_obj is None and not area_obj is None and area_obj.env != env_obj:
                errors['environment'] = [
                    "Environment resource mismatches parent environment of area resource."
                ]

        if not 'data' in bundle.data or not bundle.data['data']:
            errors['data'] = ["No or empty data field."]

        ## some additional validation of the data field might also be possible if no errors up to now
        if not errors:
            ann_cls = bundle.obj.__class__
            data = bundle.data['data']
            category = bundle.obj.__class__.CATEGORY

            data_errors = ann_cls.validate_data(category, data)
            if data_errors:
                errors['data'] = data_errors

                import sys
                print >> sys.stderr, data_errors

        return errors
Beispiel #4
0
def checkin_succeeded(request, user, area=None, env=None, virtual=False):
    from client.api import AreaResource, EnvironmentResource, UserResource

    ## default is to just return an 200 OK http response
    response = {"success": True, "code": 200, "data": {}}

    ## add the value of the virtual checkin flag
    response["data"].update({"virtual": virtual})

    ## add the user URI as data payload - will be used for all notifications
    user_uri = UserResource().get_resource_uri(user)
    response["data"].update({"user_uri": user_uri})

    if area:
        ## return data about the area resource
        ar = AreaResource()
        ar_item = ar.obj_get(pk=area.id)
        ar_bundle = ar.build_bundle(obj=ar_item, request=request)

        try:
            area_data = ar.full_dehydrate(ar_bundle).data
            response["data"].update(area_data)
        except ImmediateHttpResponse, error:
            return error.response
Beispiel #5
0
from django.conf.urls.defaults import patterns, include, url
#from tastypie.api import Api
from client.api import ClientApi
from client.api import EnvironmentResource, AreaResource, FeatureResource, AnnotationResource,\
                        AnnouncementResource, HistoryResource, UserResource, EnvrionmentContextResource
#from client.views import checkin, checkout

v1_api = ClientApi(api_name='v1')
v1_api.register(EnvironmentResource())
v1_api.register(AreaResource())
v1_api.register(FeatureResource())
v1_api.register(AnnotationResource())
v1_api.register(AnnouncementResource())
v1_api.register(HistoryResource())
v1_api.register(UserResource())
v1_api.register(EnvrionmentContextResource())

urlpatterns = patterns(
    '',
    #url(r'^checkin/$', checkin, name="checkin"),
    #url(r'^checkout/$', checkout, name="checkout"),
    (r'', include(v1_api.urls)),
)
Beispiel #6
0
 def to_serializable(self, request = None, virtual = False, include_data = False):
     from client.api import AreaResource
     
     serialized_feature = super(ProgramFeature, self).to_serializable(request = request, virtual=virtual, include_data=include_data)
     
     if include_data:
         program_dict = {'data' : {'description' : self.description} }
         
         sessions_list = []
         presentation_list = []
         speaker_list = []
         presentation_speakers_list = []
         
         sessions = self.sessions.all()
         for s in sessions:
             session_dict = {'id' : s.id,
                             'title' : s.title,
                             'tag' : s.tag,
                            }
             
             ## we add the data of the area in which this session of presentations is to take place
             session_dict['location_url'] = AreaResource().get_resource_uri(s.location)
             session_dict['location_name'] = s.location.name
             
             sessions_list.append(session_dict)
             
             presentations = s.presentations.all().order_by('startTime')
             for pres in presentations:
                 presentation_dict = {'id' : pres.id,
                                     'title' : pres.title,
                                     'sessionId' : s.id,
                                     'startTime' : pres.startTime.strftime("%Y-%m-%dT%H:%M:%S"),
                                     'endTime' : pres.endTime.strftime("%Y-%m-%dT%H:%M:%S")
                                     }
                 if pres.abstract:
                     presentation_dict['abstract'] = pres.abstract
                 
                 if pres.tags:
                     presentation_dict['tags'] = ";".join(pres.tags.getList())
                 
                 presentation_list.append(presentation_dict)
                 
                 speakers = pres.speakers.all().order_by('last_name')
                 for speaker in speakers:
                     presentation_speaker_dict = {'presentation_id' : pres.id,
                                                 'speaker_id': speaker.id
                                                 }
                     presentation_speakers_list.append(presentation_speaker_dict)
                     
                     if not any(d.get('id', None) == speaker.id for d in speaker_list):
                         speaker_dict = {'id': speaker.id,
                                         'first_name': speaker.first_name,
                                         'last_name': speaker.last_name,
                                         'affiliation': speaker.affiliation,
                                         'position': speaker.position
                                         }
                                 
                         if speaker.biography:
                             speaker_dict['biography'] = speaker.biography
                         
                         if speaker.email:
                             speaker_dict['email'] = speaker.email
                         
                         if speaker.online_profile_link:
                             speaker_dict['online_profile_link'] = speaker.online_profile_link
                         
                         if speaker.image_url:
                             speaker_dict['image_url'] = speaker.image_url
                         
                         speaker_list.append(speaker_dict)
                     
         """
         distinct_program_days_list =\
             Presentation.objects.values('startTime').\
                 extra({'start_date' : "date(startTime)"}).values('start_date').distinct()
         
         program_days = map(lambda x: x['start_date'].strftime("%Y-%m-%dT%H:%M:%S"), 
                             distinct_program_days_list)
         """
         program_dict['data']['program'] =  {#'program_days': program_days,
                                             'sessions' : sessions_list, 
                                             'presentations' : presentation_list,
                                             'speakers': speaker_list,
                                             'presentation_speakers' : presentation_speakers_list
                                            }
         
         serialized_feature.update(program_dict)
     
     return serialized_feature
Beispiel #7
0
        envr_item = envr.obj_get(envr_bundle, pk=env.id)
        envr_bundle.obj = envr_item
        envr_bundle.request = request

        try:
            env_data = envr.full_dehydrate(envr_bundle).data
            response['data'].update(env_data)
        except ImmediateHttpResponse, error:
            return error.response

        ## include the list of all areas that belong to this environment
        area_list = []
        for ar in env.areas.all():
            area_dict = {
                'name': ar.name,
                'resource_uri': AreaResource().get_resource_uri(ar)
            }

            ## check if there are tags for this area
            if ar.tags:
                area_dict['tags'] = ar.tags.getList()

            ## check if there is an image thumbnail url for the area
            if ar.img_thumbnail_url:
                area_dict['image_url'] = ar.img_thumbnail_url

            ## see how many people there are physically checked in at this area
            area_person_count = UserContext.objects.filter(
                currentArea=ar).count()
            area_dict['person_count'] = area_person_count
Beispiel #8
0
def send_feature_update_message(environment=None,
                                area=None,
                                feature=None,
                                receivers='all'):
    """
    The function sends a feature update message for the feature `feature'.
    This `receivers' are either a list of User IDs, or the keyword `all' (by default).
    For the `all' case, we consider all users checked in at the given `area' (if not None), otherwise
    at the given `environment'.
    """
    import redis
    from django.conf import settings
    from datetime import datetime
    from pytz import timezone
    from coresql.models import UserContext
    from client.api import EnvironmentResource, AreaResource, FeatureResource

    redis_server = redis.Redis(host=settings.REDIS_HOST,
                               port=settings.REDIS_PORT,
                               db=settings.REDIS_DB)

    if feature is None:
        return

    if environment is None and area is None and receivers == 'all':
        return

    if receivers == 'all':
        utc_tz = timezone("UTC")
        timestamp = datetime.now(utc_tz)
        timestamp_str = timestamp.strftime("%Y-%m-%dT%H:%M:%S")
        '''build update message content'''
        feature_categ = feature.category
        update_type = FEATURE_RETRIEVE_CONTENT_LABEL

        ## get the feature resource URI
        feature_resource_class = feature.__class__.get_resource_class()
        feature_resource_uri = feature_resource_class().get_resource_uri(
            feature)

        ## get the location URI
        location_uri = None
        if area is not None:
            location_uri = AreaResource().get_resource_uri(area)
        elif environment is not None:
            location_uri = EnvironmentResource().get_resource_uri(environment)

        update_message = {
            'type': FEATURE_UPDATE_TYPE,
            'timestamp': timestamp_str,
            'content': {
                'feature': feature_categ.encode("utf8"),
                'location_uri': location_uri,
                'resource_uri': feature_resource_uri,
                'params': [{
                    'name': 'type',
                    'value': update_type
                }]
            }
        }
        '''send it to required uses'''
        if isinstance(receivers, basestring) and receivers == 'all':
            user_contexts = None

            if area is not None:
                user_contexts = UserContext.objects.filter(
                    currentArea=area).order_by('user').distinct()

            elif environment is not None:
                user_contexts = UserContext.objects.filter(
                    currentEnvironment=environment).order_by(
                        'user').distinct()

            for uc in user_contexts:
                user_id = uc.user.user.id

                ## send message on the user channel
                channel_name = str(user_id)
                redis_server.publish(channel_name, update_message)

    elif isinstance(receivers, list):
        '''receivers is already a list of user IDs for which to send the feature update notification'''
        for user_id in receivers:
            ## send message on the user channel
            channel_name = str(user_id)
            redis_server.publish(channel_name, update_message)
Beispiel #9
0
    def is_authorized(self, request, object=None):
        from client.api import EnvironmentResource, AreaResource, AnnotationResource
        from coresql.models import Environment, Area
        from coresql.utils import str2bool

        if hasattr(request, 'user') and not request.user.is_anonymous():
            env_obj = None
            area_obj = None

            if request.method.upper() == "GET":
                if 'environment' in request.GET:
                    try:
                        env_obj = Environment.objects.get(
                            pk=request.GET['environment'])
                    except:
                        env_obj = None

                if 'area' in request.GET:
                    try:
                        area_obj = Area.objects.get(pk=request.GET['area'])
                    except:
                        area_obj = None
                ''' For GET requests we check if there is a virtual access flag set in the request.
                    If the flag is not set, the default behavior is to assume physical check-in '''
                if 'virtual' in request.GET:
                    try:
                        virtual = str2bool(request.GET['virtual'])
                        if virtual and (area_obj or env_obj):
                            ''' if the virtual flag is set to TRUE, then allow access, otherwise, check that 
                            the user is actually checked-in where he says he is '''
                            return True
                    except ValueError:
                        return False

            elif request.method.upper() == "POST":
                ''' for the rest of the methods check that the requesting user is actually checked in '''
                serdes = Serializer()
                deserialized = None
                try:
                    deserialized = serdes.deserialize(request.raw_post_data,
                                                      format=request.META.get(
                                                          'CONTENT_TYPE',
                                                          'application/json'))
                except Exception:
                    return False

                if deserialized is None:
                    return False

                if 'environment' in deserialized:
                    try:
                        #env_pk = int(deserialized['env'])
                        env_obj = EnvironmentResource().get_via_uri(
                            deserialized['environment'], request=request)
                    except:
                        env_obj = None

                if 'area' in deserialized:
                    try:
                        #area_pk = int(deserialized['area'])
                        area_obj = AreaResource().get_via_uri(
                            deserialized['area'], request=request)
                    except:
                        area_obj = None

            elif request.method.upper() in ["DELETE", "PUT"]:
                ann_res_uri = request.path
                try:
                    ann_obj = AnnotationResource().get_via_uri(ann_res_uri,
                                                               request=request)
                    env_obj = ann_obj.environment
                    area_obj = ann_obj.area

                    #print "[authorization] env_obj: ", env_obj
                    #print "[authorization] area_obj: ", area_obj
                except Exception:
                    #print "[authorization] exception in getting annotation resource for deletion: ", ex
                    env_obj = None
                    area_obj = None

            user_profile = request.user.get_profile(
            )  ## will be an instance of UserProfile => available context
            return is_checked_in(user_profile, env_obj, area_obj)

        return False
Beispiel #10
0
    def is_valid(self, bundle, request=None):
        from client.api import EnvironmentResource, AreaResource
        from coresql.models import CATEGORY_CHOICES, Annotation

        ## check that we have a user
        if not bundle.request.user or bundle.request.user.is_anonymous():
            return {'__all__': 'No user found in request.'}

        if not bundle.data:
            return {'__all__': 'No data submitted.'}

        errors = {}

        if bundle.request.method.upper() == "POST":
            env_obj = None
            area_obj = None

            if 'environment' in bundle.data:
                try:
                    env_obj = EnvironmentResource().get_via_uri(
                        bundle.data['environment'])
                except:
                    env_obj = None

            if 'area' in bundle.data:
                try:
                    area_obj = AreaResource().get_via_uri(bundle.data['area'])
                except:
                    area_obj = None

            if env_obj is None and area_obj is None:
                errors['environment'] = ['No or wrong environment uri']
                errors['area'] = ['No or wrong area uri']

            if not env_obj is None and not area_obj is None and area_obj.env != env_obj:
                errors['environment'] = [
                    "Environment resource mismatches parent environment of area resource."
                ]

        if not 'data' in bundle.data or not bundle.data['data']:
            errors['data'] = ["No or empty data field."]

        if not 'category' in bundle.data or not (
                bundle.data['category'],
                bundle.data['category']) in CATEGORY_CHOICES:
            errors['category'] = ["No category specified or wrong category."]

        ## some additional validation of the data field might also be possible if no errors up to now
        if not errors:
            for _, cls in Annotation.get_subclasses():
                category = bundle.data['category']
                data = bundle.data['data']

                if cls.is_annotation_for(category, data):
                    data_errors = cls.validate_data(category, data)
                    if data_errors:
                        errors['data'] = data_errors

                        import sys
                        print >> sys.stderr, data_errors

                    break

        return errors