Beispiel #1
0
def get_custom_response_message(sender, xform, **kwargs):
    """
    This signal sends a custom response to xform submissions. 
    If the domain has one.
    """
    if xform.metadata and xform.metadata.userID:
        userID = xform.metadata.userID
        xmlns = xform.form.get('@xmlns')
        domain = xform.domain

        try:
            app = get_app(domain, xform.app_id)
        except Exception:
            app = Application.get_by_xmlns(domain, xmlns)

        if app and hasattr(app, 'langs'):
            try:
                lang = xform.openrosa_headers[OPENROSA_ACCEPT_LANGUAGE]
            except (AttributeError, KeyError):
                lang = "default"
            if lang == "default":
                lang = app.build_langs[0] if app.build_langs else None
            message = app.success_message.get(lang)
            if message:
                success_message = SuccessMessage(
                    message, userID, domain=domain,
                    tz=timedelta(hours=0)).render()
                return ReceiverResult(
                    xml.get_simple_response_xml(
                        success_message, nature=ResponseNature.SUBMIT_SUCCESS),
                    Certainty.STRONG)
Beispiel #2
0
 def fail_actions_and_respond(doc):
     response = HttpResponse(
         xml.get_simple_response_xml(
             message=doc.problem,
             nature=ResponseNature.SUBMIT_ERROR), 
         status=201)
     return response
Beispiel #3
0
def get_custom_response_message(sender, xform, **kwargs):
    """
    This signal sends a custom response to xform submissions. 
    If the domain has one.
    """
    if xform.metadata and xform.metadata.userID:
        userID = xform.metadata.userID
        xmlns = xform.form.get("@xmlns")
        domain = xform.domain

        try:
            app = get_app(domain, xform.app_id)
        except Exception:
            app = Application.get_by_xmlns(domain, xmlns)

        if app and hasattr(app, "langs"):
            try:
                lang = xform.openrosa_headers[OPENROSA_ACCEPT_LANGUAGE]
            except (AttributeError, KeyError):
                lang = "default"
            if lang == "default":
                lang = app.build_langs[0] if app.build_langs else None
            message = app.success_message.get(lang)
            if message:
                success_message = SuccessMessage(message, userID, domain=domain, tz=timedelta(hours=0)).render()
                return ReceiverResult(
                    xml.get_simple_response_xml(success_message, nature=ResponseNature.SUBMIT_SUCCESS), Certainty.STRONG
                )
Beispiel #4
0
 def error_callback(error_log):
     error_doc = SubmissionErrorLog.get(error_log.get_id)
     _attach_shared_props(error_doc)
     submission_error_received.send(sender="receiver", xform=error_doc)
     error_doc.save()
     return HttpResponseServerError(
         xml.get_simple_response_xml(
             message="The sever got itself into big trouble! Details: %s" % error_log.problem,
             nature=ResponseNature.SUBMIT_ERROR)) 
Beispiel #5
0
    def success_actions_and_respond(self, doc):
        feedback = successful_form_received.send_robust(sender='receiver', xform=doc)
        responses = []
        errors = []
        for func, resp in feedback:
            if resp and isinstance(resp, Exception):
                error_message = unicode(resp)
                # hack to log exception type (no valuable stacktrace though)
                try:
                    raise resp
                except Exception:
                    logging.exception((
                        u"Receiver app: problem sending "
                        u"post-save signal %s for xform %s: %s"
                    ) % (func, doc._id, error_message))
                errors.append(error_message)
            elif resp and isinstance(resp, ReceiverResult):
                responses.append(resp)

        if errors:
            # in the event of errors, respond with the errors, and mark the problem
            doc.problem = ", ".join(errors)
            doc.save()
            response = HttpResponse(
                xml.get_simple_response_xml(
                    message=doc.problem,
                    nature=ResponseNature.SUBMIT_ERROR,
                ),
                status=201,
            )
        elif responses:
            # use the response with the highest priority if we got any
            responses.sort()
            response = HttpResponse(responses[-1].response, status=201)
        else:
            # default to something generic
            response = HttpResponse(
                xml.get_simple_response_xml(
                    message="Success! Received XForm id is: %s\n" % doc['_id'],
                    nature=ResponseNature.SUBMIT_SUCCESS,
                ),
                status=201,
            )
        return response
