Exemplo n.º 1
0
 def get(self, request, camp_id=None):
     """ Returns a list of campaigns for a user
      ---
      response_serializer: CampaignSerializer
     """
     try:
         cs = None
         auth_user = auth_manager.do_auth(request)
         # valid user
         user = MediaUser.objects.get(username=auth_user.username)
         if camp_id:
             cs = Campaign.objects.filter(creator=user, id=camp_id)
         else:
             cs = Campaign.objects.filter(creator=user)
         if not len(cs):
             return JSONResponse(str("User doesn't have any campaign."),
                                 status=HTTP_204_NO_CONTENT)
         serializer = CampaignSerializer(cs, many=True)
         return JSONResponse(serializer.data)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 2
0
 def post(self, request, *args, **kwargs):
     """ Creates a Call only campaign Ad
      ---
      request_serializer: CallOnlyAdSerializer
      response_serializer: CallOnlyAdSerializer
     """
     # Request Post, create user
     if request.method == 'POST':
         try:
             auth_manager.do_auth(request.META)
             serializer = CallOnlyAdSerializer(data=request.data)
             if serializer.is_valid(raise_exception=True):
                 serializer.save()
                 return JSONResponse(serializer.data,
                                     status=HTTP_201_CREATED)
             else:
                 return JSONResponse(serializer.errors,
                                     status=HTTP_400_BAD_REQUEST)
         except UserNotAuthorizedException as e:
             print e
             return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
         except Exception as e:
             print e
             return JSONResponse(serializer.errors,
                                 status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 3
0
    def get(self, request, campaign_id=None, ad_id=None):
        """ Returns a list of image campaign ads
         ---
         response_serializer: ImageAdSerializer
        """
        try:
            # Get all image-ads
            if campaign_id is None:
                ads = ImageAd.objects.all()
                serializer = ImageAdSerializer(ads, many=True)
                return JSONResponse(serializer.data)

            # Get more specific ads by campaigns
            camp = Campaign.objects.get(id=campaign_id)
            if ad_id is None:
                ads = ImageAd.objects.filter(campaign=camp)
                serializer = ImageAdSerializer(ads, many=True)
            else:
                ad = ImageAd.objects.get(id=ad_id)
                if ad.campaign.id == camp.id:
                    serializer = ImageAdSerializer(ad)
            return JSONResponse(serializer.data)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 4
0
 def post(self, request):
     """ Creates a user dash-board
      ---
      response_serializer: MediaDashboardSerializer
     """
     try:
         auth_user = auth_manager.do_auth(request)
         # ensure user
         user = MediaUser.objects.get(username=auth_user.username)
         dash = MediaDashboard.objects.filter(user=user)
         if not len(dash):
             # Get the dash-board type
             dash_typ = dashboard_controller.type(
                 user.role.name if user.role else None)
             # Create for the user
             serializer = MediaDashboardSerializer(data=request.data)
             if serializer.is_valid(raise_exception=True):
                 # Create one.
                 inst = serializer.save(user=user, dashboard_type=dash_typ)
                 updated_inst = serializer.update(inst)
                 serializer = MediaDashboardSerializer(updated_inst)
                 return JSONResponse(serializer.data,
                                     status=HTTP_201_CREATED)
         else:
             # Update the dash-board
             serializer = MediaDashboardSerializer()
             updated_inst = serializer.update(dash[0])
             serializer = MediaDashboardSerializer(updated_inst)
             return JSONResponse(serializer.data, status=HTTP_200_OK)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 5
0
def login(request):
    try:
        # Get all Http headers
        import re
        regex = re.compile('^HTTP_')
        head = dict((regex.sub('', header), value)
                    for (header, value) in request.META.items()
                    if header.startswith('HTTP_'))
        username = head['USERNAME']
        email = head['EMAIL']
        # Try if Auth driver recognizes the user
        auth_manager.do_auth(request)
        # Get the  user details, and pass them back
        # to login caller.
        usr = MediaUser.objects.get(username=username, email=email)
        serializer = UserSerializer(usr, many=False)
        return JSONResponse(serializer.data, status=HTTP_200_OK)
    except UserNotAuthorizedException as e:
        print e
        return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
    except MultipleObjectsReturned as e:
        print e
        return JSONResponse(str(e), status=HTTP_300_MULTIPLE_CHOICES)
    except DoesNotExist as e:
        print e
        return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
    except Exception as e:
        print e
        return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 6
0
 def post(self, request, userid, service_name):
     """ Creates a service request
      ---
      request_serializer: ServiceRequestSerializer
      response_serializer: UserServiceSerializer
     """
     try:
         auth_manager.do_auth(request)
         tm = datetime.now()
         if userid and service_name:
             user = MediaUser.objects.get(id=userid)
             svc = Service.objects.get(service_friendly_name=service_name)
             # Continue processing service request
             serializer = ServiceRequestSerializer(data=request.data)
             if serializer.is_valid(raise_exception=True):
                 sr = serializer.save(request_time=tm)
                 sr.update(service=svc, user_ref=user)
                 # Prepare the service for the User
                 # Return if already the service exists for the User.
                 created_svc = session_mgr.prepare_user_service(user=user,
                                                                service=svc)
                 svc_serializer = UserServiceSerializer(created_svc)
                 return JSONResponse(svc_serializer.data,
                                     status=HTTP_201_CREATED)
         else:
             return JSONResponse(serializer.errors,
                                 status=HTTP_400_BAD_REQUEST)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 7
0
 def get(self, request, userid, service_name=None):
     """ Returns a list of user service
      ---
      response_serializer: UserServiceSerializer
     """
     try:
         auth_manager.do_auth(request)
         user = MediaUser.objects.get(id=userid)
         if service_name:
             svc = Service.objects.get(service_friendly_name=service_name)
             svcs = UserService.objects.filter(user_ref=user,
                                               service_id=svc)
         else:
             svcs = UserService.objects.filter(user_ref=user)
         serializer = UserServiceSerializer(svcs, many=True)
         return JSONResponse(serializer.data)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 8
0
    def handle_operations(self, online, action, action_args, action_data):
        # action= add media etc., action_args= content-id, action_data= {}
        print 'OnlineMediaController: Performing action %s' % action

        if action == self.ADD_MEDIA_CONTENT:
            # Add media content to OOH Media source object
            campid = action_args['id'] if 'id' in action_args else None
            if campid is None:
                return JSONResponse('content id cannot be None for action type'
                                    ' %s' % self.ADD_MEDIA_CONTENT,
                                    status=HTTP_400_BAD_REQUEST)
            # get the campaign
            campaign = Campaign.objects.get(id=campid)
            _nv = {'source_type': 'online',
                   'start_date': action_data['start_date'],
                   'end_date': action_data['end_date']}
            _playing_data = json.loads(
                                str(self.playing_template.render(**_nv)))
            playing = PlayingSerializer(data=_playing_data)
            if playing.is_valid(raise_exception=True):
                play = playing.save()
                play.update(primary_media_source=online,
                            playing_content=campaign)
                return JSONResponse(playing.validated_data,
                                    status=HTTP_200_OK)
        else:
            # Unknown operation
            pass
Exemplo n.º 9
0
    def get(self, request, id):
        """ Returns playing objects for the campaigns
         ---
         response_serializer: PlayListSerializer
        """
        try:
            # valid user
            auth_manager.do_auth(request)

            camp = Campaign.objects.get(id=id)
            plays = Playing.objects.filter(playing_content=camp)
            venues = []
            for play in plays:
                if play.source_type.lower() == 'sensor':
                    # Venues are masked for sensor media
                    # so reveal them and return to the caller.
                    source = play.primary_media_source
                    venues.append(source.venue)
                else:
                    # Venues remains empty
                    pass
            pls = PlayList(playing_content=camp, venues=venues, plays=plays)
            serializer = PlayListSerializer(pls)
            return JSONResponse(serializer.data)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 10
0
 def post(self, request):
     try:
         planrequest = OOHPlanRequestSerializer(data=request.data)
         if planrequest.is_valid(raise_exception=True):
             req = planrequest.save()
             # Process the request
             classifier = ClassifierTask()
             findooh = FindOOHFiltered()
             result = chain(classifier.s(req.wish),
                            findooh.s(req.filters)).apply_async()
             slept = 0
             timeout = False
             while not result.ready():
                 time.sleep(.05)
                 slept = slept + 0.05
                 if slept > 3:
                     timeout = True
                     break
             if result.state == "SUCCESS":
                 print "slept = %s" % slept
                 outdata = json.loads(str(result.result))
                 return JSONResponse(outdata, status=HTTP_200_OK)
             elif timeout:
                 return JSONResponse("Query timeout.",
                                     status=HTTP_408_REQUEST_TIMEOUT)
             else:
                 return JSONResponse("Bad Request!.",
                                     status=HTTP_500_INTERNAL_SERVER_ERROR)
     except Exception as e:
         return JSONResponse("Bad Request!.",
                             status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 11
0
    def post(self, request, camp_id=None):
        """ Creates a campaign for a user
         ---
         request_serializer: CampaignSerializer
         response_serializer: CampaignSerializer
        """
        try:
            spec = None
            create_time = datetime.now()
            auth_user = auth_manager.do_auth(request)
            user = MediaUser.objects.get(username=auth_user.username)

            # Handle update here
            if camp_id:
                return self._update(request, camp_id, user)

            # Serialize spec
            if 'spec' in request.data:
                cspecserializer = CampaignSpecSerializer(
                    data=request.data['spec'])
                if cspecserializer.is_valid(raise_exception=True):
                    spec = cspecserializer.save()

            img = None
            # Store home page for the campaign
            if 'image' in request.data:
                imageserializer = ImageContentSerializer(
                    data=request.data['image'])
                if imageserializer.is_valid(raise_exception=True):
                    img = imageserializer.save()

            # Serialize the Campaign
            serializer = CampaignSerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                campaign = serializer.save(creation_time=create_time,
                                           creator=user)
                # Campaign created.
                if spec:
                    campaign.update(spec=spec)
                if img:
                    campaign.update(image_content=img,
                                    image_url=img.get_absolute_url())
                # Prepare the campaign for the User
                self.controller.prepare_campaign(user=user,
                                                 camp=campaign,
                                                 spec=spec)
                return JSONResponse(serializer.data, status=HTTP_201_CREATED)
            else:
                return JSONResponse(serializer.errors,
                                    status=HTTP_400_BAD_REQUEST)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except Exception as e:
            print e
            return JSONResponse(serializer.errors, status=HTTP_400_BAD_REQUEST)
Exemplo n.º 12
0
 def get(self, request, source_type, source_id):
     """ Sets and Returns current feed statistics tags for
     Media instance identified by Id.
      ---
      response_serializer: OOHOperationalDailyDataFeedSerializer
     """
     try:
         all_data = False
         auth_manager.do_auth(request)
         start_date = request.query_params['startday'] if 'startday' in\
             request.query_params else None
         end_date = request.query_params['endday'] if 'endday' in\
             request.query_params else datetime.now()
         if start_date is None:
             # get all samples
             all_data = True
         # Get the source
         if source_id is not None:
             if source_type == 'ooh':
                 source = OOHMediaSource.objects.get(id=source_id)
                 if all_data:
                     data = OOHOperationalDailyDataFeed.objects.filter(
                         source_ref=source)
                 else:
                     # filter only for a date range
                     data = OOHOperationalDailyDataFeed.objects.filter(
                         source_ref=source,
                         feed_timestamp__gt=start_date,
                         feed_timestamp__lt=end_date)
                 serializer = OOHOperationalDailyDataFeedSerializer(
                     data, many=True)
                 return JSONResponse(serializer.data, status=HTTP_200_OK)
                 # Save the data feed record
                 if serializer.is_valid(raise_exception=True):
                     serializer.save(source_ref=source)
                     return JSONResponse(str('success'),
                                         status=HTTP_201_CREATED)
             elif source_type == 'digitalmedia':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
             elif source_type == 'vod':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
             elif source_type == 'radio':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
         else:
             return JSONResponse(str("source_id is must."),
                                 status=HTTP_400_BAD_REQUEST)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 13
0
 def get(self, request, *args, **kwargs):
     """ Returns a list of call only campaign ads
      ---
      response_serializer: CallOnlyAdSerializer
     """
     try:
         auth_manager.do_auth(request.META)
         # Request Get, all users
         if request.method == 'GET':
             ads = CallOnlyAd.objects.all()
             serializer = CallOnlyAdSerializer(ads, many=True)
             return JSONResponse(serializer.data)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 14
0
 def get(self, request, service_key):
     """ Gets a service instance
      ---
      response_serializer: ServiceRequestSerializer
     """
     # Request Post, create a service data
     # for e.g. an offer, a notification etc.
     try:
         svc = UserService.objects.get(id=service_key)
         # deliver the service, delegate to service manager
         servicedata = session_mgr.servicemanager.handle_service_get_request(
             svc, request.query_params)
         return JSONResponse(servicedata.data, status=HTTP_200_OK)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 15
0
    def _update(self, request, ad):

        try:
            # partial updates
            serializer = ImageAdSerializer(data=request.data, partial=True)
            if serializer.is_valid(raise_exception=True):
                updated_obj = serializer.update(ad, serializer.validated_data)
                # Other reference fields
                # Store image'
                if "image" in request.data:
                    imageserializer = ImageContentSerializer(data=request.data)
                    if imageserializer.is_valid(raise_exception=True):
                        img = imageserializer.save()
                        img_url = img.get_absolute_url()
                        updated_obj.update(image_content=img,
                                           image_url=img_url)
                if "offerex" in request.data:
                    #
                    #
                    #
                    #
                    # Extensions are stored and updated
                    offer = OfferExtensionSerializer(
                        data=request.data['offerex'], partial=True, many=True)
                    if offer.is_valid(raise_exception=True):
                        ofs = offer.save()
                        updated_obj.update(offerex=ofs)
                if "socialex" in request.data:
                    #
                    #
                    #
                    #
                    # Extensions are stored and updated
                    social = SocialMediaExtensionSerializer(
                        data=request.data['socialex'], partial=True, many=True)
                    if social.is_valid(raise_exception=True):
                        s_exs = social.save()
                        updated_obj.update(socialex=s_exs)
                updated_obj.save()
                return JSONResponse(str(updated_obj.id),
                                    status=HTTP_202_ACCEPTED)
            # Bad request
            return JSONResponse(str(serializer.errors),
                                status=HTTP_400_BAD_REQUEST)
        except Exception as e:
            print e
            return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 16
0
 def post(self, request):
     """ Classify the message into pre-defined categories.
     """
     # Note(Sonu:TBD) Create classifier once.
     message = request.data['message']
     classifier = classifierclient.Classifier()
     classifieds = classifier.classify(message)
     return JSONResponse(classifieds, status=HTTP_200_OK)
Exemplo n.º 17
0
 def _update(self, request, camp_id, user):
     """ Updates given campaign instance
      ---
      request_serializer: CampaignSerializer
      response_serializer: CampaignSerializer
     """
     try:
         spec = None
         # TBD (Note:Sonu) : Update the image.
         inst = Campaign.objects.get(id=camp_id, creator=user)
         # For any property to be updated, validate
         # that it is done by the user who created it or
         # owns the instance to avoid billboard stealth.
         if not inst:
             # Verify if owner is modifying the parameter
             return JSONResponse(str("Not Authorized"),
                                 status=HTTP_401_UNAUTHORIZED)
         # partial updates
         serializer = CampaignSerializer(data=request.data, partial=True)
         if serializer.is_valid(raise_exception=True):
             updated_obj = serializer.update(inst,
                                             serializer.validated_data)
             # Other reference fields
             # Store image'
             if "spec" in request.data:
                 specserializer = CampaignSpecSerializer(
                     data=request.data["spec"], partial=True)
                 if specserializer.is_valid(raise_exception=True):
                     spec = specserializer.update(
                         updated_obj.spec, specserializer.validated_data)
             if "image" in request.data:
                 imageserializer = ImageContentSerializer(data=request.data,
                                                          partial=True)
                 # Bug (Sonu:) how to change the image URL? or the
                 # image URL is retained. Need to be checked.
                 # Post image update, image show may not work correctly.
                 if imageserializer.is_valid(raise_exception=True):
                     img = imageserializer.save()
                     updated_obj.update(image_content=img,
                                        image_url=img.get_absolute_url())
                     updated_obj.save()
             return JSONResponse(serializer.validated_data,
                                 status=HTTP_200_OK)
     except Exception as e:
         print e
     return JSONResponse(serializer.errors, status=HTTP_400_BAD_REQUEST)
Exemplo n.º 18
0
 def get(self, request, image_id):
     """ Returns a image identified by Id
      ---
      response_serializer: JpegImageContentSerializer
     """
     try:
         #             auth_manager.do_auth(request)
         # Request Get, all users
         if request.method == 'GET':
             if image_id is not None:
                 img = JpegImageContent.objects.get(id=image_id)
                 return HttpResponse(img.image.read(),
                                     content_type="image/jpeg")
             return JSONResponse("", status=HTTP_404_NOT_FOUND)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 19
0
 def get(self, request):
     """ Returns dash-board for the user
      ---
      response_serializer: MediaDashboardSerializer
     """
     try:
         auth_user = auth_manager.do_auth(request)
         user = MediaUser.objects.get(username=auth_user.username)
         # return the dash-board for the user.
         dash = MediaDashboard.objects.get(user=user)
         serializer = MediaDashboardSerializer(dash)
         return JSONResponse(serializer.data, status=HTTP_200_OK)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 20
0
 def get(self, request, id):
     """ Returns playing objects for the campaigns
      ---
      response_serializer: PlayingSerializer
     """
     try:
         auth_user = auth_manager.do_auth(request)
         # valid user
         user = MediaUser.objects.get(username=auth_user.username)
         camp = Campaign.objects.get(id=id)
         plays = Playing.objects.filter(playing_content=camp)
         serializer = PlayingSerializer(plays, many=True)
         return JSONResponse(serializer.data)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 21
0
    def get(self, request, camp_id):
        """ Returns a tracking object for the campaigns
         ---
         response_serializer: CampaignTrackingSerializer
        """
        try:
            auth_user = auth_manager.do_auth(request)
            # valid user
            user = MediaUser.objects.get(username=auth_user.username)
            camp = Campaign.objects.get(id=camp_id)
            track = CampaignTracking.objects.get(campaign=camp)

            serializer = CampaignTrackingSerializer(track)
            return JSONResponse(serializer.data)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
Exemplo n.º 22
0
 def post(self, request):
     try:
         notifrequest = NotificationRequestSerializer(data=request.data)
         if notifrequest.is_valid(raise_exception=True):
             req = notifrequest.save()
             print 'Request to send notif type %s with content %s' % (
                 req.type, str(req.content).encode('utf-8'))
             # Workaround : GCM apis do not accept u' in begininig of Unicode strings.
             # strip that from the request.
             if req.type == 'data':
                 content = str(req.content).replace("u\"", "\"").replace(
                     "u\'", "\'")
             elif req.type == 'notification':
                 content = req.message
             # Process the request
             users = UserSelectorTask()
             notifier = CloudNotifierTask()
             result = chain(users.s(req.selector),
                            notifier.s(req.topic, req.type,
                                       content)).apply_async()
             slept = 0
             timeout = False
             while not result.ready():
                 time.sleep(.05)
                 slept = slept + 0.05
                 if slept > 3:
                     timeout = True
                     break
             if result.state == "SUCCESS":
                 print "slept = %s" % slept
                 outdata = json.loads(str(result.result))
                 return JSONResponse(outdata, status=HTTP_200_OK)
             elif timeout:
                 return JSONResponse("Query timeout.",
                                     status=HTTP_408_REQUEST_TIMEOUT)
             else:
                 return JSONResponse("Bad Request!.",
                                     status=HTTP_500_INTERNAL_SERVER_ERROR)
     except Exception as e:
         return JSONResponse("Bad Request!.",
                             status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 23
0
 def get(self, request, userid=None):
     """ Returns a list of users
      ---
      response_serializer: UserSerializer
     """
     try:
         auth_manager.do_auth(request)
         if userid is None:
             # Request Get, all users
             usrs = MediaUser.objects.all()
             serializer = UserSerializer(usrs, many=True)
             return JSONResponse(serializer.data)
         else:
             usrs = MediaUser.objects.get(id=userid)
             serializer = UserSerializer(usrs)
             return JSONResponse(serializer.data)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except MultipleObjectsReturned as e:
         print e
         return JSONResponse(str(e), status=HTTP_300_MULTIPLE_CHOICES)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 24
0
 def post(self, request):
     """ re-creates the indexes for the campaign
     """
     try:
         campset = Campaign.objects.filter(enabled=True)
         if campset:
             cs = CampaignIndexSerializer(campset, many=True)
             task = CampaignIndexingTask()
             rc = task.delay(args=[],
                             instancename=str("__all"),
                             campaign=json.dumps(cs.data),
                             ignore_failures=True,
                             many=True)
             if rc.state == "SUCCESS":
                 return JSONResponse("indexed", status=HTTP_201_CREATED)
             else:
                 return JSONResponse("Failed",
                                     status=HTTP_500_INTERNAL_SERVER_ERROR)
         else:
             return JSONResponse("no content to index",
                                 status=HTTP_204_NO_CONTENT)
     except Exception as e:
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 25
0
 def post(self, request):
     """ Returns elements to the user based on
         english language search.
      ---
      request_serializer: SearchQuerySerializer
      response_serializer: ResearchResultSerializer
     """
     try:
         user = _log_user(request)
         _id = user['userid'] if 'userid' in user else None
         # return the dash-board for the user
         sql = SearchQuerySerializer(data=request.data)
         if sql.is_valid(raise_exception=True):
             # Push the sql to search pipeline
             obj = sql.save(userid=_id)
             print 'Search query by user {%s} for String {%s}\
              in QueryFields {%s} with QueryType {%s}.' % (
                 user['username'], obj.raw_strings, obj.query_fields,
                 obj.query_type)
             # Research result data (RRD)
             if obj.query_object_type is not None:
                 query_object_type = obj.query_object_type
             # Switch the task based on the object to operate.
             task = qc.create_task(query_object_type)
             rrd = task.delay(args=[],
                              raw_strings=obj.raw_strings,
                              fields=obj.query_fields,
                              query_type=obj.query_type,
                              ignore_failures=True)
             slept = 0
             timeout = False
             while not rrd.ready():
                 time.sleep(.05)
                 slept = slept + 0.05
                 if slept > SEARCH_TASK_TIMEOUT:
                     timeout = True
                     break
             if rrd.state == "SUCCESS":
                 print "slept = %s" % slept
                 outdata = json.loads(str(rrd.result))
                 return JSONResponse(outdata, status=HTTP_200_OK)
             elif timeout:
                 return JSONResponse("Search timeout.",
                                     status=HTTP_408_REQUEST_TIMEOUT)
             else:
                 return JSONResponse(
                     "Something went wrong terrible. Unknown error!.",
                     status=HTTP_500_INTERNAL_SERVER_ERROR)
         return JSONResponse("Obfuscated query. Cannot handle error %s" %
                             sql.errors,
                             status=HTTP_400_BAD_REQUEST)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 26
0
    def post(self, request, camp_id):
        """ Creates a campaign tracking object
         ---
         request_serializer: CampaignTrackingSerializer
         response_serializer: CampaignTrackingSerializer
        """
        try:
            auth_user = auth_manager.do_auth(request)
            camp = Campaign.objects.get(id=camp_id)
            # Get if there are campaign tracker for this campaign
            # if found, update/reset it.
            tracking_obj = None
            objs = CampaignTracking.objects.filter(campaign=camp)
            if objs:
                tracking_obj = objs[0]

            serializer = CampaignTrackingSerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                if tracking_obj:
                    serializer.update(tracking_obj, serializer.validated_data)
                else:
                    nearby_fields = self.controller.update_nearby_fields(camp)
                    ct = serializer.save(**nearby_fields)
                    ct.update(campaign=camp)
                return JSONResponse(serializer.data, status=HTTP_201_CREATED)
            else:
                return JSONResponse(serializer.errors,
                                    status=HTTP_400_BAD_REQUEST)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except Exception as e:
            print e
            return JSONResponse("Error", status=HTTP_400_BAD_REQUEST)
Exemplo n.º 27
0
 def post(self, request, service_key):
     """ Creates a service request
      ---
      request_serializer: ServiceRequestSerializer
      response_serializer: ServiceRequestSerializer
     """
     # Request Post, create a service data
     # for e.g. an offer, a notification etc.
     try:
         tm = datetime.now()
         serializer = ServiceRequestSerializer(data=request.data)
         if serializer.is_valid(raise_exception=True):
             svc = UserService.objects.get(id=service_key)
             # deliver the service, delegate to service manager
             session_mgr.servicemanager.handle_service_request(
                 svc,
                 JSONRenderer().render(serializer.data['service_meta']))
             return JSONResponse(serializer.data, status=HTTP_201_CREATED)
         else:
             return JSONResponse(serializer.errors,
                                 status=HTTP_400_BAD_REQUEST)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 28
0
 def post(self, request, source_type, source_id):
     """ Sets and Returns current feed statistics tags for
     Media instance identified by Id.
      ---
      response_serializer: OOHOperationalDailyDataFeedSerializer
     """
     try:
         auth_manager.do_auth(request)
         if id is not None:
             if source_type == 'ooh':
                 source = OOHMediaSource.objects.get(id=source_id)
                 serializer = OOHOperationalDailyDataFeedSerializer(
                     data=request.data, many=True)
                 # Save the data feed record
                 if serializer.is_valid(raise_exception=True):
                     serializer.save(source_ref=source)
                     return JSONResponse(str('success'),
                                         status=HTTP_201_CREATED)
             elif source_type == 'digitalmedia':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
             elif source_type == 'vod':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
             elif source_type == 'radio':
                 return JSONResponse(str('not implemented'),
                                     status=HTTP_501_NOT_IMPLEMENTED)
     except UserNotAuthorizedException as e:
         print e
         return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
     except DoesNotExist as e:
         print e
         return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
     except Exception as e:
         print e
         return JSONResponse(str(e), status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 29
0
    def post(self, request, campaign_id, ad_id=None):
        """ Creates an image ad for a campaign
         ---
         request_serializer: ImageAdSerializer
         response_serializer: ImageAdSerializer
        """

        # curl -X POST -S -H 'Accept: application/json'\
        # -F "image=@/home/sonu/adimages/chineese_ad.jpg;type=image/jpg"\
        # http://127.0.0.1:8000/mediacontent/ads/imageads/566c580f1d41c8a69d0a063d/

        # Request put an Image Ad for already created
        # campaign
        try:
            auth_manager.do_auth(request)
            camp = Campaign.objects.get(id=campaign_id)
            if camp:
                # Check if an update is triggered
                if ad_id is not None:
                    ad = ImageAd.objects.get(id=ad_id)
                    return self._update(request, ad)

                img = None
                img_url = None
                offer = None
                social = None
                # Store image'
                if "image" in request.data:
                    imageserializer = ImageContentSerializer(
                        data=request.data["image"])
                    if imageserializer.is_valid(raise_exception=True):
                        img = imageserializer.save()
                        img_url = img.get_absolute_url()
                serializer = ImageAdSerializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    # Add other elements
                    if "offerex" in request.data:
                        #
                        #
                        #
                        #
                        # Extensions are stored and updated
                        offer = OfferExtensionSerializer(
                            data=request.data["offerex"], many=True)
                        if offer.is_valid(raise_exception=True):
                            offer = offer.save()
                    if "socialex" in request.data:
                        #
                        #
                        #
                        #
                        # Extensions are stored and updated
                        s_ex = SocialMediaExtensionSerializer(
                            data=request.data["socialex"], many=True)
                        if s_ex.is_valid(raise_exception=True):
                            social = s_ex.save()

                    ad = serializer.save(image_content=img, image_url=img_url)
                    ad.update(offerex=offer, socialex=social, campaign=camp)
                    # Successful
                    return JSONResponse(serializer.data,
                                        status=HTTP_201_CREATED)
                return JSONResponse("Unknown error processing %s (%s) ." %
                                    (campaign_id, serializer.errors),
                                    status=HTTP_400_BAD_REQUEST)
        except DoesNotExist as e:
            print e
            return JSONResponse(str(e), status=HTTP_404_NOT_FOUND)
        except UserNotAuthorizedException as e:
            print e
            return JSONResponse(str(e), status=HTTP_401_UNAUTHORIZED)
        except Exception as e:
            print e
            return JSONResponse("Campaign with Id (%s) not found." %
                                campaign_id,
                                status=HTTP_404_NOT_FOUND)
Exemplo n.º 30
0
    def post_update(self, userobj, request):

        project_id = role = device_pref = personal_pref = media_pref = None
        loc_pref = None
        ser = None
        try:
            # Construct the objects
            if "project" in request.data:
                projserializer = ProjectSerializer(
                    data=request.data["project"], partial=True)
                if projserializer.is_valid(raise_exception=True):
                    if userobj.project_id:
                        project_id = projserializer.update(
                            userobj.project_id, projserializer.validated_data)
                    else:
                        project_id = projserializer.save()
                        userobj.project_id = project_id
            if "role" in request.data:
                roleserializer = UserRoleSerializer(data=request.data["role"],
                                                    partial=True)
                if roleserializer.is_valid(raise_exception=True):
                    if userobj.role:
                        role = roleserializer.update(
                            userobj.role, roleserializer.validated_data)
                    else:
                        role = roleserializer.save()
                        userobj.role = role

            if "device_pref" in request.data:
                devserializer = UserDevicePrefSerializer(
                    data=request.data["device_pref"], partial=True, many=True)
                if devserializer.is_valid(raise_exception=True):
                    device_pref = devserializer.save()
                    userobj.device_pref = device_pref

            if "personal_pref" in request.data:
                personalserializer = UserPersonalPrefSerializer(
                    data=request.data["personal_pref"],
                    partial=True,
                    many=True)
                if personalserializer.is_valid(raise_exception=True):
                    personal_pref = personalserializer.save()
                    userobj.personal_pref = personal_pref

            if "media_pref" in request.data:
                mediaserializer = UserMediaPrefSerializer(
                    data=request.data["media_pref"], partial=True, many=True)
                if mediaserializer.is_valid(raise_exception=True):
                    media_pref = mediaserializer.save()
                    userobj.media_pref = media_pref

            if "loc_pref" in request.data:
                locserializer = UserLocationPrefSerializer(
                    data=request.data["loc_pref"], partial=True, many=True)
                if locserializer.is_valid(raise_exception=True):
                    loc_pref = locserializer.save()
                    userobj.loc_pref = loc_pref

            if "user" in request.data:
                userserializer = UserSerializer(data=request.data["user"],
                                                partial=True)
                if userserializer.is_valid(raise_exception=True):
                    user = userserializer.update(userobj,
                                                 userserializer.validated_data)
                    # update django auth
                    auth_manager.do_update(request, user.username,
                                           user.password)
            userobj.save(last_updated=datetime.now(),
                         last_activity=datetime.now())
            ret_data = UserSerializer(userobj)
            # Updated User successfully.
            return JSONResponse(ret_data.data, status=HTTP_200_OK)
        except Exception as e:
            print e
            return JSONResponse(str(e), status=HTTP_304_NOT_MODIFIED)