Exemple #1
0
    def _fetch_channel(self, **params):
        if 'channel_id' not in params:
            raise exc.ResourceDoesNotExist(
                "The 'channel_id' parameter is required")
        channel_id = params['channel_id']

        try:
            self.channel = Channel.objects.get(channel_id)
        except Channel.DoesNotExist:
            raise exc.ResourceDoesNotExist(
                "No channel with id='%s' exists in the system." % channel_id)
Exemple #2
0
 def _search(self, user, *args, **kwargs):
     error_desc = "Requests should contain a channel id and some query text: {'channel': <>, 'query': <>}"
     required_params = ['channel', 'query']
     LOGGER.debug('Searching for FAQs with params: %s' % kwargs)
     for entry in required_params:
         if entry not in kwargs:
             error_msg = "Missing required parameter '%s'" % entry
             raise exc.InvalidParameterConfiguration(error_msg,
                                                     description=error_desc)
     try:
         channel = Channel.objects.get(kwargs['channel'])
     except Channel.DoesNotExist:
         raise exc.ResourceDoesNotExist(
             "No channel with id=%s found in the system." %
             kwargs['channel'])
     result = FAQ.objects.text_search(channel, kwargs['query'], limit=100)
     LOGGER.debug('Search results for FAQs: %s' % result)
     from solariat.utils.timeslot import parse_datetime, now
     _created = parse_datetime(kwargs.get('_created', now()), default=now())
     faq_event = FAQQueryEvent.objects.create_by_user(user,
                                                      query=kwargs['query'],
                                                      channels=[channel.id],
                                                      _created=_created)
     if 'customer_id' in kwargs:
         CustomerProfile = user.account.get_customer_profile_class()
         customer = CustomerProfile.objects.get(kwargs['customer_id'])
         # import ipdb
         # ipdb.set_trace()
         # actions = NextBestActionEngine.upsert(account_id=customer.account_id).search(faq_event, customer)
         # TODO: THink how we can implement this properly with new advisors API
         return dict(list=result,
                     event=faq_event.to_dict())  #, actions=actions)
     else:
         return dict(list=result, event=faq_event.to_dict())
    def _preprocess_params(self, user, **kwargs):
        if 'channel_id' not in kwargs:
            raise exc.InvalidParameterConfiguration(
                "Required parameter 'Perform' missing.")

        if 'content' not in kwargs and 'post_id' not in kwargs:
            raise exc.InvalidParameterConfiguration(
                "Either parameter 'content' or 'post_id' required in POST fields."
            )

        try:
            self.channel = Channel.objects.get(kwargs['channel_id'])
        except Channel.DoesNotExist:
            raise exc.ResourceDoesNotExist("No channel found with id=%s" %
                                           kwargs['channel_id'])

        if kwargs.get('post_id', False):
            post = Post.objects.get(kwargs['post_id'])
        elif kwargs.get('content', False):
            target_channel = self.channel.id if not isinstance(self.channel, SmartTagChannel) else \
                             self.channel.parent_channel
            post = factory_by_user(user,
                                   channels=[target_channel],
                                   content=kwargs['content'])
        else:
            raise Exception("Either post_id or content should be passed")
        return post
Exemple #4
0
    def get_subscription(self, user, params):
        id_ = params.get('_id', params.get('id'))
        try:
            subscription = BaseHistoricalSubscription.objects.get(id_)
        except BaseHistoricalSubscription.DoesNotExist:
            raise exc.ResourceDoesNotExist(
                "No subscription exists with id=%s" % id_)

        channel = subscription.channel
        if not channel:
            raise exc.ResourceDoesNotExist(
                "There is no channel for this subscription")

        if not channel.can_edit(user):
            raise exc.AuthorizationError(
                "User %s does not have access to subscription %s." %
                (user.email, subscription))
        return subscription
Exemple #5
0
    def dispatch_request(self, user, platform=None, name=None, **kwargs):
        """ Perform the RPC command by the platform and command name"""
        if not platform:
            raise exc.ResourceDoesNotExist("A 'platform' parameter is required")
        if not name:
            raise exc.ResourceDoesNotExist("A 'name' parameter is required")
        if platform not in TASK_MAPPING:
            raise exc.InvalidParameterConfiguration("Unsupported platform '{}'".format(platform))
        if name not in TASK_MAPPING[platform]:
            raise exc.InvalidParameterConfiguration("Unsupported {} command '{}'".format(platform, name))

        task = TASK_MAPPING[platform][name]
        data = _get_request_data()

        if 'media' in data and name in {'update_status', 'update_with_media', 'wall_post'}:
            data['media'] = make_temp_file(data['media'])

        #data = request.json
        executor = RPCTaskExecutor(task, platform, data)
        return dict(item=executor.execute())
Exemple #6
0
 def _get_doc_by_id(self, user, _id, format_docs=True, **kwargs):
     """ Fetch a single document from the collection.
     :param user: The authorized user
     :param _id:  The document id
     :return: Document dict"""
     try:
         doc = self.model.objects.get_by_user(user, _id)
     except self.model.DoesNotExist:
         raise api_exc.ResourceDoesNotExist("The requested resource does not exist in collection '{}'".format(self._model_name))
     else:
         if format_docs:
             return self._format_single_doc(doc)
         return doc
Exemple #7
0
    def get_channel(self, user, params):
        channel_id = params.get('channel', params.get('channel_id', None))
        try:
            channel = Channel.objects.get(channel_id)
        except Channel.DoesNotExist:
            raise exc.ResourceDoesNotExist("No channel exists for id=%s" %
                                           channel_id)

        if not channel.can_edit(user):
            # Access to create subscription is restricted to users with edit access on the channel
            exc_err = "User %s does not have access to create a new subscription for channel %s." % (
                user.email, channel)
            raise exc.AuthorizationError(exc_err)
        return channel