Beispiel #6
0
def generate_restore_response(user, restore_id="", version="1.0", state_hash=""):
    try:
        response = generate_restore_payload(user, restore_id, version, state_hash)
        return HttpResponse(response, mimetype="text/xml")
    except BadStateException, e:
        logging.exception("Bad case state hash submitted by %s: %s" % (user.username, str(e)))
        response = get_simple_response_xml(
            "Phone case list is inconsistant with server's records.",
            ResponseNature.OTA_RESTORE_ERROR)
        return HttpResponse(response, mimetype="text/xml", 
                            status=412) # precondition failed
    def setUp(self):
        create_domain(self.domain)
        couch_user = CommCareUser.create(self.domain, self.username, self.password)
        userID = couch_user.user_id
        couch_user.first_name = self.first_name
        couch_user.last_name = self.last_name
        couch_user.save()
        self.sm = SuccessMessage(self.message, userID, tz=self.tz)

        c = Client()

        app = Application.new_app(self.domain, "Test App", application_version=APP_V1)
        app.add_module(Module.new_module("Test Module", "en"))
        form = app.new_form(0, "Test Form", "en")
        form.xmlns = self.xmlns
        app.success_message = {"en": self.message}
        app.save()

        def fake_form_submission(userID=userID, username=self.username, xmlns=self.xmlns, time=None):
            submission = submission_template % {
                "userID": userID,
                "username": username,
                "xmlns": xmlns
            }
            f = StringIO(submission.encode('utf-8'))
            f.name = "tempfile.xml"
            kwargs = dict(HTTP_X_SUBMIT_TIME=json_format_datetime(time)) if time else {}
            response = c.post("/a/{self.domain}/receiver/".format(self=self), {
                'xml_submission_file': f,
            }, **kwargs)
            return response

        self.num_forms_today = 0
        self.num_forms_this_week = 0
        now = datetime.utcnow()
        tznow = now + self.tz
        week_start = tznow - timedelta(days=tznow.weekday())
        week_start = datetime(week_start.year, week_start.month, week_start.day) - self.tz
        day_start = datetime(tznow.year, tznow.month, tznow.day) - self.tz
        spacing = 6
        for h in xrange((24/spacing)*8):
            time = now-timedelta(hours=spacing*h)
            response = fake_form_submission(time=time)
            if time > week_start:
                self.num_forms_this_week += 1
            if time > day_start:
                self.num_forms_today += 1
            self.assertEqual(
                response.content,
                get_simple_response_xml(("Thanks {self.first_name} ({self.first_name} {self.last_name})! "
                "You have submitted {self.num_forms_today} forms today "
                "and {self.num_forms_this_week} forms since Monday.").format(self=self),
                    nature=ResponseNature.SUBMIT_SUCCESS)
            )
Beispiel #8
0
def send_default_response(sender, xform, **kwargs):
    """
    This signal just sends a default response to xform submissions.
    """
    
    def forms_submitted_count(user):
        forms_submitted = get_db().view("couchforms/by_user", 
                                        startkey=[user], 
                                        endkey=[user, {}]).one()
        return forms_submitted["value"] if forms_submitted else "at least 1"
    
    def forms_submitted_today_count(user):
        today = datetime.today()
        startkey = [user, today.year, today.month - 1, today.day]
        endkey = [user, today.year, today.month - 1, today.day, {}]
        forms_submitted_today = get_db().view("couchforms/by_user", 
                                              startkey=startkey, 
                                              endkey=endkey).one()
        return forms_submitted_today["value"] if forms_submitted_today else "at least 1"
        
    if xform.metadata and xform.metadata.userID:
        if xform.metadata.username == "demo_user":
            message = "Thanks for submitting from demo mode!"
        else: 
            to = ", %s" % xform.metadata.username if xform.metadata.username else ""
            message = ("Thanks for submitting%s.  We have received %s forms from "
                       "you today (%s forms all time)") % \
                       (to,
                        forms_submitted_today_count(xform.metadata.userID), 
                        forms_submitted_count(xform.metadata.userID))
        return ReceiverResult(xml.get_simple_response_xml(
            message, nature=ResponseNature.SUBMIT_SUCCESS), Certainty.MILD)
            
    else:
        return ReceiverResult(xml.get_simple_response_xml(
            "Thanks for submitting!", ResponseNature.SUBMIT_SUCCESS), 
            Certainty.MILD)
Beispiel #9
0
 def success_actions_and_respond(doc):
     feedback = successful_form_received.send_robust(sender="receiver", xform=doc)
     responses = []
     errors = []
     for func, resp in feedback:
         if resp and isinstance(resp, Exception):
             # hack: get stack traces and types and such through this process
             try:
                 raise resp
             except Exception:
                 logging.exception("Receiver app: problem sending post-save signal %s for xform %s: %s" \
                                   % (func, doc._id, str(resp)))
             errors.append(str(resp))
         elif resp and isinstance(resp, ReceiverResult):
             responses.append(resp)
     if errors:
         # in the event of errors, respond with the errors, and mark the problem
         doc.problem = ", ".join(errors)
         doc.save()
         response = HttpResponse(
             xml.get_simple_response_xml(
                 message=doc.problem, 
                 nature=ResponseNature.SUBMIT_ERROR), 
             status=201)
     elif responses:
         # use the response with the highest priority if we got any
         responses.sort()
         response = HttpResponse(responses[-1].response, status=201)
     else:
         # default to something generic 
         response = HttpResponse(
             xml.get_simple_response_xml(
                 message="Success! Received XForm id is: %s\n" % doc['_id'],
                 nature=ResponseNature.SUBMIT_SUCCESS), 
             status=201)
     return response
Beispiel #10
0
    def setUp(self):
        couch_user = CommCareUser.create(self.domain, self.username,
                                         self.password)
        userID = couch_user.user_id
        couch_user.first_name = self.first_name
        couch_user.last_name = self.last_name
        couch_user.save()
        self.sm = SuccessMessage(self.message, userID, tz=self.tz)

        c = Client()

        app = Application.new_app(self.domain,
                                  "Test App",
                                  application_version=APP_V1)
        app.new_module("Test Module", "en")
        form = app.new_form(0, "Test Form", "en")
        form.xmlns = self.xmlns
        app.success_message = {"en": self.message}
        app.save()

        def fake_form_submission(userID=userID,
                                 username=self.username,
                                 xmlns=self.xmlns,
                                 time=None):
            submission = submission_template % {
                "userID": userID,
                "username": username,
                "xmlns": xmlns
            }
            f = StringIO(submission.encode('utf-8'))
            f.name = "tempfile.xml"
            kwargs = dict(
                HTTP_X_SUBMIT_TIME=json_format_datetime(time)) if time else {}
            response = c.post("/a/{self.domain}/receiver/".format(self=self), {
                'xml_submission_file': f,
            }, **kwargs)
            return response

        self.num_forms_today = 0
        self.num_forms_this_week = 0
        now = datetime.utcnow()
        tznow = now + self.tz
        week_start = tznow - timedelta(days=tznow.weekday())
        week_start = datetime(week_start.year, week_start.month,
                              week_start.day) - self.tz
        day_start = datetime(tznow.year, tznow.month, tznow.day) - self.tz
        spacing = 6
        for h in xrange((24 / spacing) * 8):
            time = now - timedelta(hours=spacing * h)
            response = fake_form_submission(time=time)
            if time > week_start:
                self.num_forms_this_week += 1
            if time > day_start:
                self.num_forms_today += 1
            self.failUnlessEqual(
                response.content,
                get_simple_response_xml((
                    "Thanks {self.first_name} ({self.first_name} {self.last_name})! "
                    "You have submitted {self.num_forms_today} forms today "
                    "and {self.num_forms_this_week} forms since Monday."
                ).format(self=self),
                                        nature=ResponseNature.SUBMIT_SUCCESS))