Exemple #8
0
 def put(self, user, *args, **kwargs):
     if 'id' not in kwargs:
         raise exc.InvalidParameterConfiguration(
             "Need the id of the FAQ you want to update.")
     try:
         faq = FAQ.objects.get(kwargs['id'])
     except FAQ.DoesNotExist:
         raise exc.ResourceDoesNotExist("No FAQ with id=%s" % kwargs['id'])
     if 'question' in kwargs:
         faq.question = kwargs['question']
     if 'answer' in kwargs:
         faq.answer = kwargs['answer']
     faq.save()
     DbBasedSE1(faq.channel).compile_faqs()
     return dict(item=faq.to_dict())
Exemple #9
0
 def post(self, command=None, classifier_id=None, *args, **kwargs):
     if command in self.commands:
         if command == 'predict':
             return self.predict(*args, **kwargs)
         if command == 'train':
             return self.train(*args, **kwargs)
         if command == 'retrain':
             return self.retrain(*args, **kwargs)
         if command == 'reset':
             try:
                 instance = AuthTextClassifier.objects.get(classifier_id)
             except AuthTextClassifier.DoesNotExist:
                 raise exc.ResourceDoesNotExist(
                     "No classifier with id=%s found in the system." %
                     classifier_id)
             return self.reset(instance, *args, **kwargs)
     return self._post(*args, **kwargs)
Exemple #10
0
def get_outbound_channel(user, channel_id):
    try:
        service_channel = Channel.objects.get_by_user(user, channel_id)
        try:
            channel = service_channel.get_outbound_channel(user)
        except FacebookConfigurationException:
            # This is raised when we have multiple account channels
            # and none of them attached to the current service channel.
            # This is normal situation and we should not propagate the error.
            channel = None
        except TwitterConfigurationException as e:
            return jsonify(ok=False, error=unicode(e))
        channel_data = None
        if channel:
            channel_data = channel.to_dict()
            channel_data['is_authenticated'] = channel.is_authenticated
        return jsonify(ok=True, channel=channel_data)
    except Channel.DoesNotExist:
        raise exc.ResourceDoesNotExist("No channel with id='%s' exists in the system." % channel_id)
Exemple #11
0
    def get(self, user, _id=None, *args, **kwargs):
        """
        Handler for a specific get request On the SmartTag collection. Supports two types
        of requests, generic requests on the collection and specific item requests based on ids.

        Generic request example:
        ------------------------

            Sample request:
                curl http://staging.socialoptimizr.com/api/v2.0/smarttags?token={{your-token}}

            Parameters:
                :param token: <Required> - A valid user access token
                :param channel: <Optional> - If present should be the id of a channel from the system for which
                                             we want spart tags returned.

            Output:
                A dictionary in the form {'ok': true, 'list': [list of actual channel JSON's]}
                In case of no matched channels, list will be empty

            Sample response:
                HTTP-200
                {
                  "ok": true,
                  "list": [
                    {
                      "status": "Active",
                      "skipwords": [],
                      "usernames": [],
                      "description": null,
                      "title": "tag",
                      "influence_score": 0,
                      "uri": "http://127.0.0.1:3031/api/v2.0/smarttags/54119c5d31eddd1e7089dc40",
                      "watchwords": [],
                      "intentions": [],
                      "keywords": [],
                      "id": "54119c5d31eddd1e7089dc40"
                    }
                  ]
                }

        Specific request example:
        -------------------------

            Sample request:
                curl http://staging.socialoptimizr.com/api/v2.0/channels?token={{your-token}}&id={{channel-id}}

            Parameters:
                :param token: <Required> - A valid user access token
                :param doc_id: <Required> - A document ID for a service channel

            Output:
                A dictionary in the fork {'ok': true, 'list': [list of actual channel JSON's]}
                In case of no matched channels, return a 404

            Sample responses:

                Valid Native Channel:
                    HTTP-200
                    {
                      "item": {
                        "status": "Active",
                        "skipwords": [],
                        "usernames": [],
                        "description": null,
                        "title": "tag",
                        "influence_score": 0,
                        "uri": "http://127.0.0.1:3031/api/v2.0/smarttags/54119c5d31eddd1e7089dc40",
                        "watchwords": [],
                        "intentions": [],
                        "keywords": [],
                        "id": "54119c5d31eddd1e7089dc40"
                      },
                      "ok": true
                    }


                Invalid Document Id:
                    HTTP-404
                    {
                      "code": 34,
                      "error": "There is no smart tag with id=invalid_id in the system."
                    }
        """
        if _id:
            # Specific GET by an id
            try:
                smart_tag = SmartTagChannel.objects.get_by_user(user, id=_id)
            except SmartTagChannel.DoesNotExist:
                raise exc.ResourceDoesNotExist(
                    "No smart tag with id=%s found in the system." % _id)
            return dict(ok=True, item=self._format_doc(smart_tag))
        else:
            # General fetch
            if 'channel' in kwargs:
                # We need a specific fetch based on channel
                try:
                    channel = Channel.objects.get_by_user(user,
                                                          id=kwargs['channel'])
                except Channel.DoesNotExist:
                    raise exc.ResourceDoesNotExist(
                        "No channel with id=%s found in the system." %
                        kwargs['channel'])
                smart_tag_list = channel.smart_tags
                return dict(
                    ok=True,
                    list=[self._format_doc(st) for st in smart_tag_list])
            else:
                # Just default so the general fetch
                smart_tag_list = SmartTagChannel.objects.find_by_user(
                    user, **kwargs)
            return dict(ok=True,
                        list=[self._format_doc(st) for st in smart_tag_list])